Search is not available for this dataset
query
stringlengths
7
355k
document
stringlengths
9
341k
metadata
dict
negatives
listlengths
0
101
negative_scores
listlengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
=========================== 7. Validate forms ==========================
function validateFormCons2() { var name = document.forms["cons2"]["name"].value; var phone = document.forms["cons2"]["phone"].value; if (name == "") { alert("Заполните Имя"); return false; } if (phone == "") { alert("Заполните Телефон"); return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isValidForm() {\n var mainTextValid = isValidRequiredTextAreaField(\"main_text\");\n var articleKeywordCategoryValid = isValidRequiredField(\"article_keyword_category\");\n var articleKeywordsValid = isValidRequiredKeywordsField(\"article_keywords\");\n var originalSourceURLValid = isValidUrlField(\"original_source_url\");\n return isValidPartialForm() && mainTextValid && articleKeywordCategoryValid && articleKeywordsValid && originalSourceURLValid;\n}", "function formValidate(form) {\n function camelCase(string) {\n string = string||'';\n string = string.replace(/\\(|\\)/,'').split(/-|\\s/);\n var out = [];\n for (var i = 0;i<string.length;i++) {\n if (i<1) {\n out.push(string[i].toLowerCase());\n } else {\n out.push(string[i][0].toUpperCase() + string[i].substr(1,string[i].length).toLowerCase());\n }\n }\n return out.join('');\n }\n\n function nullBool(value) {\n return (value);\n }\n\n function getGroup(el) {\n return {\n container: el.closest('.form-validate-group'),\n label: $('[for=\"' + el.attr('id') + '\"]'),\n prompt: el.closest('.form-validate-group').find('.form-validate-prompt')\n }\n }\n\n function isValid(el) {\n function getType() {\n var attr = camelCase(el.attr('id')).toLowerCase();\n var tag = (el.attr('type') === 'checkbox') ? 'checkbox' : el[0].tagName.toLowerCase();\n function type() {\n var _type = 'text';\n if (attr.match(/zip(code|)/)) {\n _type = 'zipCode';\n } else if (attr.match(/zippostal/)) {\n _type = 'zipPostal';\n } else if (attr.match(/(confirm|)(new|old|current|)password/)) {\n _type = 'password'\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)email/)) {\n _type = 'email';\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)(phone)(number|)/)) {\n _type = 'phone';\n } else if (attr.match(/merchantid/)) {\n _type = 'merchantId';\n } else if (attr.match(/marketplaceid/)) {\n _type = 'marketplaceId';\n } else if (attr.match(/number/)) {\n _type = 'number';\n }\n return _type;\n }\n if (tag === 'input' || tag === 'textarea') {\n return type();\n } else {\n return tag;\n }\n } // Get Type\n var string = el.val()||'';\n var exe = {\n text: function () {\n return (string.length > 0);\n },\n password: function () {\n return (string.length > 6 && nullBool(string.match(/^[\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)a-zA-Z0-9_-]+$/)));\n },\n zipCode: function () {\n return (nullBool(string.match(/^[0-9]{5}$/)));\n },\n zipPostal: function () {\n return (nullBool(string.match(/^([0-9]{5}|[a-zA-Z][0-9][a-zA-Z](\\s|)[0-9][a-zA-Z][0-9])$/)));\n },\n email: function () {\n return (nullBool(string.match(/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\\.([a-z]{2}|[a-z]{3})/)));\n },\n merchantId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n return ((match) && (match[0].length > 9 && match[0].length < 22));\n },\n marketplaceId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n var length = {'United States of America':13}[region()];\n return ((match) && (match[0].length === length));\n },\n select: function () {\n return (el[0].selectedIndex > 0);\n },\n checkbox: function () {\n return el[0].checked;\n },\n phone: function () {\n return (nullBool(string.replace(/\\s|\\(|\\)|\\-/g,'').match(/^([0-9]{7}|[0-9]{10})$/)));\n },\n number: function () {\n return nullBool(string.match(/^[0-9\\.\\,]+$/));\n }\n }\n return exe[getType()]();\n }; // contentsValid\n\n return {\n confirm: function (el) {\n\n function condition(el) {\n var bool = dingo.get(el).find('form-validate').condition||false;\n if (bool && el.val().length > 0) {\n return el;\n } else {\n return false;\n }\n }\n\n function dependency(el) {\n // Needs to use recursion to climb the dependency tree to determine whether or not\n // the element is dependent on anything\n var dep = $('#' + dingo.get(el).find('form-validate').dependency);\n if (dep.size() > 0) {\n return dep;\n } else {\n return false;\n }\n }\n\n function confirm(el) {\n var match = $('#' + dingo.get(el).find('form-validate').confirm);\n if (match.size()) {\n return match;\n } else {\n return false;\n }\n }\n\n function normal(el) {\n var check = dingo.get(el).find('form-validate');\n var out = true;\n var attr = ['condition','dependency','confirm'];\n $.each(attr,function (i,k) {\n if (typeof check[k] === 'string' || check[k]) {\n out = false;\n }\n });\n return out;\n }\n\n function validate(el) {\n var group = getGroup(el);\n function exe(el,bool) {\n if (bool) {\n el.removeClass('_invalid');\n group.label.addClass('_fulfilled');\n animate(group.prompt).end();\n group.prompt.removeClass('_active');\n } else {\n el.addClass('_invalid');\n group.label.removeClass('_fulfilled');\n }\n }\n return {\n condition: function () {\n exe(el,isValid(el));\n },\n dependency: function (match) {\n if (normal(match) || condition(match)) {\n exe(el,isValid(el));\n }\n },\n confirm: function (match) {\n if (el.val() === match.val()) {\n exe(el,true);\n } else {\n exe(el,false);\n }\n },\n normal: function () {\n exe(el,isValid(el));\n }\n }\n }\n\n if (condition(el)) {\n validate(el).condition();\n } else if (dependency(el)) {\n validate(el).dependency(dependency(el));\n } else if (confirm(el)) {\n validate(el).confirm(confirm(el));\n } else if (normal(el)) {\n validate(el).normal();\n }\n },\n get: function () {\n return form.find('[data-dingo*=\"form-validate\"]').not('[data-dingo*=\"form-validate_submit\"]');\n },\n init: function (base, confirm) {\n if (el.size() > 0) {\n parameters.bool = bool;\n formValidate(el).fufilled();\n return formValidate(el);\n } else {\n return false;\n }\n },\n is: function () {\n return (form.find('.form-validate').size() < 1);\n },\n check: function () {\n var el;\n formValidate(form).get().each(function () {\n formValidate(form).confirm($(this));\n });\n return form.find('._invalid');\n },\n submit: function (event) {\n var out = true;\n var requiredField = formValidate(form).check();\n if (requiredField.size() > 0) {\n requiredField.each(function () {\n var group = getGroup($(this));\n group.prompt.addClass('_active');\n group.prompt.css('top',group.container.outerHeight() + 'px');\n if (typeof animate === 'function') {\n animate(group.prompt).start();\n }\n })\n if (requiredField.eq(0).closest('[class*=\"modal\"]').size() < 1) {\n if (typeof animate === 'function') {\n if (!dingo.isMobile()) { \n animate(requiredField.eq(0)).scroll(); \n }\n }\n requiredField.eq(0).focus();\n }\n out = false;\n }\n return out;\n }\n }\n}", "function validateForm() {\n validateFirstName();\n validateLastName();\n validateStreet();\n validateCity();\n validateZipCode();\n}", "function validate_form(){\n if (is_form_valid(form)) {\n sendForm()\n }else {\n let $el = form.find(\".input:invalid\").first().parent()\n focus_step($el)\n }\n }", "function verifyForm()\n{\n valid = true;\n validFields.forEach(function(element) { valid &= element });\n changeFormState(valid);\n}", "function validateForm() {\n\t\n\tvar error = 0;\n\t$('input').each(function(x,y) {\n\t\tvar val = $(y).val();\n\t\tif(!validate(y.name, val)) {\n\t\t\t$(y).css('border', 'solid 1px red')\n\t\t\terror = 1;\n\t\t} else {\n\t\t\t$(y).css('border', 'solid 1px 888');\n\t\t}\n\t});\n\t\n\t$('textarea').each(function(x,y) {\n\t\tvar val = $(y).val();\n\t\tif(!validate(y.name, val)) {\n\t\t\t$(y).css('border', 'solid 1px red')\n\t\t\terror = 1;\n\t\t} else {\n\t\t\t$(y).css('border', 'solid 1px 888');\n\t\t}\n\t});\n\t\n\tif(error === 1) {\n\t\treturn false;\n\t}\n}", "function isAddFormValid(){\r\n return( FNameField.isValid() && LNameField.isValid() && TitleField.isValid()&& AddField.isValid() && MailField.isValid() && TelephoneField.isValid() && MobileField.isValid());\r\n }", "function validateForm() {\n return name.length > 0 && phone.length > 0;\n }", "function validateForm() {\n\t\tvar fieldsWithIllegalValues = $('.illegalValue');\n\t\tif (fieldsWithIllegalValues.length > 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tkenyaui.clearFormErrors('htmlform');\n\n\t\tvar ary = $(\".autoCompleteHidden\");\n\t\t$.each(ary, function(index, value) {\n\t\t\tif (value.value == \"ERROR\"){\n\t\t\t\tvar id = value.id;\n\t\t\t\tid = id.substring(0, id.length - 4);\n\t\t\t\t$(\"#\" + id).focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\n\t\tvar hasBeforeSubmitErrors = false;\n\n\t\tfor (var i = 0; i < beforeSubmit.length; i++){\n\t\t\tif (beforeSubmit[i]() === false) {\n\t\t\t\thasBeforeSubmitErrors = true;\n\t\t\t}\n\t\t}\n\n\t\treturn !hasBeforeSubmitErrors;\n\t}", "function validateForm() {\n\n\tvar valid = true;\n\n\tif (!validateField(\"firstname\"))\n\t\tvalid = false;\n\n\tif (!validateField(\"lastname\"))\n\t\tvalid = false;\n\n\tif (!checkPasswords())\n\t\tvalid = false;\n\n\tif (!checkEmail())\n\t\tvalid = false;\n\n\tif (valid)\n\t\tsubmitForm();\n\n\t// Return false to make sure the HTML doesn't try submitting anything.\n\t// Submission should happen via javascript.\n\treturn false;\n}", "function validateForm() {\n\t\tvar $fields = $(\".form-control:visible\");\n\t\tvar $thisStep = $('.formPaso-stepper:visible');\n\t\tvar $nextStep = $thisStep.attr('data-nextStep');\n\t\tvar $filledFields = $fields.find('input[value!=\"\"]');\n\t\tvar $emptyFields = $fields.filter(function() {\n\t \treturn $.trim(this.value) === \"\";\n\t });\n \tfunction continueForm() {\n\t \t// apaga stepper\n\t \t// $('#stepper_portabilidad li').removeClass('active');\n\t \t// prende stepper correcto\n\t \t$('#stepper_portabilidad li.stepperLED-' + $nextStep).addClass('active');\n\t \t// deshabilita este boton\n\t \t$($thisStep).find('.nextStep').addClass('disabled');\n\t \t// oculta este paso\n\t \t$($thisStep).slideUp('1200');\n\t \t// muestra el paso siguiente\n\t \t$('#portateForm-' + $nextStep).slideDown('1200');\n\t \t// habilita el boton a paso siguiente\n\t \t$('#portateForm-' + $nextStep).find('.nextStep').removeClass('disabled');\n\t \t// anima el DOM hasta el stepper\n\t \t$('html, body').animate({scrollTop: $(\"#stepper_portabilidad\").offset().top - 30}, 500);\n\t\t // cancela form button\n\t \treturn false;\n\t }\n\t\tif (!$emptyFields.length) {\n\t\t\t// if form is ok...\n\t\t\t$('#camposvacios').slideUp();\n\t\t\tcontinueForm();\n\t\t} else {\n\t\t console.log($emptyFields);\n\t\t $emptyFields.parents('.form-group').addClass('invalidInput').removeClass('input-effect');\n\t\t $filledFields.addClass('totallyValidInput');\n\t\t console.log($filledFields);\n\t\t $('#camposvacios').slideToggle();\n\t\t $('html, body').animate({scrollTop: $(\"#camposvacios\").offset().top}, 200);\n\t\t}\n\t}", "function validateForm(){\n let errors = {};\n\n if (!formValue.firstName.trim()) {\n errors.firstName = 'First Name is required';\n }\n \n if (!formValue.lastName.trim()) {\n errors.lastName = 'Last Name is required';\n }\n \n if (!formValue.email) {\n errors.email = 'Email is required';\n } else if (!/^[\\w-.]+@([\\w-]+.)+[\\w-]{2,4}$/.test(formValue.email)) {\n errors.email = 'Email address is invalid';\n }\n setErrors(errors); \n }", "function ValidaForm() {\n if ($('#txtTitulo').val() == '') {\n showErrorMessage('El Título es obligatorio');\n return false;\n }\n if ($('#dpFechaEvento').val() == '') {\n showErrorMessage('La Fecha de publicación es obligatoria');\n return false;\n }\n if ($('#txtEstablecimiento').val() == '') {\n showErrorMessage('El Establecimiento es obligatorio');\n return false;\n }\n if ($('#txtDireccion').val() == '') {\n showErrorMessage('La Dirección es obligatoria');\n return false;\n }\n if ($('#txtPrecio').val() == '') {\n showErrorMessage('El Precio es obligatorio');\n return false;\n }\n return true;\n}", "function validateForm(){\n\t\n\tvar boo1 = validateLabPerson();\n\tvar boo2 = validateBioPerson();\n\tvar boo3 = validatePI();\n\tvar boo4 = validateBillTo();\n\tvar boo5 = validateRunType();\n\n\tvar boo6 = validateAllTables();\n//\tvar boo6 = true;\n\n\tvar boo7 = validateDate();\n\tvar boo8 = validateIAccept();\n\n\tvar boo9 = validateConcentrationUnit();\n\tvar boo10 = validateTubesAndLanes();\n\t\n//\talert(\"boo1 = \" + boo1 + \" boo2 = \" + boo2 + \" boo3 = \" + boo3 + \" boo4 = \" + boo4 +\" boo5 = \" + boo5 +\" boo6 = \" + boo6 + \" boo7 = \" + boo7 + \" boo8 = \" + boo8 + \" boo9 = \" + boo9 + \" boo10 = \" + boo10);\n\tif (boo1 && boo2 && boo3 && boo4 && boo5 && boo6 && boo7 && boo8 && boo9 && boo10){\t\n//\tif(validateLabPerson() && validateBioPerson() && validatePI() && validateBillTo() && validateRunType() && validateTable()){\n\t\t//insert fields used to generate csv\n\t\tinsertTableSize();\t\t\t\t\t// insert size of all table - used when generating csv file\n\t\tgenerateOrderNoteID();\t\t\t\t// insert orderNoteID\n\t\taddPI2TubeTag();\t\t\t\t\t// indsæt \"de tre tegn\" (fra PI) i tubetaggen.\n\t\tsetVersion();\t\t\t\t\t\t// insert the version number in the hidden field.\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n\t\n\treturn false;\n}", "function IsvalidForm() {\n ///Apply Bootstrap validation with Requird Controls in Input Form\n var result = jQuery('#InputForm').validationEngine('validate', { promptPosition: 'topRight: -20', validateNonVisibleFields: true, autoPositionUpdate: true });\n ///If all requird Information is Given\n if (result) {\n ///If all requird Information is Given then return true\n return true;\n }\n ///If all requird Information is Given then return false\n return false;\n}", "function validateForm() {\n return true;\n}", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst businessValue = business.value.trim();\n\tconst roleValue = role.value.trim();\n\tconst addressValue = address.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check business\n\tif (businessValue === \"\") {\n\t\tsetErrorFor(business, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(business);\n\t}\n\n\t// Check role\n\tif (roleValue === \"\") {\n\t\tsetErrorFor(role, \"Please select a role\");\n\t} else {\n\t\tsetSuccessFor(role);\n\t}\n\n\t// Check addresss\n\tif (addressValue === \"\") {\n\t\tsetErrorFor(address, \"Please enter a address\");\n\t} else {\n\t\tsetSuccessFor(address);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function validate_form() {\n valid = true;\n\n if (document.form.age.value == \"\") {\n alert(\"Please fill in the Age field.\");\n valid = false;\n }\n\n if (document.form.heightFeet.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.weight.value == \"\") {\n alert(\"Please fill in the Weight field.\");\n valid = false;\n }\n\n if (document.form.position.selectedIndex == 0) {\n alert(\"Please fill in the Position field.\");\n valid = false;\n }\n\n if (document.form.playingStyle.selectedIndex == 0) {\n alert(\"Please fill in the Playing Style field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Maximum Price field.\");\n valid = false;\n }\n\n return valid;\n}", "function validateForm() {\n isFormValid = true;\n\n validateName();\n validateEmail();\n validateDemand();\n validateOptions();\n\n if (isFormValid) {\n submit.disabled = false;\n } else {\n submit.disabled = true;\n\n }\n}", "function validateForm() {\n return fields.email.length > 0 && fields.password.length > 0;\n }", "function validation(form) {\n function isEmail(email) {\n return /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(\n email\n );\n }\n\n function isPostCode(postal) {\n if (\n /^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(\n postal\n ) ||\n /^\\d{5}$|^\\d{5}-\\d{4}$/.test(postal)\n )\n return true;\n else return false;\n }\n\n function isPhone(phone) {\n if (/^\\d{10}$/.test(phone)) return true;\n else return false;\n }\n\n function isPassword(password) {\n // Input Password and Submit [7 to 15 characters which contain only characters, numeric digits, underscore and first character must be a letter]</h2\n if (/^[A-Za-z]\\w{7,14}$/.test(password)) {\n return true;\n } else {\n return false;\n }\n }\n\n let isError = false;\n let password = '';\n\n validationFields.forEach((field) => {\n const isRequired =\n [\n 'firstName',\n 'LastName',\n 'email',\n 'address',\n 'postalCode',\n 'password',\n 'conPassword',\n ].indexOf(field) != -1;\n\n if (isRequired) {\n const item = document.querySelector('#' + field);\n\n if (item) {\n const value = item.value.trim();\n if (value === '') {\n setErrorFor(item, field + ' cannot be blank!');\n isError = true;\n } else if (field === 'email' && !isEmail(value)) {\n setErrorFor(item, 'Invalid Email Address!');\n isError = true;\n } else if (field === 'postalCode' && !isPostCode(value)) {\n setErrorFor(item, 'Invalid Postal Code!');\n isError = true;\n } else if (field === 'phone' && !isPhone(value)) {\n setErrorFor(item, 'Invalid Phone Number!');\n isError = true;\n } else if (field === 'password' && isPassword(value)) {\n setSuccessFor(item);\n password = value;\n } else if (field === 'password' && !isPassword(value)) {\n setErrorFor(\n item,\n ' Minimum 7 and Maximum 15 characters, numeric digits, underscore and first character must be a letter!'\n );\n isError = true;\n password = '';\n } else if (field === 'conPassword' && password !== value) {\n setErrorFor(item, 'Confirmation Password Not Match!');\n isError = true;\n } else {\n setSuccessFor(item);\n }\n }\n }\n });\n\n return isError === false;\n}", "function verifyFormData(form) {\n\t\n\tif (hasErrors) hasErrors = false;\n\t\n\tif (form == null) return false;\n\t\n\tvar elements = form.elements;\n\tif (elements.length == 0) return false;\n\t\n\tfor (var i = 0; i < elements.length; i++){\n\t\tvar element = elements[i];\n\t\t\n\t\t// checking text boxes \n\t\tif (element.tagName == \"INPUT\" && element.type && element.type == \"text\" && !element.optional) {\n\t\t\t\n\t\t\tif (element.value == null || element.value.trim() == \"\"){\n\t\t\t\t\n\t\t\t\thasErrors = true;\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\terror.style.display = \"block\";\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\terror.style.display = \"none\";\n\t\t\t}\n\t\t}\n\t\t\n\t\t// checking radio buttons\n\t\tif (element.tagName == \"INPUT\" && element.type && element.type == \"radio\" && !element.optional) {\n\t\t\t\n\t\t\tvar elementName = element.name;\n\t\t\tvar radioGroup = document.getElementsByName(elementName);\n\t\t\t\n\t\t\tif (radioGroup[0].checked == false && radioGroup[1].checked == false) {\n\t\t\t\t\n\t\t\t\thasErrors = true;\n\t\t\t\tvar error = document.getElementById(elementName);\n\t\t\t\terror.style.display = \"block\";\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tvar error = document.getElementById(elementName);\n\t\t\t\tif (error != null)\n\t\t\t\t\terror.style.display = \"none\";\n\t\t\t}\n\t\t}\n\t\t\n\t// checking text areas\n\t\tif (element.tagName == \"TEXTAREA\" && !element.optional) {\n\t\t\tif (element.value == null || element.value.trim() == \"\"){\n\t\t\t\t\n\t\t\t\thasErrors = true;\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\tif (error != null)\n\t\t\t\t\terror.style.display = \"block\";\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\tif (error != null)\n\t\t\t\t\terror.style.display = \"none\";\n\t\t\t}\n\t\t}\n\t\t\n\t\t// checking the drop down or select\n\t\tif (element.tagName == \"SELECT\" && !element.optional) {\n\t\t\tif (element.value == null || element.value.trim() == \"\"){\n\t\t\t\t\n\t\t\t\thasErrors = true;\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\tif (error != null)\n\t\t\t\t\terror.style.display = \"block\";\n\t\t\t}\n\t\t\t\n\t\t\telse {\n\t\t\t\tvar error = document.getElementById(element.name);\n\t\t\t\tif (error != null)\n\t\t\t\t\terror.style.display = \"none\";\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\t\n\tif (hasErrors == true){\n\t\tvar title = \"Fix Errors Before Continuing\";\n\t\tvar message = \"Oops, looks like you did not fill out the required fields, please go back to \" +\n\t\t \"the survey and fill them up.\";\n\t\tshowMessageBox(title, message);\n\t\treturn false;\n\t}\n\t\n\telse return true;\n}", "function validateForm () {\n const nameFieldDom = document.getElementById('name');\n const textFieldDom = document.getElementById('message');\n const checkboxDom = document.getElementById('isAttending');\n // console.log('Data within these fields is: ', nameFieldDom.value, textFieldDom.value);\n if (\n nameFieldDom.value.trim() == '' || \n textFieldDom.value.trim() == '' || \n textFieldDom.value.length <= 3 || \n nameFieldDom.value.length < 3\n ) return true;\n else return false;\n }", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst schoolValue = school.value.trim();\n\tconst levelValue = level.value.trim();\n\tconst skillValue = skill.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else if (isNaN(phoneValue)) {\n\t\tsetErrorFor(phone, \"Please enter a valid phone number\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check School\n\tif (schoolValue === \"\") {\n\t\tsetErrorFor(school, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(school);\n\t}\n\n\t// Check Level\n\tif (levelValue === \"\") {\n\t\tsetErrorFor(level, \"Please select a level\");\n\t} else {\n\t\tsetSuccessFor(level);\n\t}\n\n\t// Check LevSkills\n\tif (skillValue === \"\") {\n\t\tsetErrorFor(skill, \"Please enter a skill\");\n\t} else {\n\t\tsetSuccessFor(skill);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password2);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function getFormIsValid() {\n return interactedWith && !getFieldErrorsString()\n }", "function validateForm() {\n let validCandidates = 0;\n optionNames.forEach((e) => {\n if (e !== null || e !== undefined || e !== \"\") validCandidates += 1;\n });\n return validCandidates >= 2;\n }", "function validate(){\r\n\tvar validableForms = $(\".validableForm\");\r\n\tfor(var i=0;i<validableForms.length;i++){\r\n\t\t$(validableForms[i]).validationEngine({promptPosition : \"bottomLeft\"\r\n\t\t\t , scroll: false});\r\n\t}\r\n}", "function validateForm() {\n let res = true;\n //Valida cada uno de los campos por regex\n for (let key in regexList) {\n if (!evalRegex(key, document.forms[formName][key].value)) {\n setMsg(key, fieldList[key].error);\n res = false;\n } else setMsg(key, '');\n }\n\n //Valida la fecha de contrato\n if (!validateDate()) {\n setMsg('fechaContrato', fieldList['fechaContrato'].error);\n res = false;\n } else setMsg('fechaContrato', '');\n\n //Valida el salario introducido\n if (!validateSalary()) {\n setMsg('salario', fieldList['salario'].error);\n res = false;\n } else setMsg('salario', '');\n\n //Valida que la contraseña y la confirmacion sean iguales\n if (document.forms[formName]['passwordReply'].value != document.forms[formName]['password'].value) {\n setMsg('passwordReply', fieldList['passwordReply'].error);\n res = false;\n } else setMsg('passwordReply', '');\n\n //Valida si el usuario ya esta registrado\n if (validateUser(document.forms[formName]['usuario'].value)) {\n setMsg('usuario', 'El usuario ya ha sido registrado');\n res = false;\n }\n\n return res;\n}", "validateForm() {\n return this.state.serviceName.length > 0 && this.state.description.length > 0 && this.state.location.length > 0 && this.state.category.length > 0 && this.state.url.length > 0\n }", "validateForm() {\n\n const singer = this.shadowRoot.getElementById('singer');\n const song = this.shadowRoot.getElementById('song');\n const artist = this.shadowRoot.getElementById('artist');\n const link = this.shadowRoot.getElementById('link');\n\n if(singer && song && artist) {\n return (singer.value != '' && song.value != '' && artist.value != '');\n };\n\n return false;\n }", "function validateForm() {\r\n var newTitle = document.forms[\"validForm\"][\"btitle\"].value;\r\n var newOwner = document.forms[\"validForm\"][\"bowner\"].value;\r\n var newContent = document.forms[\"validForm\"][\"bcontent\"].value;\r\n var newPublisher = document.forms[\"validForm\"][\"bpublisher\"].value;\r\n if (newTitle == \"\") {\r\n alert(\"Title must be filled out\");\r\n return false;\r\n } else if (newOwner == \"\") {\r\n alert(\"Name Must be filled out\");\r\n return false;\r\n } else if (newContent == \"\") {\r\n alert(\"Content Must be filled out\");\r\n return false;\r\n } else if (newPublisher == \"\") {\r\n alert(\"Publisher Name Must be filled out\");\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "formValidate() {\n\t\tconst allValid = [\n\t\t\t...this.template.querySelectorAll('lightning-input, lightning-combobox')\n\t\t].reduce((validSoFar, inputCmp) => {\n\t\t\tinputCmp.reportValidity();\n\t\t\treturn validSoFar && inputCmp.checkValidity();\n\t\t}, true);\n\t\treturn allValid;\n }", "function validate_form(thisform){\n //if (validate_required(instanceName)==false){\n if(false){\n SetErrorMessage(1,\"Hola Yandy, esto es un error\");\n return false;\n }\n return true;\n}", "function valid_application_form(){\n\t// Verifies that the name is filled\n\tif(document.getElementById('name').value == \"\"){\n\t\talert('Veuillez saisir le nom.');\n\t\treturn false;\n\t}\n\t// Verifies that the description is filled\n\tif(document.getElementById('description').value == \"\"){\n\t\talert('Veuillez saisir la description.');\n\t\treturn false;\n\t}\n\treturn true;\n}", "function validar(form){\r\n\t\r\n\tif (Spry.Widget.Form.validate(form) == false) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\telse{\r\n\t\treturn true;\r\n\t}\r\n}", "function validar(form){\r\n\t\r\n\tif (Spry.Widget.Form.validate(form) == false) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\telse{\r\n\t\treturn true;\r\n\t}\r\n}", "function validate_form(step_index){\r\n var names = $.map($('#steps li').eq(step_index).find('input, select'), function (elm) { return elm.name; }) \r\n\t\t/*if($('#steps li').eq(step_index).val() != ''){\r\n\t\t\treturn true;\r\n\t\t}else{\r\n\t\t\treturn false;\r\n\t\t}*/\r\n var s = submitPartialFunction(names);\r\n return s; \r\n\t}", "function validateForm(event)\n{\n\tevent.preventDefault();\n\n\t//save the selection of the form to a variable\n\tvar form = document.querySelector('form');\n\t//save the selection of the required fields to an array\n\tvar fields = form.querySelectorAll('.required');\n\n\t//set a default value that will be used in an if statement\n\tvar valid = true;\n\n\t//check each box that has the required tag\n\tfor(var i = 0; i < fields.length; i++)\n\t{\n\t\t//check that the field has a value\n\t\t//if it does not\n\t\tif(!fields[i].value)\n\t\t{\n\t\t\t//valid is false\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\t//if valid is true by the end\n\t//each box should have a value\n\tif(valid == true)\n\t{\n\t\t//remove our disabled class from the button\n\t\tbtn.removeAttribute('class');\n\t\t//set the disabled property to false\n\t\tbtn.disabled = false;\n\t}\n}", "function validateForm(frm) {\n var flag = true;\n if (!formInputValidations(frm)) {\n //console.log('formInputValidations');\n flag = false;\n }\n if (!formTextareaValidations(frm)) {\n //console.log('formTextareaValidations');\n flag = false;\n }\n if (!formSelectValidations(frm)) {\n //console.log('formSelectValidations');\n flag = false;\n }\n return flag;\n}", "function checkForm() {\n let isValid = true;\n let errors_messages = [];\n\n // Check all input\n document.querySelectorAll(\"#signup_form input\").forEach(input => {\n if (!input.value) {\n errors_messages.push(input.name + \"is missing.\");\n isValid = false;\n }\n })\n\n // Check all select\n document.querySelectorAll(\"#signup_form select\").forEach(select => {\n if (!select.value) {\n errors_messages.push(select.name + \"is missing.\");\n isValid = false;\n }\n })\n\n // Check if the password and the re password are the same\n if (passwordInput.current.value !== repasswordInput.current.value) {\n errors_messages.push(\"Password and Re-password are not the same.\");\n isValid = false;\n }\n\n // Check if the user is 18 years or older\n if (!checkAge(document.querySelector(\"input[id=birthdate]\"))) {\n errors_messages.push(\"You must be at least 18 years old.\");\n isValid = false;\n }\n\n // Show all information about the form\n if (!isValid) {\n let html_return = \"<ul>\";\n errors_messages.forEach(error => {\n html_return += \"<li>\" + error + \"</li>\"\n })\n html_return += \"</ul>\";\n\n UIkit.notification({\n message: html_return,\n status: 'danger',\n pos: 'top-right',\n timeout: 5000\n });\n }\n\n return isValid;\n }", "function appValidation() {\n if ($(\"#registerForm\").length > 0)\n registerFormValid();\n if ($(\"#loginForm\").length > 0)\n loginFormValid();\n if ($(\"#checkForm\").length > 0)\n checkFormValid();\n if ($('#saleForm').length > 0)\n saleFormValid();\n }", "function validateForm() {\n return content.length > 0;\n }", "function formIsValid(id, isCreate) {\n if ($(\"#\" + id).valid()) { return true; }\n if (isCreate) { return false; }\n $(\"#\" + id + \" input\").each(function (index) {\n if ($(this).data(\"ismodified\") && $(this).hasClass(\"input-validation-error\")) { return false; }\n });\n return true;\n}", "validateForm() {\n return this.validateEmail() === 'success'\n && this.validateEmails() === 'success'\n && this.selectedPatent !== null;\n }", "formValid() {\n var valid = true;\n var required = this.$form.find(':input[required]');\n\n $.each(required, function(index, el) {\n var value = $(el).val();\n\n if (!value || value == '') {\n valid = false;\n }\n });\n\n return valid;\n }", "function validateForm() {\r\n return validatePassword() && validateState();\r\n}", "function verifyForm(form) {\n\tif (!requestValidation(form)) {\n\t\treturn false;\n\t}\n\treturn true;\n}", "validateForm() {\r\n if(this.getInputVal(this.inputBill) !== \"\" && \r\n this.getInputVal(this.inputPeople) !== \"\" &&\r\n (this.getInputVal(this.inputCustom) !== \"\" || \r\n this.percentageBtns.some(btn => btn.classList.contains(\"active\")))) \r\n {\r\n this.disableReset(false);\r\n return true;\r\n }\r\n else {\r\n this.disableReset(true);\r\n this.displayResult(\"__.__\", \"__.__\");\r\n return false;\r\n }\r\n }", "function validateForms() {\n var typedForms = document.querySelectorAll('input');\n var designMenu = document.getElementById('design');\n var designLabel = document.querySelector('.shirt').lastElementChild;\n var designChoice = designMenu.options[designMenu.selectedIndex].text;\n var paymentMethod = document.getElementById('payment');\n var paymentForm = paymentMethod.options[paymentMethod.selectedIndex].text;\n if (designChoice == 'Select Theme') {\n addErrorIndication('Please select a theme', designLabel);\n }\n if ($(\"[type=checkbox]:checked\").length < 1) {\n var activityList = document.querySelectorAll('.activities label')\n var str = 'Please select at least one activity';\n addErrorIndication(str, activityList[activityList.length-1]);\n }\n if (paymentForm == 'Select Payment Method') {\n addErrorIndication('Please select a payment method', paymentMenu);\n }\n for (let i = 0; i < typedForms.length; i++) {\n var currentForm = typedForms[i];\n if (currentForm.id == 'name' && currentForm.value.length < 1) {\n var str = 'Please enter a name';\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'mail' && checkFormat(currentForm) == false) {\n var str = 'Please enter an email address';\n addErrorIndication(str, currentForm);\n } else if (paymentForm == 'Credit Card' && checkFormat(currentForm) == false) {\n if (currentForm.id == 'cc-num') {\n var str = 'Please enter a credit card number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is between 13 and 16 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'zip') {\n var str = 'Please enter a zip number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 5 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'cvv') {\n var str = 'Please enter a CVV number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 3 digits long';\n }\n addErrorIndication(str, currentForm);\n }\n }\n }\n}", "function validateForm() {\n return email.length > 0 && password.length > 0;\n }", "function validateForm()\n { \t \t\n \t\n \t$('#frmMain').addClass('submitted');\n \t\n \tvar validated = true;\n \t$('#frmMain').find(':input').each(function(){ \n \t\t\n \t\tvar id = $(this).prop('id');\n \t\tif(id!=\"\")\n \t\t{\n\t \t\tvar Value = $('#' + id).val(); \t\t\n\t \t\tvar requ = $(this).prop('required');\t\n\t \t\t \t\t\n\t \t\tif(Value == \"\" && requ == true) \t\t\n\t \t\t\tvalidated = false;\n \t\t}\n \t});\n\n \tif(validated == true)\n \t{ \t\t \t\t\t\n \t\tvar Lenght = $(\"#txtLengthInFeet\").val();\n \tvar Inch = $(\"#drpLengthInInch\").find(\"option:selected\").text();\n \tvar Fraction = $(\"#drpLengthInFraction\").find(\"option:selected\").text();\n \t\n \tvalidated = validateLength(Lenght,Inch,Fraction,\"Length\");\n \t}\n \t$('[data-required]').each(function() { \t\t\n \t if (!$(this).val()) \n \t {\n \t\t var id = $(this).attr('id') + 1;\n \t\t\n \t\t if ($(this).data('select2') && $('#' + id).is(':visible')) \n \t\t {\n \t\t \t$(\"#\"+id).addClass('error'); \n \t\t \tvalidated = false;\n \t\t }\n \t\t }\n \t});\n \t\n \treturn validated;\n \t\n }", "function validateForm(form) {\n var idx;\n var formValid = true;\n\n if (occupationSelect.value == 'other') {\n requiredFields.push('occupationOther');\n }\n\n //retrieves the required field elements\n for (idx = 0; idx < requiredFields.length; ++idx) {\n var requiredField = form.elements[requiredFields[idx]];\n formValid &= validateRequiredField(requiredField);\n }\n return formValid;\n }", "function MM_validateForm() { //v4.0\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;\n for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n';\n } else if (test!='R') { num = parseFloat(val);\n if (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\n if (test.indexOf('inRange') != -1) { p=test.indexOf(':');\n min=test.substring(8,p); max=test.substring(p+1);\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\n } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\n } if (errors) alert('The following error(s) occurred:\\n'+errors);\n document.MM_returnValue = (errors == '');\n}", "function isValidForm(){\n\n if(newCatNameField.value.length > 0 && checkDuplicateName(newCatNameField.value) &&\n newCatLimitField.validity.valid && newCatLimitField.value.length > 0){\n createButton.classList.remove('mdl-button--disabled');\n }\n else {\n createButton.classList.add('mdl-button--disabled');\n }\n }", "function formValidation() {\n //* If validation of email fails, add the warning class to email input and set the display of warning message to inline.\n if (!validation.isEmailValid(email.value)) {\n email.classList.add(\"warning\");\n email.nextElementSibling.style.display = \"inline\";\n }\n //* If validation of name fails, add the warning class to name input and set the display of warning message to inline.\n if (!validation.isNameValid(name.value)) {\n name.classList.add(\"warning\");\n name.nextElementSibling.style.display = \"inline\";\n }\n /*\n * If validation of message fails, add the warning class to message text area and set the display of warning\n * message to inline\n */\n if (!validation.isMessageValid(message.value)) {\n message.classList.add(\"warning\");\n message.nextElementSibling.style.display = \"inline\";\n }\n /*\n *If validation of title fails, add the warning class to title input and set the display of warning\n *message to inline\n */\n\n if (!validation.isTitleValid(title.value)) {\n title.classList.add(\"warning\");\n title.nextElementSibling.style.display = \"inline\";\n }\n if (\n validation.isEmailValid(email.value) &&\n validation.isNameValid(name.value) &&\n validation.isTitleValid(title.valid) &&\n validation.isMessageValid(message.value)\n ) {\n return true;\n } else return false;\n}", "checkForm() {\n this.elements.resetHint();\n\n const title = this.elements.form.querySelector('.field-title').value;\n const price = this.elements.form.querySelector('.field-price').value;\n\n if (!title || /^\\W/.test(title)) {\n this.elements.showHint('title', 'Нужно заполнить поле');\n return true;\n }\n\n if (!price) {\n this.elements.showHint('price', 'Нужно заполнить поле');\n return true;\n }\n\n if (/\\D/.test(price)) {\n this.elements.showHint('price', 'некорректное значение');\n return true;\n }\n }", "function isFormValid() {\n\tlet formIsValid = true;\n\n\tformIsValid = highlightCurrencyInputErrors(formIsValid, 'loanAmount');\n\tformIsValid = highlightCurrencyInputErrors(formIsValid, 'annualTax');\n\tformIsValid = highlightCurrencyInputErrors(formIsValid, 'annualInsurance');\n\n\treturn formIsValid;\n}", "function formValidator(){\n\t\tvar form = $(\"#create-client\");\n\t\tform.validate({\n\t\t\trules: {\n\t\t\t\tfullName: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tminlength: 5,\n\t\t\t\t\tmaxlength: 50,\n\t\t\t\t},\n\t\t\t\tphone: {\n\t\t\t\t\tdigits: true,\n\t\t\t\t\tmaxlength: 10,\t\n\t\t\t\t},\n\t\t\t\temail: {\n\t\t\t\t\temail: true,\n\t\t\t\t\tmaxlength: 100,\n\t\t\t\t},\n\t\t\t\taddress: {\n\t\t\t\t\tmaxlength: 100,\n\t\t\t\t},\n\t\t\t\tnationality: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tmaxlength: 50,\n\t\t\t\t},\n\t\t\t\tdateOfBirth: {\n\t\t\t\t\trequired: true,\n\t\t\t\t\tdate: true,\n\t\t\t\t},\n\t\t\t\teducation: {\n\t\t\t\t\tmaxlength: 100,\n\t\t\t\t},\n \t\t\t},\n \t\t\tinvalidHandler: function(event, validator) {\n \t\t\t\tresetError();\n\t\t\t\tvar errors = validator.numberOfInvalids();\n\t\t\t\tif(errors){\n\t\t\t\t\tshowError(validator);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "static form(formdata) {\n console.log(\" \");\n console.log(\"%cValidate Form\", \"color: green;\", formdata);\n let valid = true;\n Validate.cleanErrors();\n\n if (Validate.vEmail(formdata.email)) {\n Validate.addError(\"email\", \"El mail no es valido\")\n valid = false\n }\n\n let date = new Date(formdata.date)\n if (date > Date.now()) {\n Validate.addError(\"date\", \"La fecha debe ser anterior a la fecha de hoy\")\n valid = false\n }\n\n if (formdata.checkbox == false) {\n Validate.addError(\"checkbox\", \"Debe aceptar el checkbox'\")\n valid = false\n }\n\n if (formdata.number < 2) {\n Validate.addError(\"number\", \"El numero debe ser mayor a 2\")\n valid = false\n }\n\n if (formdata.radio != \"Hombre\") {\n Validate.addError(\"radio\", \"Debe ser hombre\")\n valid = false\n }\n\n if (formdata.select != \"AR\") {\n Validate.addError(\"select\", \"Debe ser Argentina\")\n valid = false\n }\n\n if (formdata.text != \"valido\") {\n Validate.addError(\"text\", \"Agregar el texto 'valido'\")\n valid = false\n }\n\n\n valid = Validate.vRquired(formdata,valid);\n let color = valid ? \"green\" : \"red\";\n console.log(` isValid:%c${valid}`, `color: ${color};`);\n\n return valid;\n }", "function validateForm(){\n var field = readFormField;\n function notBlank(field, str){ if(str.trim() == '') return field + \" required.\"; }\n var emailPattern = /^[\\w+\\-\\.]+@\\w+\\.\\w+$/;\n var pr = undefined;\n pr = pr || notBlank('Purchaser first name', field('purchaser_first_name'));\n pr = pr || notBlank('Purchaser last name', field('purchaser_last_name'));\n pr = pr || notBlank('Purchaser email', field('purchaser_email'));\n if(!field('purchaser_email').match(emailPattern)){\n pr = pr || 'The purchaser email address looks invalid.';\n }\n if(field('recipient_email').trim() != ''){\n if(!field('recipient_email').match(emailPattern)){\n pr = pr || 'The recipient email address looks invalid.';\n }\n }\n pr = pr || notBlank('Card number', field('card_number'));\n pr = pr || notBlank('Card CVC', field('card_cvc'));\n pr = pr || notBlank('Card expiration month', field('card_month'));\n pr = pr || notBlank('Card expiration year', field('card_year'));\n return pr;\n}", "function isValidPartialForm() {\n var authorNicknameValid = isValidRequiredField(\"author_nickname\");\n var titleValid = isValidRequiredField(\"title\");\n var headerTextValid = isValidRequiredField(\"header_text\");\n return authorNicknameValid && titleValid && headerTextValid;\n}", "function checkForm(e) {\n var inputlist = document.getElementsByClassName(\"required\"); // Make an array of required inputs\n var empties = new Array(); // Create a blank list for empty fields\n // Check for empty fields, an add them to the empty list\n for( var i = 0; i < inputlist.length; i++ )\n if(Form.Element.getValue(inputlist[i]) == \"\"){\n empties.push($(inputlist[i]).getAttribute(\"id\"));\n }\n else {\n $(inputlist[i]).style.border=\"1px solid #333\";\n }\n // If there are empty fields, highight them\n if(empties.length > 0) {\n var i = 0;\n while( i < empties.length ) {\n $(empties[i]).style.border=\"2px solid #a00\";\n i++;\n }\n $(\"formerror\").style.display=\"inline\";\n Event.stop(e);\n }\n else {\n // Cosmetic: Reset all of the checked fields to the regular style\n for( var i = 0; i < inputlist.length; i++ )\n $(inputlist[i]).style.border=\"1px solid #333\";\n // If there aren't empty fields, submit the form\n return true;\n }\n}", "function checkForm(){\n\n\tif ((verifyElementWithId(\"name\"))\n\t\t&& (verifyElementWithId(\"name1\"))\n\t\t&& (verifyElementWithId(\"name2\"))\n\n\t\t&& (verifyElementWithId(\"way\"))\n\t\t&& (verifyElementWithId(\"textaddress\"))\n\t\t&& (verifyElementWithId(\"textaddressnumber\"))\n\t\t&& (verifyElementWithId(\"textpostalcode\"))\n\t\t&& (verifyElementWithId(\"city\"))\n\n\t\t&& (verifyElementWithId(\"emailbox\"))\n\t\t&& (verifyElementWithId(\"passwordbox\"))\n\t\t&& (verifyElementWithId(\"passwordrepeatbox\"))\n\n\t\t&& (verifyCheckBoxWithId(\"acceptconditions\"))\n\t\t&& (document.getElementById(\"passwordbox\").value == document.getElementById(\"passwordrepeatbox\").value)) {\n\n\t\talert(\"Su registro se ha enviado con éxito.\");\n\t\treturn true;\n\n\t} else {\n\n\t\treturn false;\n\t}\n\n}", "function validateForm(){\n // Set error catcher\n var error = 0;\n // Check name\n if(!validateName('reg_name')){\n document.getElementById('nameError').style.display = \"block\";\n error++;\n }\n // Validate email\n var x =document.getElementById('reg_email').value;\n if(!validateEmail(x)){\n document.getElementById('emailError').style.display = \"block\";\n error++;\n }\n // Validate animal dropdown box\n if(!validateSelect('Occupation')){\n document.getElementById('animalError').style.display = \"block\";\n error++;\n }\n if(!validatePassword('reg_pass')){\n document.getElementById('pass_Error').style.display = \"block\";\n error++;\n }\n // Don't submit form if there are errors\n if(error > 0){\n return false;\n }\n else if(error == 0){\n regfun();\n }\n }", "_validate(values) {\n const constraint = this.constructor.FORM_CONSTRAINT\n const result = validate(Object.assign({}, this.state, values), constraint)\n return result\n }", "function isValidateForm() {\n var validName = validateName();\n var validEmail = validateEmail();\n var validActivity = validateActivity();\n var validPayment = validatePayment();\n\n return validName && validEmail && validActivity && validPayment;\n }", "function validateForm(value) {\n\t\t\tif (status !== \"\") {\n\t\t\t\t// Reset status on input change\n\t\t\t\t$$invalidate(3, status = \"\");\n\t\t\t}\n\n\t\t\treturn validateProvider(value) !== null;\n\t\t}", "function validate(){\n\n\t\t//TODO: make this work\n\n\n\t}", "function validateForm()\n{\n return true;\n}", "function validateForm()\n{\n return true;\n}", "function validateForm() {\n\n\tvar x, i, z, valid = true;\n\tx = document.getElementsByClassName(\"tab\");\n\ty = x[currentTab].getElementsByClassName(\"required\");\n\tz = x[currentTab].getElementsByTagName(\"select\");\n\n\tfor (i = 0; i < y.length; i++) { // Check every input field in the current tab\n\t\tif (y[i].value == \"\") { // Check if a field is empty\n\t\t y[i].className += \" invalid\"; // Add an \"invalid\" class to the field\n\t\t valid = false; // Set the current valid status to false\n\t\t}\n\t\tif (y[i].type == \"hidden\") {\n\t\t\tvalid = true;\n\t\t}\n\t}\n\n\tfor (i = 0; i < z.length; i++) { // Check every input field in the current tab\n\t\tif (z[i].value == \"\") { // Check if a field is empty\n\t\t z[i].className += \" invalid\"; // Add an \"invalid\" class to the field\n\t\t valid = false; // Set the current valid status to false\n\t\t}\n\t\tif (z[i].type == \"hidden\") {\n\t\t\tvalid = true;\n\t\t}\n\t}\n\n\tif (valid) { // If the valid status is true, mark the step as finished and valid\n\t\tdocument.getElementsByClassName(\"indicator\")[currentTab].className += \" finish\";\n\t}\n\treturn valid; // Return the valid status\n}", "validateForm () {\n const form = this.panelEl.querySelector('.panel-content');\n if (!form.checkValidity()) {\n this.fail('Please correct errors navmesh configuration.');\n }\n }", "function validateAddOpForm() {\n // Check inputs\n return pageDialog.amount.value.length > 0 && pageDialog.desc.value.length > 0\n }", "function validateForm() {\n var form = $(this);\n var values = {};\n $.each(form.serializeArray(), function(i, field) {\n values[field.name] = field.value;\n });\n\n var input = parseInput(values['class']);\n if (input === null) {\n toggleError(true);\n displayErrorMessage('Class not found.');\n return false;\n }\n toggleError(false);\n displayErrorMessage('');\n\n var page = abbrToLinkMap[input['department'].toLowerCase()];\n var link = input['department'] + input['courseNumber'];\n form.attr('action', removeWhitespace(page + \"#\" + link));\n\n return true;\n}", "function validateRegistrationForm(){\n let messageList= [\"firstname\", \"lastname\", \"email\", \"phonenumber\", \"postalcode\", \"address\", \"city\", \"province\"];\n return validateFieldInput(messageList[0]) && validateFieldInput(messageList[1]) && validateFieldInput(messageList[2]) && validateFieldInput(messageList[3]) && validateFieldInput(messageList[4]);\n }", "function validateForm()\n {\n \t \t\n \tvar connectionTypeFormId;\n \t\n \t$('#frmMain').addClass('submitted');\n \t$('#frmRefrenceDrawing').addClass('submitted');\n \t\n \tif($('#ConnectiontypeMonorail').val()=='connectionTypeMonoEP'){\n \t\t\n \t\t$('#frmPostWithEndPlate').addClass('submitted');\n \t\t$('#frmDirectlyBolted').addClass('submitted');\n \t\t\n \t\tconnectionTypeFormId = \"frmPostWithEndPlate\";\n \n } \n else if($('#ConnectiontypeMonorail').val()=='connectionTypeMonoDB'){\n \t \n \t $('#frmDirectlyBolted').addClass('submitted');\n \t $('#frmPostWithEndPlate').removeClass('submitted');\n \t\t \n }\n \t \t\n \tvar validated = true;\n \t$('#frmMain').find(':input').each(function(){ \n \t\t\n \t\tvar id = $(this).prop('id');\n \t\tif(id!=\"\")\n \t\t{\n\t \t\tvar Value = $('#' + id).val(); \t\t\n\t \t\tvar requ = $(this).prop('required');\t\n\t \t\tvar elemetvisible = $('#' + id).is(':visible'); \t\t\n\t \t\tif(Value == \"\" && requ == true && elemetvisible) \t\t\n\t \t\t\tvalidated = false;\n \t\t}\n \t});\n \tif(validated==true)\n \t\t{\n \t\t\tvar Lenght = $(\"#txtLengthInFeet\").val();\n \tvar Inch = $(\"#drpLengthInInch\").find(\"option:selected\").text();\n \tvar Fraction = $(\"#drpLengthInFraction\").find(\"option:selected\").text(); \t\n \t\tvalidated = validateLength(Lenght,Inch,Fraction,\"Length\");\n \t\t\t\n \t\t}\n \t\n \t$('#'+connectionTypeFormId).find(':input').each(function(){ \t\t\n \t\t\n \t\tvar id = $(this).prop('id');\n \t\tif(id!=\"\")\n \t\t{\n\t \t\tvar Value = $('#' + id).val(); \t\t\n\t \t\tvar requ = $(this).prop('required');\n\t \t\tvar elemetvisible = $('#' + id).is(':visible');\n \t\t \t\t\n\t \t\tif(Value == \"\" && requ == true && elemetvisible) \t\t\n\t \t\t\tvalidated = false;\n \t\t}\n \t\t\n \t}); \n \tif(validated==true && connectionTypeFormId == \"frmPostWithEndPlate\")\n \t\t{\n \t\t\tvar PostLenght = $(\"#txtPostLengthInFeet\").val();\n \tvar PostInch = $(\"#drpPostLengthInInch\").find(\"option:selected\").text();\n \tvar PostFraction = $(\"#drpPostLengthInFraction\").find(\"option:selected\").text();\n \t\n \tvalidated = validateLength(PostLenght,PostInch,PostFraction,\"Post Length\");\n \t\t\n \t\t}\n \t\n \t$('#frmDirectlyBolted').find(':input').each(function(){ \t\t\n \t\t\n \t\tvar id = $(this).prop('id');\n \t\tif(id!=\"\")\n \t\t{\n\t \t\tvar Value = $('#' + id).val(); \t\t\n\t \t\tvar requ = $(this).prop('required');\n\t \t\t \t\t\n\t \t\tif(Value == \"\" && requ == true) \t\t\n\t \t\t\tvalidated = false;\n \t\t}\n \t\t\n \t}); \n \t\n \t$('[data-required]').each(function() { \t\t\n \t if (!$(this).val()) \n \t {\n \t\t var id = $(this).attr('id') + 1;\n \t\t\n \t\t if ($(this).data('select2') && $('#' + id).is(':visible')) \n \t\t {\n \t\t \t$(\"#\"+id).addClass('error'); \n \t\t \tvalidated = false;\n \t\t }\n \t\t }\n \t});\n \treturn validated; \n \t\n }", "function validateForm() {\n var $form = $('#album-form');\n $form.validator('validate');\n\n return !$form.find(':invalid').length;\n}", "function formIsValid() {\n if (total_loan_box.value === \"\" || isNaN(total_loan_box.value)) {\n speakToUser(\"You must enter a valid decimal number for the <strong>Total Loan Amount</strong>.\");\n focusOnBox(\"total_loan\");\n return false;\n }\n\n if (interest_rate_box.value === \"\" || isNaN(interest_rate_box.value)) {\n speakToUser(\"You must enter a valid decimal number for the <strong>Yearly Interest Rate</strong>.\");\n focusOnBox(\"interest_rate\");\n return false;\n }\n\n if (loan_term_box.value === \"\" || isNaN(loan_term_box.value)) {\n speakToUser(\"You must enter a valid number of years for the <strong>Loan Term</strong>.\");\n focusOnBox(\"loan_term\");\n return false;\n }\n\n return true;\n}", "validateForm() {\n return (this.validatePrices()\n && this.validateName() === 'success'\n && this.state.hash !== \"\"\n && this.state.ipfsLocation !== \"\"\n && this.state.fileState === FileStates.ENCRYPTED)\n }", "function isObsFormValid(){\t \n var v1 = textoObsField.isValid();\n return( v1);\n }", "function validateForm(form) {\n var fieldsRequired = ['firstName', 'lastName', 'address1',\n 'city', 'state', 'zip', 'birthdate'];\n var idx;\n var occupation1 = 'occupationOther';\n var formsValid = true;\n for (idx = 0; idx < fieldsRequired.length; idx++) {\n formsValid &= validateField(form.elements[fieldsRequired[idx]]);\n }\n if (document.getElementById('occupation').value === 'other') {\n formsValid &= validateField(form.elements[occupation1]);\n }\n\n return formsValid;\n}", "validateForm(formFields) {\n return Object.values(formFields).reduce((valid, formField) => {\n return valid && formField.valid;\n }, true);\n }", "function MM_validateForm_Site() { //v4.0\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm_Site.arguments;\n\t\n for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n';\n } else if (test!='R') { num = parseFloat(val);\n if (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\n if (test.indexOf('inRange') != -1) { p=test.indexOf(':');\n min=test.substring(8,p); max=test.substring(p+1);\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\n } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\n\n\t}\n\t\n\t //extra validation\n\t errors += validate_state();\n\t errors += validate_lat();\n\t errors += validate_lon();\n\t errors += validate_elevation();\n\t \n\tif (errors) alert('The following error(s) occurred:\\n'+errors);\n document.MM_returnValue = (errors == '');\n}", "function validateAttendanceForm() {\n var $form = $('#edit-attendance-form');\n if ($form) {\n //Hours\n if ($form.find('select[name=\"absent_type\"] :selected').val() == 'time') {\n if ($.trim($form.find('input[name=\"from_hour\"]').val()) == '') {\n $form.find('input[name=\"from_hour\"]').focus();\n return false;\n }\n if ($.trim($form.find('input[name=\"to_hour\"]').val()) == '') {\n $form.find('input[name=\"to_hour\"]').focus();\n return false;\n }\n }\n //Content\n if ($.trim($form.find('textarea[name=\"content\"]').val()) == '') {\n $form.find('textarea[name=\"content\"]').focus();\n return false;\n }\n }\n return true;\n}", "function validateForm() {\n var formValid = checkValidity($('form'))\n $('.form-control').removeClass('border-danger text-danger');\n\n $('.form-control').each(function() {\n let inputValid = checkValidity($(this))\n if ( ($(this).prop('required') && ($(this).val().length == 0 || $(this).val() == \" \")) // test for blank while required\n || ($(this).hasClass('check-url') && !validateURL($(this).val())) // test for check URL\n ) {\n inputValid = false;\n formValid = false;\n }\n\n // Test for BCH address\n if ($(this).hasClass('check-bch-address')) {\n if (bchaddr.isValidAddress($(this).val())) {\n if (bchaddr.isLegacyAddress($(this).val())) {\n // isLegacyAddress throws an error if it is not given a valid BCH address\n // this explains the nested if\n inputValid = false;\n formValid = false;\n }\n } else {\n inputValid = false;\n formValid = false;\n }\n }\n\n let showError = $(this).parent().find(\".show-error-on-validation\")\n\n // After all validation\n if (!inputValid) {\n \n $(this).addClass('border-danger text-danger');\n \n if (showError.length) {\n showError.removeClass(\"d-none\")\n }\n\n } else {\n if (showError.length) {\n showError.addClass(\"d-none\")\n }\n }\n });\n\n // Submit if everything is valid\n if (formValid) {\n return true\n } else {\n $(\"#error\").removeClass(\"d-none\");\n $(\"#error\").text(\"Some fields are incorrect.\")\n return false\n }\n}", "function validateForm() {\n return username.length > 0 && password.length > 0;\n }", "function formHasErrors()\n{\n\tvar errorFlag = false;\n //validating all of the text fields to confirm the have options\n\tfor(let i = 0; i < requireTextFields.length; i++){\n\t\tvar textField = document.getElementById(requireTextFields[i])\n\t\t\n\t\tif(!hasInput(textField)){\n\t\t\t//display correct error message\n\t\t\tdocument.getElementById(requireTextFields[i] + \"_error\").style.display = \"inline\";\n document.getElementById(requireTextFields[i]).style.border = \"0.75px red solid\";\n \n\t\t\terrorFlag = true;\n\t\t} else {\n\t\t\t\n\t\t\t//after user enters the correct info this hides the border and error message\n\t\t\tdocument.getElementById(requireTextFields[i] + \"_error\").style.display = \"none\";\n\t\t\tdocument.getElementById(requireTextFields[i]).style.border = \"1px solid #e5e5e5;\";\n\t\t}\n\t}\n\treturn errorFlag;\n}", "function validateForm() {\n\t\n\tvar messageString = \"\"; // Start with blank error message\n\tvar tableViewRows = $.tableView.data[0].rows;\n\t\n\tfor (var i = 0; i < tableViewRows.length; ++i) {\n\t\t\n\t\tvar fieldObject = tableViewRows[i].fieldObject;\n\t\tvar value = getFieldValue(tableViewRows[i]);\n\t\t\n\t\tif (fieldObject.field_type == 'Checkbox') {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t// Checks if the field is blank and/or required\n\t\tif (value == \"\" || value == null) {\n\t\t\tif (fieldObject.required == \"No\") {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" is a required field.\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// -------------- Text ----------------\n \t\tif (fieldObject.field_type == 'Text') {\n \t\t\t// Do Nothing\n \t\t\t\n \t\t// -------------- Checkbox ----------------\n \t\t} else if (fieldObject.field_type == 'Checkbox') { \n \t\t\t// Do Nothing\t\n \t\t\n \t\t\n \t\t// ------------ Integer ----------------\n \t\t} else if (fieldObject.field_type == 'Integer') { \n\t\t\t// Is number? And is integer?\n\t\t\tif (Number(value) > 0 && value % 1 == 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be an integer.\\n\";\n\t\t\t}\n\t\t\n\t\t\n\t\t// ------------ Decimal ----------------\n\t\t} else if (fieldObject.field_type == 'Decimal') { \n\t\t // Is number?\n\t\t\tif (Number(value) > 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be a number.\\n\";\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t// ---------- Calculated ------------\n\t\t} else if (fieldObject.field_type == 'Calculated') { \n\t\t\n\t\t\n\t\t// -------------- Incremental Text ----------------\n\t\t} else if (fieldObject.field_type == 'Incremental Text') { \n\t\t\n\t\t\n\t\t// -------------- Date ----------------\n\t\t} else if (fieldObject.field_type == 'Date') { \n\t\t\n\t\t\n\t\t// -------------- Time ----------------\n\t\t} else if (fieldObject.field_type == 'Time') { \n\t\t\t\n\t\t\t\n\t\t// -------------- Date-Time ----------------\n\t\t} else if (fieldObject.field_type == 'Date-Time') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Message') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Location') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Photo') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Recording') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Button Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Structural Attitude') { \n\t\t\n\t\t} else { \n\t\t\t\n\t\t}\n\t\t//------------------------------------------------------------------------------------------------------------------------------------------\n\t}\n\treturn messageString;\n}", "function isECourseFormValid(){\r\n return( CourseNameField.isValid() && CourseDaysField.isValid());\r\n }", "function ValidarForm(){\r\n\t/*Validando el campo nombre*/\r\n\tif(document.frmCliente.nombre.value.length==0){\r\n\t\talert(\"Debe escribir el Nombre\")\r\n\t\tdocument.frmCliente.nombre.focus()\r\n\t\treturn false\r\n\t}\r\n\t/*Validando el campo apellidos*/\r\n\tif(document.frmCliente.apellidos.value.length==0){\r\n\t\talert(\"Debe escribir los Apellidos\")\r\n\t\tdocument.frmCliente.apellidos.focus()\r\n\t\treturn false\r\n\t}\r\n\t/*Validando el campo cedula*/\r\n\tif(document.frmCliente.cedula.value.length==0){\r\n\t\talert(\"Debe escribir el numero de Cedula\")\r\n\t\tdocument.frmCliente.cedula.focus()\r\n\t\treturn false\r\n\t}\r\n\t/*Validando el campo telefono*/\r\n\tif(document.frmCliente.telefono.value.length==0){\r\n\t\talert(\"Debe escribir el numero de Telefono\")\r\n\t\tdocument.frmCliente.telefono.focus()\r\n\t\treturn false\r\n\t}\r\n\t/*Validando el campo correo*/\r\n\tif(document.frmCliente.correo.value.length==0){\r\n\t\talert(\"Debe escribir su Correo\")\r\n\t\tdocument.frmCliente.correo.focus()\r\n\t\treturn false\r\n\t}\r\n\t/*Validando el campo direccion*/\r\n\tif(document.frmCliente.direccion.value.length==0){\r\n\t\talert(\"Debe escribir su Direccion\")\r\n\t\tdocument.frmCliente.direccion.focus()\r\n\t\treturn false\r\n\t}\r\n}", "function formValidator() {\n //create object that will save user's input (empty value)\n let feedback = [];\n //create an array that will save error messages (empty)\n let errors = [];\n //check if full name has a value\n if (fn.value !== ``){\n //if it does, save it\n feedback.fname = fn.value; \n }else {\n //if it doesn't, crete the error message and save it\n errors.push(`<p>Invalid Full Name</p>`);\n }\n \n //for email\n if (em.value !== ``){\n feedback.email = em.value;\n //expression.test(String('my-email@test.com').toLowerCase()); \n }else {\n errors.push(`<p>Invalid Email</p>`);\n }\n\n //for message\n if (mes.value !== ``){\n feedback.message = mes.value;\n }else {\n errors.push(`<p>Write a comment</p>`)\n }\n \n //create either feedback or display all errors\n if (errors.length === 0) {\n console.log(feedback);\n }else {\n console.log(errors);\n }\n //close event handler\n}", "function validate(form, index) {\n\n for (var i = 0; i < form.elements.length; i++) {\n if (form.elements[i].name !== 'filename') {\n resetError(form.elements[i].name + 'Input', form);\n }\n }\n\n for (var i = 0; i < form.elements.length; i++) {\n if (form.elements[i].name == \"password\") {\n checkPassword(form.elements[i].name + 'Input', form);\n }\n if (form.elements[i].value == \"\" && form.elements[i].name != \"filename\") {\n\n showError(form.elements[i].name + 'Input', 'Fill the ' + form.elements[i].name + ' field', form);\n\n\n }\n\n }\n\n\n if (form == \"privateCabinetform\" || index == \"registerform\") {\n checkEmail('emailInput', form);\n }\n\n }", "function isValidUpdateForm() {\n\tvar name = $(\"#name-update\").val();\n\tvar date = $(\"#date-update\").val();\n\tvar score = $(\"#scores-update\").val();\n\t\n\tvar checkName = isValidName(name);\n\tvar checkDate = isValidDate(date);\n\tvar checkScore = isValidScore(score);\n\t\n\t$(\"#invalid-name-update\").html(\"\");\n\t$(\"#invalid-date-update\").html(\"\");\n\t$(\"#invalid-score-update\").html(\"\");\n\t\n\tif (!checkName || !checkDate || !checkScore) {\n\t\tif (!checkName) {\n\t\t\t$(\"#invalid-name-update\").html(\"Invalid student's name\");\n\t\t}\n\t\tif (!checkDate) {\n\t\t\t$(\"#invalid-date-update\").html(\"Invalid student's date\");\n\t\t}\n\t\tif (!checkScore) {\n\t\t\t$(\"#invalid-score-update\").html(\"Invalid student's score\");\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}", "function validateForm(form) {\n\tvar reqField = []\n\treqField.push(form.elements['firstName']);\n\treqField.push(form.elements['lastName']);\n\treqField.push(form.elements['address1']);\n\treqField.push(form.elements['city']);\n\treqField.push(form.elements['state']);\n\tzip = form.elements['zip']\n\tbirthdate = form.elements['birthdate']\n\n\ttoReturn = true;\n\n\treqField.forEach(function(field) {\n\t\tif (field.value.trim().length == 0) {\n\t\t\tfield.className = field.className + \" invalid-field\";\n\t\t\ttoReturn = false;\n\t\t} else {\n\t\t\tfield.className = 'form-control'\n\t\t}\n\t});\n\n\tif (document.getElementById('occupation').value == 'other') {\n\t\tvar otherBox = document.getElementsByName('occupationOther')[0]\n\t\tif (otherBox.value.trim().length == 0) {\n\t\t\totherBox.className = otherBox.className + ' invalid-field';\n\t\t\ttoReturn = false;\n\t\t} else {\n\t\t\totherBox.className = 'form-control'\n\t\t}\n\t}\n\n\tvar zipRegExp = new RegExp('^\\\\d{5}$');\n\n\tif (!zipRegExp.test(zip.value.trim())) {\n\t\tzip.className = zip.className + ' invalid-field';\n\t\ttoReturn = false;\n\t} else {\n\t\tzip.className = 'form-control';\n\t}\n\n\tif (birthdate.value.trim().length == 0) {\n\t\tbirthdate.className = birthdate.className + ' invalid-field'\n\t} else {\n\t\tvar dob = new Date(birthdate.value);\n\t\tvar today = new Date();\n\t\tif (today.getUTCFullYear() - dob.getUTCFullYear() == 13) {\n\t\t\tif (today.getUTCMonth() - dob.getUTCMonth() == 0) {\n\t\t\t\tif (today.getUTCDate() - dob.getUTCDate() == 0) {\n\t\t\t\t\tcorrectAge(birthdate)\n\t\t\t\t} else if (today.getUTCDate() - dob.getUTCDate() < 0) {\n\t\t\t\t\ttoReturn = tooYoung(birthdate);\n\t\t\t\t} else {\n\t\t\t\t\tcorrectAge(birthdate)\n\t\t\t\t}\n\t\t\t} else if (today.getUTCMonth() - dob.getUTCMonth() < 0) {\n\t\t\t\ttoReturn = tooYoung(birthdate);\n\n\t\t\t} else {\n\t\t\t\tcorrectAge(birthdate)\n\t\t\t}\n\t\t} else if (today.getUTCFullYear() - dob.getUTCFullYear() < 13) {\n\t\t\ttoReturn = tooYoung(birthdate);\n\n\t\t} else {\n\t\t\tcorrectAge(birthdate)\n\t\t}\n\t}\n\n\treturn toReturn;\n}", "function validateForm(form) {\n console.log(\"validateForm called on \" + form);\n // feed parameter with 'this' value at the onClick so we can reference the form from the element itself\n console.log(\"form \" + form);\n // Get the forms control points to reference both their name and value in a loop\n var controls = form.elements;\n var notValid = [];\n console.log(\"checking \" + controls + \" and its value \");\n\n // Create the loop and add mistakes to the notValid array\n for(var i = 0; i < controls.length; i++) {\n // controls are added if they value doesn't exist\n if (controls[i].value == \"\") {\n notValid[i] = controls[i].name + ': ' + controls[i].value;\n }\n }\n // If no errors, return true and proceed, if errors, alert them all and return false.\n if (notValid.length == 0) {\n console.log(\"All fields are entered correctly\");\n return true;\n } else {\n alert(notValid.join('\\n'));\n return false;\n }\n\n}", "function OnSecondFormSubmit (event)\n{\n var e = document.forms[1].elements;\n \n OnMidasSubmit (event);\n valid = true;\n for (i=0;i<e.length;i++)\n {\n valid = valid && checkValidity(e[i]);\n }\n return valid;\n}", "function validateForm(el) {\n\n\tvar isValid = true;\n\t$('.validation-error').remove();\n\t$(el).find(\"input,select, textarea\").each(function () {\n\t\tif (typeof ($(this).attr(\"require\")) != \"undefined\" && $.trim($(this).val()) == \"\") {\n\t\t\t$(this).addClass('invalid-input');\n\t\t\t$(this).parent('div').append(\"<span class='validation-error'><i class='glyphicon glyphicon-exclamation-sign'></i>\" + $(this).attr('data-validation-message') + \"</span>\");\n\t\t\tisValid = false;\n\t\t\t$('form .col-xs-4,form .col-xs-6,form .col-sm-4,form .col-sm-6').matchHeight();\n\t\t} else if (typeof ($(this).attr(\"require\")) != \"undefined\" && $.trim($(this).val()) != \"\") {\n\t\t\t$(this).removeClass('invalid-input');\n\n\t\t}\n\t});\n\n\treturn isValid;\n}", "function validateForm() {\n\tvar flag = true;\n\t\n\t// Get the values from the text fields\n\tvar songName = songNameTextField.value;\n\tvar artist = artistTextField.value;\n\tvar composer = composerTextField.value;\n\t\n\t// A regular expression used to test against the values above\n\tvar regExp = /^[A-Za-z0-9\\?\\$'&!\\(\\)\\.\\-\\s]*$/;\n\t\n\t// Make sure the song name is valid\n\tif (songName == \"\" || !regExp.test(songName)) {\n\t\tflag = false;\n\t\talert(\"Please enter a song name. Name can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t// Make sure the artist is valid\n\telse if (artist == \"\" || !regExp.test(artist)) {\n\t\tflag = false;\n\t\talert(\"Please enter an artist. Artist can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t// Make sure the composer is valid\n\telse if (composer == \"\" || !regExp.test(composer)) {\n\t\tflag = false;\n\t\talert(\"Please enter a composer. Composer can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t\n\treturn flag;\n}", "validate(event) {\n\t\tevent.preventDefault();\n\n\t\tlet valid = true;\n\n\t\tconst form = document.forms['form'];\n\t\tconst formNodes = Array.prototype.slice.call(form.childNodes);\n\t\tvalid = this.props.schema.fields.every(field => {\n\t\t\tconst input = formNodes.find(node => node.id === field.id);\n\n\t\t\t// Check field is answered if mandatory\n\t\t\tif (!field.optional || typeof field.optional === 'object') {\n\t\t\t\tlet optional;\n\n\t\t\t\t// Check type of 'optional' field.\n\t\t\t\tif (typeof field.optional === 'object') {\n\n\t\t\t\t\t// Resolve condition in 'optional' object.\n\t\t\t\t\tconst dependentOn = formNodes.find(node => node.id === field.optional.dependentOn);\n\t\t\t\t\tconst dependentOnValue = this.getValue(dependentOn, field.type);\n\n\t\t\t\t\t// Try and find a value in schema 'values' object that matches a value\n\t\t\t\t\t// given in 'dependentOn' input.\n\t\t\t\t\t// Otherwise, use the default value provided.\n\t\t\t\t\tconst value = field.optional.values.find(val => dependentOnValue in val);\n\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\toptional = value[dependentOnValue];\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptional = field.optional.default;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t// Else 'optional' field is just a boolean value.\n\t\t\t\t\toptional = field.optional;\n\t\t\t\t}\n\n\t\t\t\t// If not optional, make sure input is answered.\n\t\t\t\tif (!optional) {\n\t\t\t\t\treturn Boolean(this.getValue(input, field.type));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn field.validations.every(validation => {\n\t\t\t\tif (validation.containsChar) {\n\t\t\t\t\t// Ensure input value has the specified char.\n\t\t\t\t\treturn this.getValue(input, field.type).trim().includes(validation.containsChar);\n\n\t\t\t\t} else if (validation.dateGreaterThan) {\n\t\t\t\t\t// Ensure difference between today and given date is larger than specified interval.\n\t\t\t\t\tconst value = this.getValue(input, field.type);\n\n\t\t\t\t\tlet diff = Date.now() - new Date(value).getTime();\n\n\t\t\t\t\t// Convert from milliseconds to the unit given in schema.\n\t\t\t\t\tswitch(validation.dateGreaterThan.unit) {\n\t\t\t\t\t\tcase \"seconds\":\n\t\t\t\t\t\t\tdiff = diff / 1000;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"minutes\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"hours\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"days\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"years\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24 / 365;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\treturn diff > validation.dateGreaterThan.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\t// If all checks pass, submit the form. Otherwise alert the user.\n\t\tif (valid) {\n\t\t\tthis.submit();\n\t\t} else {\n\t\t\talert(\"Form is not valid. Please make sure all inputs have been correctly answered.\");\n\t\t}\n\n\t}", "function valida(obj) {\r\nfrm=obj.form;\r\n\r\n\r\nif (frm.habi_user.checked!=true && frm.habi_tipo_user.checked!=true && frm.habi_alto_nivel.checked!=true && frm.habi_perfiles.checked!=true && frm.habi.checked!=true) {\r\n\t alert(\"Debe Indicar al menos una opci\\u00f3n para realizar la Consulta de Usuarios\");\r\n\t return false\r\n\t}\r\n\r\n\r\n\r\nif (frm.habi_user.checked !=false){\r\n\t if (vacio(frm.nb_usuarios.value)==false) {\r\n alert(\"Debe Indicar el Nombre del Usuario\");\r\n frm.nb_usuarios.focus(); \r\n return false\r\n\t }\r\n}\r\n\r\nif (frm.habi_tipo_user.checked !=false){\r\n\tif ((frm.tipo_usuario.selectedIndex)==0) {\r\n alert(\"Debe Seleccionar el Tipo de Usuario\"); \r\n frm.tipo_usuario.focus();\r\n return false\r\n\t}\r\n}\r\n\nif (frm.habi_alto_nivel.checked !=false){\r\n\tif (frm.alto_nivel.selectedIndex==0) {\r\n\t\talert(\"Debe Seleccionar el Alto Nivel\"); \r\n\t\tfrm.alto_nivel.focus();\r\n\t\treturn false\r\n\t}\r\n}\r\n\t \r\nif (frm.habi_perfiles.checked !=false){\r\n\tif (frm.perfiles.selectedIndex==0) {\r\n\t\talert(\"Debe Seleccionar el Perfil\"); \r\n\t\tfrm.perfiles.focus();\r\n\t\treturn false\r\n\t\t}\r\n}\r\n\r\nreturn true \r\n}", "function checkFormValidity() {\n var inputs = document.querySelectorAll('input'),\n i;\n\n for (i = 0; i < inputs.length; i = i + 1) {\n customCheckValidity(inputs[i]);\n }\n }" ]
[ "0.77663404", "0.7680214", "0.7641938", "0.75574666", "0.745958", "0.74075925", "0.7387387", "0.7375239", "0.7369232", "0.72942215", "0.7291866", "0.72850144", "0.72816", "0.7257996", "0.72522587", "0.7246838", "0.72438323", "0.7233917", "0.72313005", "0.72135985", "0.7205324", "0.71825135", "0.7166845", "0.7146695", "0.7136379", "0.7132363", "0.7129326", "0.7117027", "0.7104309", "0.70954365", "0.70822203", "0.70794135", "0.706316", "0.7060653", "0.70516896", "0.70516896", "0.70514953", "0.70508295", "0.7034069", "0.70266116", "0.7009647", "0.7009127", "0.699494", "0.69732714", "0.6969581", "0.69565696", "0.6955911", "0.6955473", "0.695285", "0.6951078", "0.69492304", "0.6946044", "0.69444346", "0.69431597", "0.6939862", "0.6933231", "0.69330055", "0.6926147", "0.6919238", "0.6918811", "0.69187456", "0.6918111", "0.6916791", "0.6914461", "0.69102067", "0.6908883", "0.6898743", "0.6897505", "0.6896068", "0.6896068", "0.68927413", "0.6892649", "0.687769", "0.68754023", "0.6843829", "0.68427724", "0.6842263", "0.684058", "0.6838893", "0.6835839", "0.6835388", "0.68327355", "0.6824247", "0.6823713", "0.68152237", "0.6813215", "0.68052113", "0.67982477", "0.6798245", "0.67967314", "0.6791881", "0.678726", "0.6785572", "0.6785274", "0.6785273", "0.6783102", "0.678061", "0.6767051", "0.6765034", "0.6763894", "0.67628515" ]
0.0
-1
creates a badge for some container jQuery is required for this plugin
function RT_Badge(userOpts) { this.$badge = null; this.z = 0; this.opts = { container : $("body")[0], position : "topright", theme : "red", offsetX : -10, offsetY : -10, animate : "blink", shape : "round", x : 0 }; // add the badge to the page this.apply = function(userOpts) { this.opts = $.extend(this.opts,userOpts); var $container = $(this.opts.container); if(!this.$badge) { this.$badge = $("<div class='rt_badge'></div>"); // determine where to put the badge var left = $container.offset().left; var top = $container.offset().top; this.$badge.css({ left:left + $container.outerWidth() + this.opts.offsetX, top:top + this.opts.offsetY }); if(this.opts.shape == "square") this.$badge.addClass("square"); $("body").append(this.$badge); // update badge info this.update(this.opts.x); } } // blink the object this.blink = function() { if(this.$badge.css("display") == "none") { this.$badge.stop().fadeIn().fadeOut().fadeIn(); } else { this.$badge.stop().fadeOut().fadeIn(); } } // show the object this.show = function() { switch(this.opts.animate) { case "blink": this.z ? this.blink() : this.hide(); break; case "none": default: this.z ? this.$badge.show() : this.hide(); break; } } // hide it this.hide = function() { if(this.$badge) { this.$badge.fadeOut(); } } // update the text this.update = function(x) { this.opts = $.extend(this.opts,userOpts); if(this.$badge) { // allow for +1 and -1 x = x.toString(); var y = parseInt(x.substr(1,x.length)); if(x.charAt(0) == "+") { this.z += y; } else if(x.charAt(0) == "-") { // protect against neg numbers this.z = this.z <= 0 ? 0 : this.z - y; } else { this.z = parseInt(x); } // set the text this.$badge.text(this.z); // show the badge this.show(); // if there is no badge, add it } else { this.apply({x : x}); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createFloatingBadge(mode, status, ht = 160) {\n const iconUrl = \"https://kkapuria3.github.io/images/KK.png\";\n const iconUrl1 = \"https://i.pinimg.com/600x315/cd/28/16/cd28168e19f7fdf9c666edd083921129.jpg\"\n const iconUrl2 = \"https://brandlogovector.com/wp-content/uploads/2020/07/Discord-Logo-Icon-Small.png\"\n const iconUrl3 = \"https://img.icons8.com/cotton/2x/source-code.png\"\n\n const script = document.createElement('script');\n\n const $container = document.createElement(\"div\");\n const $bg = document.createElement(\"div\");\n\n const $link = document.createElement(\"a\");\n const $link1 = document.createElement(\"a\");\n const $link2 = document.createElement(\"a\");\n const $link3 = document.createElement(\"a\");\n\n const $img = document.createElement(\"img\");\n const $img1 = document.createElement(\"img\");\n const $img2 = document.createElement(\"img\");\n const $img3 = document.createElement(\"img\");\n\n const $text = document.createElement(\"P\");\n const $BAGDE_BORDER = document.createElement(\"P\");\n const $mode = document.createElement(\"P\");\n const $status1 = document.createElement(\"P\");\n\n script.setAttribute('type', 'text/javascript');\n script.setAttribute('src', 'https://cdn.jsdelivr.net/npm/brython@3.9.5/brython.min.js');\n\n $link.setAttribute(\"href\", \"https://github.com/kkapuria3\");\n $link.setAttribute(\"target\", \"_blank\");\n $link.setAttribute(\"title\", \"RefreshNoBot\");\n\n $link1.setAttribute(\"href\", \"https://www.buymeacoffee.com/kapuriakaran\");\n $link1.setAttribute(\"target\", \"_blank\");\n $link1.setAttribute(\"title\", \"Buy Dev a Coffee\");\n\n $link2.setAttribute(\"href\", \"https://discord.gg/UcxcyxS5X8\");\n $link2.setAttribute(\"target\", \"_blank\");\n $link2.setAttribute(\"title\", \"Join Discord\");\n\n $link3.setAttribute(\"href\", \"https://www.buymeacoffee.com/kapuriakaran\");\n $link3.setAttribute(\"target\", \"_blank\");\n $link3.setAttribute(\"title\", \"View Source Code\");\n\n $img.setAttribute(\"src\", iconUrl);\n $img1.setAttribute(\"src\", iconUrl1);\n $img2.setAttribute(\"src\", iconUrl2);\n $img3.setAttribute(\"src\", iconUrl3);\n var MAIN_TITLE = (\"Open Source Amazon-Bot v1.1-beta ◻️ TESTMODE: \" + TESTMODE + \" ◻️ ITEM KEYWORD: \" + AMAZON_PRODUCT_ID + \" ◻️ CUTOFF PRICE : \" + CUTOFF_PRICE);\n $BAGDE_BORDER.innerText = (\"------------------------------------------------------------------------------------------------------------------------------------ \");\n $text.innerText = MAIN_TITLE;\n $mode.innerText = mode;\n $status1.innerText = status;\n\n $container.style.cssText = \"position:fixed;left:0;bottom:0;width:950px;height:\" + ht + \"px;background: black; border: 1px solid #FFF\";\n $bg.style.cssText = \"position:absolute;left:-100%;top:0;width:60px;height:350px;background:#1111;box-shadow: 0px 0 10px #060303; border: 1px solid #FFF;\";\n $link.style.cssText = \"position:absolute;display:block;top:11px;left: 10px; z-index:10;width: 30px;height:30px;border-radius: 1px;overflow:hidden;\";\n $link1.style.cssText = \"position:absolute;display:block;top:40px;left: 0px; z-index:10;width: 50px;height:50px;border-radius: 0px;overflow:hidden;\";\n $link2.style.cssText = \"position:absolute;display:block;top:70px;left: 0px; z-index:10;width: 50px;height:50px;border-radius: 0px;overflow:hidden;\";\n $link3.style.cssText = \"position:absolute;display:block;top:118px;left: 12px; z-index:10;width: 25px;height:25px;border-radius: 0px;overflow:hidden;\";\n $img.style.cssText = \"display:block;width:100%\";\n $img1.style.cssText = \"display:block;width:100%\";\n $img2.style.cssText = \"display:block;width:100%\";\n $img3.style.cssText = \"display:block;width:100%\";\n $text.style.cssText = \"position:absolute;display:block;top:3px;left: 50px;background: transperant; color: white;\";\n $BAGDE_BORDER.style.cssText = \"position:absolute;display:block;top:22px;left: 50px;background: transperant; color: green;\";\n $mode.style.cssText = \"position:absolute;display:block;top:43px;left: 50px;background: transperant; color: white;\";\n $status1.style.cssText = \"position:absolute;display:block;top:64px;left: 50px;background: transperant; color: white;\";\n //\n //\n $link.appendChild($img);\n $link1.appendChild($img1);\n $link2.appendChild($img2);\n $link3.appendChild($img3);\n $container.appendChild(script);\n $container.appendChild($bg);\n $container.appendChild($link);\n $container.appendChild($link1);\n $container.appendChild($link2);\n $container.appendChild($link3);\n $container.appendChild($text);\n $container.appendChild($BAGDE_BORDER);\n $container.appendChild($mode);\n $container.appendChild($status1)\n return $container;\n }", "function bsBadge(){return _callWithEmphasis(this, oj.span, 'badge', 'default', arguments)}", "function setupBadgePresetForm(container){\r\n\r\n setupForm(container);\r\n\r\n container.find('img').hide().load(function(){\r\n $(this).fadeIn();\r\n });\r\n\r\n var badgePreview = $('.badgecreator .preview img', container);\r\n var parts = (badgePreview.attr('src') != '')?badgePreview.attr('src').split('?')[1].split('&'):[];\r\n var po = {};\r\n for(var i=0; i<parts.length; i++){\r\n parts[i] = parts[i].split('=');\r\n po[parts[i][0]] = parts[i][1];\r\n }\r\n\r\n var currentShape, currentPattern, currentColor;\r\n if(po.s) currentShape = container.find('.shapes > li > a[data-name=\"'+po.s+'\"]').addClass('selected').data('name');\r\n else currentShape = container.find('.shapes > li > a')\r\n .eq(\r\n Math.round(\r\n Math.random()*(container.find('.shapes > li > a').length-1)\r\n )\r\n )\r\n .addClass('selected').data('name');\r\n\r\n if(po.p) currentPattern = container.find('.patterns > li > a[data-name=\"'+po.p+'\"]').addClass('selected').data('name');\r\n else currentPattern = container.find('.patterns > li > a')\r\n .eq(\r\n Math.round(\r\n Math.random()*(container.find('.patterns > li > a').length-1)\r\n )\r\n )\r\n .addClass('selected').data('name');\r\n\r\n if(po.c) currentColor = po.c;\r\n else currentColor = ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6);\r\n\r\n badgePreview.attr('src', '/svg?p='+currentPattern+'&s='+currentShape+'&c='+currentColor);\r\n\r\n container.find('#keywords').each(function(){\r\n $(this).autocomplete({\r\n serviceUrl: '/ajax/tag',\r\n delimiter: /(,|;)\\s*/,\r\n paramName: 'q'\r\n });\r\n });\r\n\r\n $('a[href=\"#change-pattern\"]', container).click(function(){\r\n currentPattern = $(this).data('name');\r\n $(this).parent().parent().find('a.selected').removeClass('selected');\r\n $(this).addClass('selected');\r\n badgePreview.attr('src', '/svg?p='+currentPattern+'&s='+currentShape+'&c='+currentColor);\r\n return false;\r\n });\r\n\r\n $('a[href=\"#change-shape\"]', container).click(function(){\r\n currentShape = $(this).data('name');\r\n $(this).parent().parent().find('a.selected').removeClass('selected');\r\n $(this).addClass('selected');\r\n badgePreview.attr('src', '/svg?p='+currentPattern+'&s='+currentShape+'&c='+currentColor);\r\n return false;\r\n });\r\n\r\n container.find('input[type=\"button\"].submit').click(function(e){\r\n e.preventDefault();\r\n var _this = this;\r\n var pid = ($('#preset-id').val() != '')?$('#preset-id').val():null;\r\n var ok = true;\r\n\r\n if($('#name').val() == '') { $('#name').addClass('error'); ok = false; }\r\n if($('#keywords').val() == '') { $('#keywords').addClass('error'); ok = false; }\r\n\r\n if(ok){\r\n $.ajax({\r\n 'url': '/ajax/savepreset',\r\n 'type': 'POST',\r\n 'data': {\r\n 'name': $('#name').val(),\r\n 'img': badgePreview.attr('src'),\r\n 'keywords': $('#keywords').val(),\r\n 'comment': $('#comment').val(),\r\n 'proof': $('#proof').val(),\r\n 'id': pid\r\n },\r\n 'success' : function(data){\r\n if(!data.error){\r\n if($(_this).hasClass('small')){\r\n $('#name').val('');\r\n $('#keywords').val('').change();\r\n $('#comment').val('').change();\r\n $('#proof').val('').change();\r\n $('#preset-id').val('');\r\n\r\n currentShape = container.find('.shapes > li > a')\r\n .eq(\r\n Math.round(\r\n Math.random()*(container.find('.shapes > li > a').length-1)\r\n )\r\n )\r\n .addClass('selected').data('name');\r\n currentPattern = container.find('.patterns > li > a')\r\n .eq(\r\n Math.round(\r\n Math.random()*(container.find('.patterns > li > a').length-1)\r\n )\r\n )\r\n .addClass('selected').data('name');\r\n currentColor = ('000000' + Math.floor(Math.random()*16777215).toString(16)).slice(-6);\r\n $(\"#shape-color\").spectrum('set', currentColor);\r\n\r\n badgePreview.attr('src', '/svg?p='+currentPattern+'&s='+currentShape+'&c='+currentColor);\r\n\r\n showMessage('Preset wurde erstellt',$('.message', container), false);\r\n } else {\r\n hideModal();\r\n }\r\n\r\n $.ajax({\r\n 'url': '/ajax/minpreset?id='+data.id,\r\n 'type': 'GET',\r\n 'success' : function(data){\r\n if(pid){\r\n $('.badges').isotope('remove', $('.badges .badge[data-id=\"'+pid+'\"]'));\r\n }\r\n var item = $(data);\r\n $('.badges').isotope( 'insert', item);\r\n setupBadgePreset(item);\r\n }\r\n });\r\n } else {\r\n //modalAlert(data.msg);\r\n showMessage(data.msg,$('.message', container), true);\r\n }\r\n }\r\n });\r\n }\r\n });\r\n\r\n $(\"#shape-color\").spectrum({\r\n color: currentColor,\r\n localStorageKey: 'shapeColors',\r\n showPalette: true,\r\n showSelectionPalette: true,\r\n palette: ['#ffcc00', '#0070af'],\r\n showInitial: true,\r\n preferredFormat: 'hex',\r\n showInput: true,\r\n show: function(color) {\r\n var c = $(\"#shape-color\").spectrum('container');\r\n var o = c.offset();\r\n c.css('left', (o.left-14)+'px').css('top', (o.top+5)+'px');\r\n return true;\r\n }, change : function(color){\r\n currentColor = color.toHexString().substr(1);\r\n badgePreview.attr('src', '/svg?p='+currentPattern+'&s='+currentShape+'&c='+currentColor);\r\n }\r\n });\r\n\r\n $('.slider', container).each(function(){\r\n setupSlider($(this));\r\n });\r\n}", "function findContainer() {\n if (guid) {\n $container = $j('.jive-content-rating[data-guid=\"'+ guid +'\"]');\n } else {\n $container = $j('#jive-content-rating');\n }\n }", "function identify_badges() {\n jQuery.each($('.bandBadge'), function(i) {\n this.json = json[i];\n this.queue = [new Song(this.json[\"bName\"],\n this.json[\"aName\"],\n this.json[\"sName\"],\n this.json[\"sPath\"],\n this.json[\"bPic\"])];\n badges[i] = this;\n\n });\n }", "function badges(badge) {\r\n return e('img', {\r\n key: badge.id\r\n , src: badge.image\r\n , className: 'badge'\r\n , alt: badge.name\r\n , style: { width: '25px', height: '25px' }\r\n })\r\n }", "function createBadge() {\n badges = game.add.physicsGroup();\n var badge = badges.create(750, 400, 'badge');\n badge.animations.add('spin');\n badge.animations.play('spin', 10, true);\n}", "function createBadge() {\n badges = game.add.physicsGroup();\n let badge = badges.create(750, 400, 'badge');\n badge.animations.add('spin');\n badge.animations.play('spin', 10, true);\n}", "function createCommunityDivForPanel(response,flag,extClass){\r\n console.log(response);\r\n var badge = '';\r\n var badge2 = '';\r\n var panelForwarded = 'discussion';\r\n var numberUser = '';\r\n try{\r\n if(flag==0 || flag==2){\r\n\r\n var panelComImage = response.image;\r\n var panelComId = response._id;\r\n var panelComName = response.name;\r\n\r\n if(flag==2)\r\n {\r\n numberUser = 'Request('+response.request.length+')';\r\n numberUser = \"<a class='comnametxt-user' href='/community/manageCommunity/\"+panelComId+\"'>\"+numberUser+\"</a>\";\r\n badge = '<label class=\"label label-success\" style=\"cursor:pointer !important;\"><i class=\"fa fa-cogs\"></i></label>';\r\n }else{\r\n numberUser = 'Members('+response.user.length + response.admin.length+')';\r\n numberUser = \"<a class='comnametxt-user' href='/community/communitymembers/\"+panelComId+\"'>\"+numberUser+\"</a>\";\r\n badge = '<label class=\"label label-success\" style=\"cursor:pointer !important;\"><i class=\"fa fa-cogs\"></i></label>';\r\n }\r\n }else if(flag==1){\r\n var panelComImage = response.image;\r\n var panelComId = response._id;\r\n var panelComName = response.name;\r\n panelForwarded = 'communityprofile';\r\n numberUser = 'Members('+response.request.length+')';\r\n numberUser = \"<a class='comnametxt-user' style='text-decoration:none;color:black;cursor:context-menu'>\"+numberUser+\"</a>\";\r\n badge = '<label class=\"label label-danger\" style=\"cursor:pointer !important;\"><i class=\"fa fa-times\"></i></label>';\r\n badge2 = '<label class=\"label label-danger\">Pending</label>&nbsp;&nbsp;&nbsp;';\r\n }else if(flag==3){\r\n var panelComImage = response.image;\r\n var panelComId = response._id;\r\n var panelComName = response.name;\r\n panelForwarded = 'communityprofile';\r\n numberUser = 'Members('+response.request.length+')';\r\n numberUser = \"<a class='comnametxt-user' style='text-decoration:none;color:black;cursor:context-menu'>\"+numberUser+\"</a>\";\r\n badge = '<label class=\"label label-success\" style=\"cursor:pointer !important;\"><i class=\"fa fa-times\"></i></label>';\r\n badge2 = '<label class=\"label label-success\">Invitation</label>&nbsp;&nbsp;&nbsp;';\r\n }\r\n code=\"<div class='col-sm-12 col-xs-12 \"+extClass+\" community-div' style='margin-top:5px;' id='can\"+panelComId+\"'>\";\r\n code +=\"<div class='col-sm-1 col-xs-3' style='padding:10px;z-index:1'>\";\r\n code +=\"<a href='/community/\"+panelForwarded+\"/\"+panelComId+\"'><img src='/Upload/CommunityProfile/\"+panelComImage+\"' class='cpic'></a>\";\r\n code +=\"</div>\";\r\n code +=\"<div class='col-sm-10 col-xs-7' style='padding-top:25px;padding-bottom:5px;overflow:scroll'>\";\r\n code +=\" <p style='margin:0'><a class='comnametxt' href='/community/\"+panelForwarded+\"/\"+panelComId+\"'>\"+badge2+panelComName+\"</a>&nbsp;&nbsp;&nbsp;\"+numberUser+\"</p>\";\r\n code +=\"</div>\";\r\n code +=\"<div class='col-sm-1 col-xs-2' style='padding:0'>\";\r\n if(flag==1)\r\n {\r\n code +=\"<a class='community-short-btn' onclick='cancelRequest(\\\"\"+panelComId+\"\\\")' style='float:right'>\";\r\n code +=badge+\"</a>\";\r\n } else if(flag==2)\r\n {\r\n code +=\"<a class='community-short-btn' href='/community/manageCommunity/\"+panelComId+\"' style='float:rignt'>\";\r\n code +=badge+\"</a>\";\r\n }else if(flag==3)\r\n {\r\n code +=\"<a class='fa fa-check' onclick='acceptInvitation(\\\"\"+panelComId+\"\\\")' style='float:right'>\";\r\n code +=badge+\"</a>\";\r\n }\r\n code +=\"</div>\";\r\n code +=\"</div>\";\r\n anyCommunity = true;\r\n }catch(err){\r\n code = '';\r\n }\r\n return code;\r\n}", "function setupBadgeForm(container){\r\n setupForm(container);\r\n\r\n container.find('#rating').change(function(e){\r\n switch($(e.target).val()){\r\n case '0': container.find('.badge').removeClass('bronze silver gold').addClass('bronze'); break;\r\n case '2': container.find('.badge').removeClass('bronze silver gold').addClass('gold'); break;\r\n default: container.find('.badge').removeClass('bronze silver gold').addClass('silver'); break;\r\n }\r\n });\r\n\r\n var handleSemesterChange = function(e){\r\n $.ajax({\r\n 'url': '/ajax/candidates',\r\n 'type': 'GET',\r\n 'data': {\r\n 'y': $('#year').val(),\r\n 's': $('#semester').val(),\r\n 'id': $('#preset-id').val()\r\n },\r\n 'success' : function(data){\r\n if(!data.error) $('#students').val(data.count);\r\n }\r\n });\r\n };\r\n\r\n container.find('#semester').change(handleSemesterChange);\r\n container.find('#year').change(handleSemesterChange);\r\n\r\n container.find('#lva').each(function(){\r\n $(this).autocomplete({\r\n serviceUrl: $(this).data('serviceurl'),\r\n paramName: 'q',\r\n preventBadQueries: false,\r\n onSelect: function(d){\r\n $('#lva_id').val(d.data.id);\r\n //$('#students').val(d.data.students);\r\n }\r\n });\r\n });\r\n\r\n container.find('#awardee').each(function(){\r\n var lastValue = '';\r\n $(this).change(function(){\r\n if($(this).val() != lastValue) {\r\n $('#awardee_id').val('');\r\n }\r\n }).autocomplete({\r\n serviceUrl: $(this).data('serviceurl'),\r\n paramName: 'q',\r\n params: {'pid': $('#preset-id').val()},\r\n onSelect: function(d){\r\n lastValue = d.value;\r\n $('#awardee_id').val(d.data);\r\n }\r\n });\r\n });\r\n\r\n container.find('#keywords').each(function(){\r\n $(this).autocomplete({\r\n serviceUrl: '/ajax/tag',\r\n delimiter: /(,|;)\\s*/,\r\n paramName: 'q'\r\n });\r\n });\r\n\r\n container.find('#awarder').data('oldvalue', container.find('#awarder').val()).change(function(){\r\n if($(this).val() == $(this).data('oldvalue')){\r\n $('.opt.issuer').fadeOut();\r\n } else {\r\n $('.opt.issuer').fadeIn();\r\n }\r\n });\r\n\r\n container.find('input[type=\"button\"].submit').click(function(e){\r\n e.preventDefault();\r\n\r\n var _this = this;\r\n\r\n var data = {\r\n 'keywords': $('#keywords').val(),\r\n 'comment': $('#comment').val(),\r\n 'pid': $('#preset-id').val(),\r\n 'rating': $('#rating').val(),\r\n 'year': $('#year').val(),\r\n 'semester': $('#semester').val()\r\n }\r\n\r\n container.find('.error').removeClass('error');\r\n\r\n var ok = true;\r\n\r\n if($('#awardee_id').val() != '') data['awardee_id'] = $('#awardee_id').val();\r\n else if ($('#awardee').val() != '') data['awardee'] = $('#awardee').val();\r\n else { $('#awardee').addClass('error'); ok = false; }\r\n\r\n if($('#lva_id').val() != '') data['lva_id'] = $('#lva_id').val();\r\n else if ($('#lva').val() != '') data['lva'] = $('#lva').val();\r\n else { $('#lva').addClass('error'); ok = false; }\r\n\r\n if($('#students').val() != '' || $('#students').val() > 0) data['students'] = $('#students').val();\r\n else { $('#students').addClass('error'); ok = false; }\r\n\r\n if($('#proof').val() != '') data['proof'] = $('#proof').val();\r\n else { $('#proof').addClass('error'); ok = false; }\r\n\r\n if($('#awarder').val() != $('#awarder').data('oldvalue')) data['awarder'] = $('#awarder').val();\r\n\r\n if(ok){\r\n $.ajax({\r\n 'url': '/ajax/issue',\r\n 'type': 'POST',\r\n 'data': data,\r\n 'success' : function(data){\r\n if(!data.error){\r\n if($(_this).hasClass('small')){\r\n $('#awardee').val('').change();\r\n $('#awardee_id').val('').change();\r\n //$('#lva').val('').change();\r\n //$('#lva_id').val('').change()\r\n //$('#students').val('').change();\r\n //$('#proof').val('').change();\r\n //$('#comment').val('').change();\r\n $('#rating').val('0').change();\r\n //$('#awarder').val($('#awarder').data('oldvalue')).change();\r\n showMessage('Badge wurde vergeben',$('.message', container), false);\r\n } else {\r\n hideModal();\r\n }\r\n } else {\r\n //modalAlert(data.msg);\r\n showMessage(data.msg,$('.message', container), true)\r\n }\r\n }\r\n });\r\n }\r\n });\r\n}", "function addBadges(badgeCollect, badgeNum, badgeTitle, imgurID) {\n //since the badges are child of childs, just search innerHTML for original-title=\"Broadcaster\"\n //or similar. Basically use the same method that I did for my original greasemonkey script at this point.\n //I've narrowed it down to badges so that the message doesn't screw up my detection.\n\n let badgeCSS = \"customTTVBadge\" + badgeNum;\n\n if(badgeCollect.innerHTML.indexOf(badgeCSS) === -1) {\n let tempBadge = document.createElement(\"a\");\n tempBadge.setAttribute(\"target\", \"_blank\");\n tempBadge.setAttribute(\"rel\", \"noopener\");\n \n tempBadge.innerHTML = \"<img class=\\\"badge-img tooltip custom-badge-img \" + badgeCSS + \"\\\" src=\\\"https://i.imgur.com/\" + imgurID + \"\\\" title=\\\"\" + badgeTitle + \"\\\">\";\n \n badgeCollect.appendChild(tempBadge);\n }\n}", "get widgetClass() {\n // If we don't have a badge, our classList doesn't include \"b-badge\"\n if (this.badge) {\n return 'b-badge';\n }\n }", "appendContainer() {\n\t\t\tlet beatyboxContainer = document.createElement('div');\n\t\t\tbeatyboxContainer.classList.add('beatybox-container');\n\n\t\t\t//add custom styles\n\t\t\t$(beatyboxContainer).css('animationDuration', params.animationDuration + 's');\n\t\t\t$(beatyboxContainer).css('animationName', params.animationNameEntrance || \"fadeIn\");\n\n\t\t\t$('body').append(beatyboxContainer);\n\n\t\t\t//determing the type of closure\n\t\t\tif(params.closing === \"tap\" || params.closing == null) {\n\t\t\t\t$(document).on('click', (e)=>{\n\t\t\t\t\tif(e.target && e.target.classList.contains('beatybox-container')) {\n\t\t\t\t\t\tthis.removeContainer();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} else if(params.closing === \"cross\") {\n\t\t\t\tlet cross = new beatyboxClose\n\t\t\t\tcross.appendClose();\n\t\t\t} else if(params.closing === \"all\") {\n\t\t\t\t$(document).on('click', (e)=>{\n\t\t\t\t\tif(e.target && e.target.classList.contains('beatybox-container')) {\n\t\t\t\t\t\tthis.removeContainer();\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\tlet cross = new beatyboxClose;\n\t\t\t\tcross.appendClose()\n\t\t\t}\n\n\t\t}", "function insertAlertBox() {\n $( 'body' ).append( '<div id=\"alert-container\"></div>' );\n }", "injuryStatus(status){\n let indc = $('.inj-indicator', this.content);\n let iconc = $('.ra', this.content);\n let badge;\n if(status){\n switch(status){\n case 'normal':\n badge = {status: 'normal', class: 'badge-hidden'};\n iconc.removeClass('ra-3x');\n iconc.addClass('ra-4x');\n break;\n case 'injured':\n badge = {status: 'injured', class: 'badge-warning'};\n iconc.removeClass('ra-4x');\n iconc.addClass('ra-3x');\n break;\n case 'near-death':\n badge = {status: 'near-death', class: 'badge-danger'};\n iconc.removeClass('ra-4x');\n iconc.addClass('ra-3x');\n break;\n }\n }else{\n switch(this.injStatus){\n case 'normal':\n badge = {status: 'injured', class: 'badge-warning'};\n iconc.removeClass('ra-4x');\n iconc.addClass('ra-3x');\n $(this.content).effect('shake');\n break;\n case 'injured':\n badge = {status: 'near-death', class: 'badge-danger'};\n $(this.content).effect('shake');\n break;\n case 'near-death':\n badge = {status: 'normal', class: 'badge-hidden'};\n iconc.removeClass('ra-3x');\n iconc.addClass('ra-4x');\n break;\n }\n\n }\n indc.html(badge.status);\n indc.removeClass('badge-danger badge-hidden badge-warning');\n indc.addClass(badge.class);\n this.injStatus = badge.status;\n }", "function create_container($) {\n \n // set body to relative - may not be necessary\n document.body.style.position = \"relative\";\n \n var d = document.createElement('div');\n $(d).css({\n \"background-color\": \"#ffffff\",\n \"border\": \"1px solid #000000\",\n \"font-size\": \"small\",\n \"padding\": \"2px\",\n \"position\": \"fixed\",\n \"right\": \"0\",\n \"top\": \"0\",\n \"bottom\": \"0\",\n \"overflow\": \"scroll\",\n \"zIndex\": \"1000\",\n \"display\": \"none\",\n }).attr('id', 'container');\n $(d).prependTo($(\"body\"));\n \n }", "function addNotification(icon) {\n // Get the app\n let app = icon.parentElement;\n // Get the badge\n let badge = app.getElementsByClassName('badge')[0];\n // Get the badge count\n let badgeCount = getBadgeCount(badge);\n // Increate by between 1 and 3\n badgeCount = badgeCount + 1 + Math.floor(Math.random() * 3);\n // Set the badge\n setBadgeCount(icon, badgeCount);\n // Start a new timer\n addNotificationTimer(icon);\n}", "getDynamicBadges() {\n let classes = \"badge m-2 badge-\";\n classes += this.state.value === 0 ? \"warning\" : \"primary\";\n return classes;\n }", "get widgetClass() {\n // If we don't have a badge, our classList doesn't include \"b-badge\"\n if (this.badge) {\n return 'b-badge';\n }\n }", "createLifeBar() {\n const lifeContainer = document.createElement(\"div\");\n lifeContainer.id = \"life_container\";\n return lifeContainer;\n }", "renderBadge() {\n return html`\n <div class=\"TWPT-badge\">\n <md-icon>repeat</md-icon>\n </div>\n `;\n }", "function set_badge(on) {\n $('#server_status_badge').removeClass();\n $('#server_status_badge').addClass('badge');\n $('#server_status_badge').addClass('badge-pill');\n if (on) {\n $('#server_status_badge').addClass('badge-success');\n $('#server_status_badge').text('Online');\n\n // Now that it's online, enable the new project button!\n // (Only if the check isn't shown.)\n if ($('#success_check').is(':hidden')) {\n $('#new_proj_btn').css('pointer-events', 'auto');\n $('#new_proj_btn').prop('disabled', false);\n }\n\n // remove popover\n $('#new_proj_btn_span').popover('hide');\n $('#new_proj_btn_span').popover('disable');\n $('#new_proj_btn_span').popover('dispose');\n\n } else {\n $('#server_status_badge').addClass('badge-danger');\n $('#server_status_badge').text('Offline');\n }\n}", "function createBadge(item) {\n var output = \"\";\n\n // create the output\n output += \"<div class='characterSheetItemFormatter' style='height:110px'>\";\n output += \"<div class='characterSheetHeader' style='float:left; width: 125px'>\";\n output += \"<b>\" + item.name + \"</b></div>\";\n output += \"<div class='characterSheetHeader' style='width: 125px; height: 80px; \";\n output += \"text-align: center; display: table-cell; vertical-align: middle; margin:auto'>\";\n output += \"<img src='\" + item.image;\n output += \"' onmouseover=\\'showToolTip(\\\"\";\n output += \"<b>\" + item.name + \"</b><br>\" + item.description;\n output += \"\\\");\\' onmouseout=\\\"hideToolTip()\\\" onclick=\\\"removeToolTip();\\\" \";\n output += \"style=\\\"cursor: pointer; \\\"\";\n output += \"' /></div></div>\";\n \n return output;\n}", "function circloidRevealBugFix(){\n\t// Reveal Badges\n\tsetTimeout(function(){\n\t\t$(\"#header > .nav > li.dropdown .label\").animate({\"opacity\":\"show\"}, 500, \"easeOutQuart\");\n\t\t$(\".menu-item-top > a.top > .badge\").animate({\"opacity\":1}, 500, \"easeOutQuart\");\n\t}, badgeRevealTime);\n}", "function printingInfoContainer() {\n jQuery('<div id=\"ksp_printing_info\" class=\"popupinfo\"> \\\n <a class=\"viewerClose\" style=\"float: right; z-index: 100\" href=\"#\" onclick=\"shadowViewer.hide();return false;\"><img alt=\"close\" title=\"close\" src=\"/stores/realmadrid/artwork/english/interface/close_v1.jpg\"></a> \\\n <div class=\"content\"> \\\n <p class=\"printing_popup_title\">'+ ksp_popup_title +'</p> \\\n '+ ksp_popup_content +' \\\n </div> \\\n </div>').appendTo('body');\n}", "_createNotifElem(notif) {\n let notifElem = $(`<div id='${this._getNotifElemID(notif.key)}' class='notif'></div>`).data(\"notif\", notif);\n this._getNotifIconElem(notif.knownSeverity).appendTo(notifElem);\n\n if (notif.timestamp) {\n let time = notif.timestamp instanceof Date ? notif.timestamp.toLocaleString() : notif.timestamp;\n $(`<div class='notif-time'>${time}</div>`).appendTo(notifElem);\n }\n\n let messageElem = $(\"<div class='notif-msg'></div>\").appendTo(notifElem);\n\n if (notif.message instanceof jQuery) {\n messageElem.append(notif.message);\n } else if (notif.isHtml) {\n messageElem.html(notif.message);\n } else {\n messageElem.text(notif.message);\n }\n\n notifElem.data(\"notif\", notif);\n return notifElem;\n }", "function changeBadge(badge, msg, type='badge-secondary') {\n badge\n .removeClass()\n .addClass('badge')\n .addClass(type)\n .text(msg)\n .fadeIn(300);\n}", "updateNotificationBadge() {\n if (this.bannerMsgs.length < 2) {\n this.notificationBadge.classList.add('hidden');\n } else if (this.bannerMsgs.length > 9) {\n this.notificationBadge.classList.remove('hidden');\n this.notificationBadge.textContent = '∞';\n } else {\n this.notificationBadge.classList.remove('hidden');\n this.notificationBadge.textContent = this.bannerMsgs.length.toString();\n }\n }", "function _createCoverReplacement(container, width, height) {\n\t\t\t$(container).append('<span style=\"line-height: '+height+'px; color: '+options.metaColor+';\">&hellip;</span>');\n\t\t}", "function update_cart_icon(count)\n{\njQuery(\".cart_badge\").html(count);\n//setTimeout()\njQuery(\".item_added\").click();\nsetTimeout(hideItemAdded, 3000);\n}", "createReputationContainer() {\n let rep_container = document.createElement(\"div\");\n rep_container.id = \"reputation_container\";\n return rep_container;\n }", "function buildPopup () {\n if (!notifCounter) {\n const divNoNotif = document.createElement('div')\n divNoNotif.id = 'noNotif'\n divNoNotif.innerText = 'Aucune notification'\n contentDiv.appendChild(divNoNotif)\n if (debugMode) console.log(divNoNotif.innerText)\n }\n const body = document.body\n body.appendChild(contentDiv)\n // Remove useless nodes\n while (body.childNodes.length > 2) {\n body.removeChild(body.childNodes[1])\n }\n currentDom = body\n}", "getBadgeClasses() {\r\n let classes = \"badge m-1 badge-\";\r\n classes += (this.props.counter.value === 0) ? \"warning\" : \"primary\";\r\n return classes;\r\n }", "function look_ruby_sb_widget_instagram_popup() {\r\n if ('undefined' != typeof (look_ruby_sb_instagram_popup) && 1 == look_ruby_sb_instagram_popup) {\r\n $('.instagram-content-wrap .instagram-el a').magnificPopup({\r\n type: 'image',\r\n removalDelay: 200,\r\n mainClass: 'mfp-fade',\r\n closeOnContentClick: true,\r\n closeBtnInside: true,\r\n gallery: {\r\n enabled: true,\r\n navigateByImgClick: true,\r\n preload: [0, 1]\r\n }\r\n });\r\n }\r\n }", "function updateJQuery($) {\n if (!$ || ($ && $.bridget)) {\n return;\n }\n $.bridget = jQueryBridget;\n }", "function ourBookmarkletCode($)\n {\n // -----------------------------------------------------------------------------------------\n // Custom code goes from here ......\n\n var message = $('<div>').css({\n position: 'fixed',\n top: '2em',\n left: '2em',\n padding: '2em',\n 'background-color': '#ace',\n 'z-index': 100000\n }).text('We have jQuery here!');\n\n $('body').append(message);\n\n message.animate({'font-size': '200%'}, {duration: 1000});\n\n // ... to here.\n // -----------------------------------------------------------------------------------------\n }", "function JQSliderCreate() {\r\n $(this)\r\n .removeClass('ui-corner-all ui-widget-content')\r\n .wrap('<span class=\"ui-slider-wrap\"></span>')\r\n .find('.ui-slider-handle')\r\n .removeClass('ui-corner-all ui-state-default');\r\n }", "function achievementsBox(object)\n{\n\tif (typeof object != \"object\") return;\n\tif (typeof object.achievementsList != \"object\" || object.achievementsList.length<1) return;\n\n\t// Remove previous achievements box, if exists, and create a new one\n\t$(\"#achievements_box\").remove();\n\t$(\"#no_achievements\").parent().append('<div id=\"achievements_box\"><div class=\"container\"><h3>Achievements</h3><ul></ul></div></div>');\n\tfor (var i=0;i<object.achievementsList.length;i++) {\n\t\tvar date_txt = '';\n\t\tvar date_year = object.achievementsList[i].year;\n\t\tvar date_month = object.achievementsList[i].month;\n\t\tvar date_day = object.achievementsList[i].day;\n\t\tif(object.achievementsList[i].month>0 && object.achievementsList[i].day>0) date_txt = '<span>'+date_year+'-'+date_month+'-'+date_day+'</span>';\n\t\t$(\"#achievements_box ul\").append('<li><img src=\"style/img/badge.png\" title=\"'+object.achievementsList[i].ruleKey+'\">'+object.achievementsList[i].text+date_txt+'</li>');\n\t}\n\t$(\"#achievements_box\").append('<div class=\"arrow-down\"></div');\n\t$(\"#achievements_box\").hide();\n\n\t// Add click functionality to the achievements number, so\n\t// the achievements box can be displayed\n\t$(\"#no_achievements\").bind('click', function(e){\n\t\t\t\t\t\t\t\t\t\t\t\t$('#achievements_box').show();\n\t\t\t\t\t\t\t\t\t\t\t\t$(\"#no_achievements\").addClass(\"active\");\n\t\t\t\t\t\t\t\t\t\t\t\te.stopPropagation();\n\t});\n\t$(\"#no_achievements\").css({cursor:\"pointer\"});\n\n\t// If a remove bind has not been set,\n\t// then add one to hide achievements box\n\tif (!remove_bind_achievements_box){\n\t\t$(\"html\").click(function () { \n\t\t\t\t\t\t\t\t$(\"#achievements_box\").hide();\n\t\t\t\t\t\t\t\t$(\"#no_achievements\").removeClass(\"active\");\n\t\t});\n\t\tvar remove_bind_achievements_box = true;\n\t}\n}", "function updateJQuery($) {\n if (!$ || ($ && $.bridget)) {\n return;\n }\n $.bridget = jQueryBridget;\n }", "function JQSliderCreate()\n\t{\n\t\t$(this)\n\t\t\t.removeClass('ui-corner-all ui-widget-content')\n\t\t\t.wrap('<span class=\"ui-slider-wrap\"></span>')\n\t\t\t.find('.ui-slider-handle')\n\t\t\t.removeClass('ui-corner-all ui-state-default');\n\t}", "function widgetInit(widget, data){\n widget.className = 'github-badge';\n data.orientation = widget.getAttribute('orientation') || 'vertical';\n if(data.orientation) widget.className += ' '+data.orientation;\n data.badge = widget.getAttribute('badge') || 'octo';\n widget.className += ' '+data.badge;\n data.username = widget.getAttribute('user');\n }", "function initShowBizContainer() {\n\t\t\tjQuery(document).ready(function() {\n\n\t\t\t\t\tjQuery('.showbiz-container').showbizpro({\n\t\t\t\t\t\t\tcontainerOffsetRight:0,\n\t\t\t\t\t\t\theightOffsetBottom:3\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t}", "function createNoty(message, type) {\n var html = '<div class=\"alert alert-' + type + ' alert-dismissable page-alert\">';\n html += '<button type=\"button\" class=\"close\"><span aria-hidden=\"true\">×</span><span class=\"sr-only\">Close</span></button>';\n html += message;\n html += '</div>';\n $(html).hide().prependTo('#noty-holder').slideDown();\n}", "createParentElement() {\n const div = document.createElement('div');\n div.classList.add('h5p-digibook-cover');\n return div;\n }", "getBadgeClasses() {\n let classes = \"badge m-2 badge-\";\n classes += this.props.counter.value === 0 ? \"warning\" : \"light\";\n return classes;\n }", "function showLoadingImage(container) {\n container.empty().append('<div class=\"barspinner dark\"><div class=\"rect1\"></div><div class=\"rect2\"></div><div class=\"rect3\"></div><div class=\"rect4\"></div><div class=\"rect5\"></div></div>');\n}", "function buildProgressBar() {\n jQueryprogressBar = jQuery( \"<div>\", {\n id: \"progressBar\"\n } );\n jQuerybar = jQuery( \"<div>\", {\n id: \"bar\"\n } );\n jQueryprogressBar.append( jQuerybar )\n .prependTo( jQueryelem );\n }", "function badgeImg(link, name) { return ' '; }", "function renderEmpty() {\n var alertDiv = $(\"<div>\");\n alertDiv.addClass(\"alert alert-danger\");\n alertDiv.text(\"Sorry - Nothing to reServe today!\");\n groceryContainer.append(alertDiv);\n }", "function accendiSeNotifica()\n{\n\t$('#sos').attr('class', 'badge badge-important');\n\t$('#sos').html('!');\n}", "function displayLoadingProgressInPopup(message){\r\n var $container = $(\".preload-progress\");\r\n \r\n if($container.length){\r\n $container.text(message.percentComplete+\"%\");\r\n }//if\r\n}", "_initEmptyLegend(){\n // Create panel for the legend\n $(this.legendContainer).append(\n $('<div>', {\n 'id':'legend-panel',\n 'class':'panel panel-primary',\n // 'html':'<span>For HTML</span>',\n })\n );\n\n // Add body and legend\n $(\"#legend-panel\").append(\n $('<div>', {\n 'class': 'panel-heading text-center',\n 'html': 'Legend'\n }),\n $('<form>', {\n 'id': 'legend-form',\n 'class': 'panel-body'\n })\n );\n\n }", "onAdd() {\n this.createPopupHtml();\n this.getPanes().floatPane.appendChild(this.containerDiv);\n }", "function load_banner () {\n if (url == \"https://scratch.mit.edu/\" && GM_getValue(\"pos\", \"top\") != \"none\") {//on main page\n console.log(\"loading banner\");\n let box = element(\"div\").a(\"class\", \"box\")\n .append(element(\"div\").a(\"class\", \"box-header\")\n .append(element(\"h4\").t(\"Resurgence Userscript Info\"))\n .append(element(\"h5\"))\n .append(element(\"p\")\n .append(element(\"a\").a(\"href\", \"https://github.com/Wetbikeboy2500/Resurgence\").t(\"Resurgence Github\"))\n )\n )\n .append(element(\"div\").a(\"class\", \"box-content\")\n .append(element(\"p\").t(\"Current Version: \" + currentVersion).a(\"style\", \"margin: 0;\"))\n .append(element(\"p\").a(\"style\", \"margin: 0;\").t(\"Recent Version:\").a(\"id\", \"recent_version\"))\n .append(element(\"div\").a(\"id\", \"changelog\").a(\"style\", \"position: relative; left: 60%; top: -54px; width: 40%; height: 54px; margin-bottom: -54px; border: 1px solid #D9D9D9; border-radius: 25px; background-color: white; overflow: hidden;\")\n .append(element(\"div\").a(\"style\", \"width: 100%; height: 100%; overflow-y: scroll; position: absolute; top: 0px; left: 0px;\")\n .append(element(\"button\").a(\"style\", \"display: inline-block; height: 54px; line-height: 15px; background-color: #F2F2F2; border: 1px solid #D9D9D9; border-radius: 25px; margin: auto; padding: 10px;\").t(\"Expand change log\").a(\"data-expanded\", \"false\")\n .e(\"click\", (e) => {\n let target = document.getElementById(\"changelog\");\n if (e.currentTarget.getAttribute(\"data-expanded\") == \"false\") {\n e.currentTarget.parentElement.style.height = \"\";\n e.currentTarget.parentElement.style[\"overflow-y\"] = \"\";\n const height = e.currentTarget.parentElement.getBoundingClientRect().height;\n target.style.height = height + \"px\";\n target.style[\"margin-bottom\"] = (-1 * height) + \"px\";\n e.currentTarget.setAttribute(\"data-expanded\", \"true\");\n e.currentTarget.innerHTML = \"Collapse change log\";\n } else {\n e.currentTarget.parentElement.style.height = \"100%\";\n e.currentTarget.parentElement.style[\"overflow-y\"] = \"scroll\";\n target.style.height = 54 + \"px\";\n target.style[\"margin-bottom\"] = -54 + \"px\";\n e.currentTarget.setAttribute(\"data-expanded\", \"false\");\n e.currentTarget.innerHTML = \"Expand change log\"\n }\n })\n )\n .append(element(\"ul\").a(\"style\", \"padding-right: 5px;\")\n .append(element(\"h5\").t(\"Changes in \" + currentVersion).a(\"style\", \"margin: 0px; display: inline-block\"))\n .append(element(\"li\").t(\"Countdowns to multiple holidays\"))\n .append(element(\"li\").t(\"There is now a change log you can view (if I decide to update this)\"))\n .append(element(\"li\").t(\"Recent version now displays correctly\"))\n .append(element(\"li\").t(\"Updated code to use fetch instead of xhttprequests with promises\"))\n .append(element(\"li\").t(\"Changed run order for better loading\"))\n .append(element(\"li\").t(\"Numerous changes to the code be less buggy\"))\n .append(element(\"li\").t(\"Improved feel of changelog\"))\n )\n )\n )\n );\n if (GM_getValue(\"pos\", \"top\") == \"top\") {\n document.getElementsByClassName(\"mod-splash\")[0].insertBefore(box.dom, document.getElementsByClassName(\"mod-splash\")[0].children[0]);\n } else {\n box.apthis(document.getElementsByClassName(\"mod-splash\")[0]);\n }\n\n //gets the current version of the code from the github page\n fetch(\"https://raw.githubusercontent.com/Wetbikeboy2500/Resurgence/master/ScratchFixer.user.js\")\n .then((response) => { return response.text() })\n .then((text) => {\n const version = text.substring(text.indexOf(\"@version\") + 9, text.indexOf(\"// @description\") - 1);\n let tmpVersion = Number(version);\n if (tmpVersion != currentVersion) {\n if (tmpVersion < GM_info.script.version) {\n document.getElementById(\"recent_version\").innerHTML = \"Recent Version: \" + version + \" \";\n element(\"a\").a(\"href\", \"https://raw.githubusercontent.com/Wetbikeboy2500/Resurgence/master/ScratchFixer.user.js\").t(\"Downgrade (Your version is too revolutionary)\").apthis(document.getElementById(\"recent_version\"));\n } else {\n document.getElementById(\"recent_version\").innerHTML = \"Recent Version: \" + version + \" \";\n element(\"a\").a(\"href\", \"https://raw.githubusercontent.com/Wetbikeboy2500/Resurgence/master/ScratchFixer.user.js\").t(\"Update\").apthis(document.getElementById(\"recent_version\"));\n }\n } else {\n document.getElementById(\"recent_version\").innerHTML = \"Recent Version: \" + version;\n }\n })\n .catch((e) => {\n console.warn(\"An error occured while getting the version\", e);\n });\n }\n }", "function renderContainer() {\n var node = document.getElementById(\"blq-content\");\n\t\tnode = node.getElementsByClassName(\"g-group\")[1];\n\t\tnode = node.getElementsByClassName(\"g-w8\")[0];\n\t\t\n\t\tvar div = document.createElement(\"div\");\n\t\tdiv.setAttribute(\"id\", \"gm-semantic-tags\");\n\t\tdiv.setAttribute(\"class\", \"g-container\");\n\t\tdiv.setAttribute(\"style\", \"border-top:5px solid #E0E0E0; margin-bottom:1.38em; padding-top:0.46em;\");\n\n\t\tvar title = document.createElement(\"h2\");\n\t\ttitle.appendChild(document.createTextNode(\"Tags\"));\n\t\ttitle.setAttribute(\"style\", \"margin-bottom:10px; text-transform:uppercase;\");\n\t\t\n\t\tvar content = document.createElement(\"div\");\n\t\tcontent.setAttribute(\"id\", \"gm-semantic-tags-content\");\n\t\tcontent.setAttribute(\"style\", \"min-height:40px; background:url(http://dbpedia-i18n.appspot.com/images/progress.gif) 30% 30% no-repeat\");\n\t\t\n\t\tvar disclaimer = document.createElement(\"p\");\n\t\tdisclaimer.setAttribute(\"class\", \"disclaimer\");\n\t\tdisclaimer.innerHTML = \"Powered by <a href=\\\"http://www.google.com\\\">Google</a> and <a href=\\\"http://www.zemanta.com\\\">Zemanta</a>\";\n\t\n\t\tdiv.appendChild(title);\n\t\tdiv.appendChild(content);\n\t\tdiv.appendChild(disclaimer);\n\t\t\n\t\tnode.insertBefore(div, node.firstChild); \t\n\t}", "function createBasketWeightGuide(){\n // create the element for the guide\n $('.af__basket__weight-guide--label').after('<div class=\"js-af__weight-guide__wrapper\"></div>');\n $('.js-af__weight-guide__wrapper').append('<div class=\"js-af__weight-guide__meter\"></div>');\n \n $('.af__product__add-to-basket').submit(function(e){\n e.preventDefault();\n //var $multiplier=\n weightGuideListener();\n })\n}", "function runNotification(alert) {\r\n var unique_id = $.gritter.add({\r\n // (string | mandatory) the heading of the notification\r\n title: 'Notification!',\r\n // (string | mandatory) the text inside the notification\r\n text: alert,\r\n // (bool | optional) if you want it to fade out on its own or just sit there\r\n sticky: false,\r\n // (int | optional) the time you want it to be alive for before fading out\r\n time: 4000,\r\n // (string | optional) the class name you want to apply to that specific message\r\n class_name: 'my-sticky-class'\r\n });\r\n // You can have it return a unique id, this can be used to manually remove it later using\r\n /*\r\n setTimeout(function(){\r\n $.gritter.remove(unique_id, {\r\n fade: true,\r\n speed: 'slow'\r\n });\r\n }, 6000)\r\n */\r\n\r\n return false;\r\n\r\n\r\n\r\n}", "function pushNotification(text,css_class=\"\") {\n $(\"<div class='notification \"+css_class+\"'>\"+text+\"</div>\")\n .appendTo('.push-notifications-container')\n .delay(4000)\n .queue(function() {\n $(this).remove();\n });\n // Scroll to bottom of notifications box\n $('.push-notifications-container').scrollTop($('.push-notifications-container')[0].scrollHeight);\n}", "function initVariables($container){\n $body = $('body');\n\n $body.on('click', '#addPolicyLink', function(){\n if($(\"#policiesContainer\").hasClass('d-none')){\n utilityModule.hideMessage();\n \n $(\"#policiesContainer\").removeClass('d-none').addClass('d-block');\n $(\"#policyLinkLabel\").html(\"Hide policies\");\n $(\"#addPolicyLink\").find(\"span\").removeClass('fa-plus');\n $(\"#addPolicyLink\").find(\"span\").addClass('fa-times');\n } else {\n $(\"#policiesContainer\").removeClass('d-block').addClass('d-none');\n $(\"#policyLinkLabel\").html(\"Add policies\");\n $(\"#addPolicyLink\").find(\"span\").removeClass('fa-times');\n $(\"#addPolicyLink\").find(\"span\").addClass('fa-plus');\n }\n \n });\n\n\n }", "function addWeixinTip(){\n $('.container').append(\"<div class='weixin-tip'></div>\");\n var $weixin_tip = $('.weixin-tip')\n .append('<div class=\"absolute tip-arrow\"></div>')\n .append('<div class=\"mt100\"><p>请点击右上角</p><p>【分享到朋友圈】</p><p>或</p><p>【发送给朋友】</p></div>')\n .append('<div class=\"logo\"><a href=\"http://thepaper.cn\"><img src=\"assets/paper-logo.svg\"/></a></div>')\n .click(function(){\n $(this).fadeOut('fast',function(){$(this).remove();});\n });\n}", "function make_divs_undergrad_minors(tag_undergrad_minors_row,ugminors,div_bg,div_icon){\n //making div for a minor\n\n $div_to_append = $(\"<div class='tag_undergrad_minors_for_minor' style='background:\"+div_bg+\"'><i\" +\n \" class='\"+div_icon+\" fa-4x' style='color:white; margin-top: 30px'></i></div>\");\n\n $div_to_append.append(\"<p class='tag_undergrad_minors_for_minor_title'>\"+ugminors.title+\"</p>\");\n\n $div_to_append.on(\"click\",function () {\n create_modal_minors(this,ugminors);\n });\n // div box\n tag_undergrad_minors_row.append($div_to_append);\n\n }", "function addNotification() {\n var unread = document.getElementById(\"unread\");\n var newUnread = unread.cloneNode(true);\n var bell = document.getElementById(\"bell\");\n var newBell = bell.cloneNode(true);\n var notification_container = document.getElementById(\"notification_container\");\n newUnread.innerHTML = parseInt(unread.innerHTML);\n unread.parentNode.replaceChild(newUnread, unread);\n bell.parentNode.replaceChild(newBell, bell);\n notification_container.classList.remove(\"seen\");\n notification_container.style.backgroundColor = 'rgba(235, 154, 45, 1)';\n }", "function dropdownTotalAmounts()\n{\n\t// $('div.notification-container').slideDown();\n\n\tvar dropdownCounts = $('#dropdown_id');\n\tvar dropdownIcon = $('#dropdown_icon');\n \n if(dropdownCounts.hasClass('dropdown_closed'))\n {\n dropdownCounts.removeClass('dropdown_closed');\n dropdownCounts.addClass('dropdown_open');\n\n dropdownIcon.removeClass('fa-chevron-down');\n dropdownIcon.addClass('fa-chevron-up');\n\n\n $('div.notification-container').slideDown();\n\n }\n else if(dropdownCounts.hasClass('dropdown_open'))\n {\n \tdropdownCounts.removeClass('dropdown_open');\n dropdownCounts.addClass('dropdown_closed');\n\n dropdownIcon.removeClass('fa-chevron-up');\n dropdownIcon.addClass('fa-chevron-down');\n\n $('div.notification-container').slideUp();\n }\n}", "function renderLicenseBadge(data) {\n\n}", "function showNoticeStatic(content, className, autoClose) {\n className = className || \"noticeBarGreen\";\n autoClose = autoClose || false;\n var container = $('<div id=\"noticeBarContainer\"></div>').addClass(\"noticeBarContainer\").addClass(\"smaller\");\n container.html('<span id=\"noticeBarValue\" class=\"noticeBar ' + className + '\">' + content + '</span');\n $('body').append(container);\n // scroll down notice\n if (!autoClose) {\n $('#noticeBarContainer').animate({ top: '0' }, 400);\n } else {\n $('#noticeBarContainer').animate({ top: '0' }, 400,\n function() {\n // scroll up notice after down animation is complete\n $('#noticeBarContainer').animate({ top: '-50px' }, 1000,\n function() {\n // remove notice container\n $('#noticeBarContainer').remove();\n submitProgress = false;\n }\n );\n }\n ).delay(3000);\n }\n}", "function requireContainer() {\n if (!container) {\n container = document.createElement(\"div\");\n container.setAttribute(\"id\", groupId);\n container.setAttribute(\"data-group\", groupName);\n container.style.setProperty(\"pointer-events\", \"none\");\n document.body.append(container);\n }\n return container;\n }", "function init(){\n var temp = document.createElement(\"div\"),\n body = $(\"body\"),\n /* itemsToAdd array contains the list of elements to be inserted\n field - The key under which a reference to DOM element will be stored in internal handles object\n id - Actual id of the element\n cssClass - The CSS style class which will be applied\n container - The generated item will be appended to what is specified as the container */\n itemsToAdd = [\n { field: \"mask\", id: \"msgMask\", cssClass: \"toasty_msgMask\", container: body },\n { field: \"measurebox\", id: \"msgMeasureBox\", cssClass: \"toasty_msgMeasureBox\", container: body },\n { field: \"container_br\", id: \"container_br\", cssClass: \"toasty_msgContainer br\", container: body },\n { field: \"container_bl\", id: \"container_bl\", cssClass: \"toasty_msgContainer bl\", container: body },\n { field: \"container_tr\", id: \"container_tr\", cssClass: \"toasty_msgContainer tr\", container: body },\n { field: \"container_tl\", id: \"container_tl\", cssClass: \"toasty_msgContainer tl\", container: body },\n { field: \"tc_holder\", id: \"tc_holder\", cssClass: \"toasty_msgContainer tc\", container: body },\n { field: \"container_tc\", id: \"container_tc\", cssClass: \"toasty_subContainer\", container: \"#tc_holder\" },\n { field: \"bc_holder\", id: \"bc_holder\", cssClass: \"toasty_msgContainer bc\", container: body },\n { field: \"container_bc\", id: \"container_bc\", cssClass: \"toasty_subContainer\", container: \"#bc_holder\" }\n ],\n i,\n maxI,\n item,\n domSearch;\n\n for(i = 0, maxI = itemsToAdd.length; i < maxI; i++) {\n item = itemsToAdd[i];\n domSearch = $(\"#\"+item.id);\n if (domSearch.length > 0) {\n handles[item.field] = domSearch;\n } else {\n handles[item.field] = $(\"<div id='\" + item.id + \"' class='\" + item.cssClass + \"'></div>\").appendTo(item.container);\n }\n }\n\n initialized = true;\n }", "drawBadges (){\n /**\n * container in the left hand side\n * @type {T | string}\n */\n select (\"slot_not_available\").innerHTML = this.slotsArray.reduce((acc, [slotTime, flag], i)=>acc +\n `<button class=\"btn btn-primary\" ${flag?\"disabled\":\"\"} onclick=\"makeAvailable(${i})\">${slotTime}</button>`\n , \"\");\n\n /**\n * container in the right hand side\n * @type {T | string}\n */\n select(\"slot_available\").innerHTML = this.slotsArray.reduce((acc, [slotTime, flag], i)=>acc +\n `<button class=\"btn btn-success ${!flag?\"invisible\":\"\"}\" ${!flag?\"disabled\":\"\"} onclick=\"makeAvailable(${i})\">${slotTime}</button>`, \"\");\n switchButtonDisplay();\n }", "function createContainers() {\n\t\t\t\t//console.log('Creating containers...');\n\t\t\t\t// Define html to be prepended to the body\n\t\t\t\tvar qfInner = \"<div id=\\\"qfCloseContainer\\\">&times;</div>\\n<div id=\\\"qfSheetContent\\\"></div>\";\n\t var qfSheetContainer = \"<div id=\\\"qfSheetContainer\\\">\" + qfInner + \"</div>\";\n\t\t\t\tvar qfDimmer = \"<div id=\\\"qfDimmer\\\"></div>\";\n\t\t\t\tvar qfSpinner = \"<div id=\\\"qfSpinner\\\"></div>\";\n\t\t\t\n\t\t\t\t// Prepend the containers and remove the body scrollbars\n $('body').css('overflow','hidden').prepend(qfSheetContainer, qfDimmer, qfSpinner);\n\t\t\n\t\t\t\t// Hide the containers immediately\n\t\t\t\t$('#qfDimmer').hide().fadeIn(250);\n\t\t\t\t$('#qfSheetContainer, #qfSpinner').hide();\n\t\t\t}", "function pollGetTotalVotes(e, optionid) {\n\n e.preventDefault();\n\n var $el = ga(e.target);\n var pollId = $el.attr('id').split('pollmiv|')[1];\n\n var poll_participants = '';\n var poll_u_markup_schel = '<div id=\"modal_cnt\" class=\"modal_cnt\">\\\n\t\t\t\t\t<div data-block=\"ShowLikers\" class=\"loader-container\">\\\n\t\t\t\t\t<ul class=\"cardsList jbpop\"></ul></div></div>';\n\n var p_u_markup = '<li class=\"cardsList_li show-on-hover\">\\\n <div class=\"userCard\">\\\n <div class=\"card_main\">\\\n <div class=\"card_wrp\">\\\n <div class=\"photoWrapper\">\\\n <a class=\"photoWrapper\" href=\"/user/%uid\" hrefattr=\"true\"><img src=\"/getPhoto?p=%pid&sz=thumb&g=%gender\" alt=\"%uname\" width=\"128\" height=\"128\">%online</a>\\\n </div>\\\n </div>\\\n </div>\\\n <div class=\"card_add\">\\\n <div class=\"ellip\"><a href=\"/user/%uid\" class=\"o\" hrefattr=\"true\">%uname</a></div>\\\n </div>\\\n </div>\\\n </li>';\n\n\n var jb_ = new jBox('Modal', {\n id: 'forpoll' + pollId,\n title: lang.poll_participants,\n fade: false,\n closeButton: 'box',\n 'fixed': true,\n height: 'auto',\n width: '818px',\n minHeight: '100px',\n position: {\n x: 'center', // Horizontal Position (Use a number, 'left', 'right' or 'center')\n y: 'top' // Vertical Position (Use a number, 'top', 'bottom' or 'center')\n },\n offset: {\n x: 0,\n y: 30\n },\n onClose: function() {\n ga('#forpoll' + pollId).remove();\n\n }\n });\n jb_.open()\n .ajax({\n type: 'POST',\n url: '/cmd.php',\n data: {\n cmd: 'pollParticipants',\n sondageid: pollId,\n optionid: optionid ? optionid : 0,\n view_as: 'json'\n },\n\n reload: true,\n setContent: false,\n success: function(data) {\n var d = validateJson(data);\n\n if(d.succ == 1) {\n\n ga('#forpoll' + pollId).find('.jBox-content').html(poll_u_markup_schel);\n\n for(var i = 0; i < d.data.length; i++) {\n var b = d.data[i];\n poll_participants += p_u_markup.replace(/%uid/g, b.uid).replace(/%pid/g, b.uphoto).replace(/%uname/g, b.uname).replace('%gender', b.ugender).replace('%online', b.online ? '<span class=\"ic-online\"></span>' : '');\n\n }\n\n\n ga('#forpoll' + pollId).find('ul.cardsList').html(poll_participants);\n } else {\n\n displayErr(d.err);\n\n }\n\n }\n });\n}", "function addRefereshListener (refreshSelector, timeout = 1000) {\n return () => {\n const showAll = document.body.querySelector(refreshSelector)\n if (showAll) {\n showAll.addEventListener('click', () => {\n removeElementsByClass('scite-badge')\n setTimeout(() => insertBadges(), timeout)\n })\n }\n }\n}", "getBadgeClasses() {\n let classes = \"badge m-2 badge-\";\n // Appends either warning or primary to the end of classes depending on its value === 0 or not\n classes += this.props.counter.value === 0 ? \"primary\" : \"default\";\n return classes;\n }", "function look_ruby_tfooter_widget_instagram_popup() {\r\n if ('undefined' != typeof (look_ruby_tfooter_instagram_popup) && 1 == look_ruby_tfooter_instagram_popup) {\r\n $('.instagram-content-wrap .footer-instagram-el a').magnificPopup({\r\n type: 'image',\r\n removalDelay: 200,\r\n mainClass: 'mfp-fade',\r\n closeOnContentClick: true,\r\n closeBtnInside: true,\r\n gallery: {\r\n enabled: true,\r\n navigateByImgClick: true,\r\n preload: [0, 1]\r\n }\r\n });\r\n }\r\n }", "containerTemplate() {\n\n return this.createDomElement(\n \"div\",\n {\n \"class\": [\n \"scrolling-js-container\"\n ],\n \"style\": {\n height: this.INIT_PAGES.length * 100 + \"%\",\n }\n }\n );\n }", "getBadgeClasses() {\n //if count is 0 display in yellow else display in blue\n let classes = \"badge m-2 badge-\";\n classes += this.props.counter.value === 0 ? \"warning\" : \"primary\";\n return classes;\n }", "function addNotificationToHTML(result,bool) {\n\n if (result.length>0) {\n var totalUnseen=result[0];\n result=result[1];\n }\n\n if (bool) {\n //ul for notification container\n var ul=document.createElement(\"ul\");\n ul.setAttribute(\"class\",\"collection\");\n }\n else {\n //ul for dropdown notification icon\n var ul=document.getElementById(\"notification\");\n }\n\n if (result.length==0){\n $('#countOfNotification').html('Notification');\n var li=document.createElement(\"li\");\n var a=document.createElement(\"a\");\n var text=document.createTextNode(\"No notification\");\n a.setAttribute(\"href\",\"#!\");\n a.appendChild(text);\n li.appendChild(a);\n ul.appendChild(li);\n }\n else {\n if (totalUnseen!=0) {\n $('.notification-badge').css(\"background-color\",\"#ff0000\");\n $('.notification-badge').html(totalUnseen);\n }\n else {\n $('.notification-badge').css(\"background-color\",\"transparent\");\n $('.notification-badge').empty();\n }\n $('#linkNotification').attr(\"href\",\"javascript:showNotification();\");\n $('#countOfNotification').html('Notification <span style=\"color:red;\">('+totalUnseen+')</span>');\n\n for (var i=0;i<result.length;i++) {\n var li_divider=document.createElement(\"li\");\n li_divider.setAttribute(\"class\",\"divider\");\n li_divider.setAttribute(\"tabindex\",\"-1\");\n var li=document.createElement(\"li\");\n var text=document.createTextNode(result[i][2]);\n var date=document.createTextNode(result[i][1]);\n var a=document.createElement(\"a\");\n a.setAttribute(\"href\",\"javascript:void(0);\");\n a.setAttribute(\"onclick\",\"javascript:openNotification(event,'\"+result[i][3]+\"')\");\n a.setAttribute(\"id\",result[i][0]);\n\n if (result[i][4]==1) {\n li.style.backgroundColor=\"#f3f4f7\";\n }\n\n if (bool) {\n li.setAttribute(\"class\",\"collection-item avatar\");\n var span=document.createElement('span');\n var t=document.createTextNode(\"New notification\");\n var p=document.createElement('p');\n p.appendChild(text);\n p.appendChild(document.createElement('br'));\n p.appendChild(date);\n span.appendChild(t);\n li.appendChild(span);\n li.appendChild(p);\n a.appendChild(li);\n ul.appendChild(a);\n }\n else {\n a.appendChild(text);\n a.appendChild(document.createElement('br'));\n a.appendChild(date);\n li.appendChild(a);\n ul.appendChild(li);\n ul.appendChild(li_divider);\n }\n }\n if (bool) {\n var div=document.getElementById('notificationContainer');\n div.appendChild(ul);\n }\n else {\n var liEnd=document.createElement(\"li\");\n var aEnd=document.createElement(\"a\");\n var textEnd=document.createTextNode(\"See all\");\n aEnd.appendChild(textEnd);\n aEnd.setAttribute(\"id\",\"seeMoreNotif\");\n aEnd.setAttribute(\"href\",\"javascript:showNotification();\");\n liEnd.appendChild(aEnd);\n ul.appendChild(liEnd);\n }\n }\n}", "function updateNotificationBadge(numNotifications) {\n $(\".dropdown .notification-badge\").html(numNotifications);\n }", "function setBadgeCount(icon, count) {\n // Get the app\n let app = icon.parentElement;\n // Get the badge\n let badge = app.getElementsByClassName('badge')[0];\n // Set the badge to the count\n badge.innerHTML = count;\n // If the count is zero, hide the badge with opacity,\n // otherwise make it visible\n if (count === 0) {\n badge.style.opacity = '0';\n }\n else {\n console.log('here');\n badge.style.opacity = '1';\n }\n}", "function DiscountBadge({ listPrice, sellingPrice, label = '', children }) {\n const percent = calculateDiscountTax(listPrice, sellingPrice)\n const shouldShowPercentage = percent && percent >= 0.01\n\n return (\n <div className={`${styles.discountContainer} relative dib`}>\n {shouldShowPercentage ? (\n <div\n className={`${styles.discountInsideContainer} t-mini white absolute right-0 pv2 ph3 bg-emphasis z-1`}\n >\n <IOMessage id={label}>\n {labelValue => (\n <>\n {!labelValue && '-'}\n <FormattedNumber value={percent} style=\"percent\" />{' '}\n {labelValue && ' '}\n {labelValue && <span>{labelValue}</span>}\n </>\n )}\n </IOMessage>\n </div>\n ) : null}\n {children}\n </div>\n )\n}", "function citruscartGrayOutAjaxDiv(container, text, suffix) {\r\n\t\r\n\tif (!suffix || suffix == '')\r\n\t\tsuffix = '_transp';\r\n\r\n\tvar img_loader = '<img src=\"' + window.com_citruscart.jbase + 'media/citruscart/images/ajax-loader' + suffix + '.gif' + '\"/>';\r\n\t//document.getElementById(container).setStyle('position', 'relative');\r\n\ttext_element = '';\r\n\tif (text && text.length)\r\n\t\ttext_element = '<div class=\"text\">' + text + '</div>';\r\n\r\n\t// make all texts in the countainer gray\r\n\tcitruscartSetColorInContainer(container, '');\r\n\t\r\n\t//document.getElementById(container).innerHTML += '<div class=\"citruscartAjaxGrayDiv\">' + img_loader + text_element + '</div>';\r\n\t\r\n\t\r\n}", "function robotResponse4() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Thanks for sharing this article.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function robotResponse6() {\r\n $('.commentsection').append('<div class=\"cloud\"><div class=\"container\"><div class=\"row\"><div class=\"col-lg-4\"><img src=\"img/gabby_avatar.jpg\"></div><div class=\"col-lg-8\"><p class=\"sentText\"> Hi Alison.' + '</p><br><p style=\"color:gray;text-align:left;\">Posted by: Gabby Mendoza on ' + newdate + '</p></div></div></div><hr>');\r\n }", "function _get_containers() {\n $.ajax({\n url: '/samples/ajax/cnt/visit/' + visit,\n type: 'GET',\n dataType: 'json',\n timeout: 5000,\n success: function(json){\n \n var drag = { \n containment: '#drag_container',\n stack: '#unassigned div',\n /*cursor: 'move',*/\n /*cancel: 'a',*/\n revert: true\n }\n \n $.each(json, function(i,c) {\n var a = c['SAMPLECHANGERLOCATION']\n //var b = c['BEAMLINELOCATION']\n var assigned = c['SAMPLECHANGERLOCATION'] && (c['BEAMLINELOCATION'] == bl) && (c['DEWARSTATUS'] == 'processing')\n \n if (!(c['CONTAINERID'] in containers)) {\n sc = $('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')\n \n if (!assigned || (assigned && !$('#blp'+a).children('div').children('div[cid='+c['CONTAINERID']+']').length)) {\n \n $('<div cid=\"'+c['CONTAINERID']+'\" sid='+c['SHIPPINGID']+' did=\"'+c['DEWARID']+'\" loc=\"'+c['SAMPLECHANGERLOCATION']+'\" class=\"container\"><span class=\"r\"><a title=\"Click to view container contents\" href=\"/shipment/cid/'+c['CONTAINERID']+'\">View Container</a></span><h1>'+c['CODE']+'</h1></div>').appendTo(assigned ? ($('#blp'+a).children('div')) : sc).addClass(assigned ? 'assigned' : '').draggable(drag)\n containers[c['CONTAINERID']] = a\n }\n \n \n } else {\n d = $('div[cid='+c['CONTAINERID']+']')\n var state = c['SAMPLECHANGERLOCATION'] == d.attr('loc') && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing'\n if (!state) {\n if (c['SAMPLECHANGERLOCATION'] && c['BEAMLINELOCATION'] == bl && c['DEWARSTATUS'] == 'processing') {\n d.appendTo($('#blp'+a).children('div')).addClass('assigned')\n } else d.appendTo($('div[sid='+c['SHIPPINGID']+']').children('div[did='+c['DEWARID']+']').children('div.containers')).removeClass('assigned')\n }\n \n }\n })\n \n map_callbacks()\n }\n })\n }", "function checkImageCount() {\n var newImageCount = document.querySelectorAll(\"#issue_images > *\").length;\n if (newImageCount < $maxImages) {\n $('#image_input').closest('.badge').removeClass('u-hidden');\n } else {\n $('#image_input').closest('.badge').addClass('u-hidden');\n }\n}", "function initHtml () {\n\t\t\t$container.addClass(\"ibm-widget-processed\");\n\n\t\t\tif (config.type === \"simple\") {\n\t\t\t\t$hideables.addClass(\"ibm-hide\");\n\t\t\t}\n\n\t\t\tif (config.type === \"panel\") {\n\t\t\t\t$headings.removeClass(\"ibm-active\");\n\t\t\t\t$containers.slideUp(slideupSpeed);\n\t\t\t}\n\t\t}", "function colorizePackageDelivery(e) {\n let packageCount = parseInt($(\"#default-package-delivery .value\").html());\n if (packageCount > 0) {\n $(\".widget-basedisplay-default-package-delivery\").css(\"background\", \"#d88014\");\n } else {\n $(\".widget-basedisplay-default-package-delivery\").css(\"background\", \"\");\n }\n }", "function ready() {\n jQuery( \".datepicker\" ).datepicker({ dateFormat: 'yy-mm-dd' });\n\n jQuery('.dd').nestable({ \n listNodeName: 'ul',\n maxDepth: 100,\n })\n .nestable('collapseAll')\n .on('change', updateOrder);\n\n jQuery('.dd-content .glyphicon-eye-open, .dd-content .glyphicon-plus-sign').click(function(){\n var element = jQuery(this).parents('.dd-content');\n\n jQuery('.dd-content').removeClass('active');\n element.addClass('active');\n });\n\n jQuery(\"#overlay\").css({\n opacity : 0.5,\n top : 0,\n bottom : 0,\n left : 0,\n right : 0,\n });\n\n var maxheight = 0;\n jQuery(\"div.thumbnail\").each(function(){\n if(jQuery(this).height() > maxheight) { maxheight = jQuery(this).height(); }\n });\n \n jQuery(\"div.thumbnail\").height(maxheight + 43);\n\n jQuery('.glyphicon').each(function() {\n var tooltip = '';\n if(jQuery(this).hasClass('glyphicon-eye-open')) {\n tooltip = 'Anzeigen';\n } \n else if(jQuery(this).hasClass('glyphicon-trash')) {\n tooltip = 'Löschen';\n }\n else if(jQuery(this).hasClass('glyphicon-pencil')) {\n tooltip = 'Bearbeiten';\n }\n else if(jQuery(this).hasClass('glyphicon-plus-sign')) {\n tooltip = 'Neu';\n }\n else if(jQuery(this).hasClass('glyphicon-time')) {\n tooltip = 'Aufwand';\n }\n else if(jQuery(this).hasClass('glyphicon-download-alt')) {\n tooltip = 'Download';\n }\n jQuery(this).data('toggle', 'tooltip').attr('title', tooltip);\n });\n\n jQuery('.glyphicon').tooltip();\n\n initProject();\n initPbs();\n initWbs();\n initRbs();\n initRam();\n initMilestone();\n initIteration();\n}", "function attachPopUpToReference(triggerElement) {\n\n if ($(triggerElement).attr(\"id\") == \"two-cents-status-item-container\") {\n\n $(\"#rate-options-pop-up\").insertAfter($(triggerElement));\n }\n else {\n\n var twoCentsStatusItemContainer = $(triggerElement).closest(\".rate-status-item-container\");\n $(\"#rate-options-pop-up\").insertAfter($(twoCentsStatusItemContainer));\n }\n\n}", "function fetch_notifications() {\r\n $.get('/home/get_notification_popup', function(data){\r\n if(data > 0)\r\n {\r\n $('#notifications').badger(data);\r\n }\r\n \r\n notification_timer = setTimeout(fetch_notifications, 45000);\r\n });\r\n}", "function addRangeSlider(containerDivID,title,variable,min,max,defaultValue,step,sliderID,mode,tooltip){\n $('#'+containerDivID).append(`<div class='dual-range-slider-container px-1' rel=\"txtTooltip\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"${tooltip}\">\n <div class='dual-range-slider-name py-2'>${title}</div>\n <div id=\"${sliderID}\" class='dual-range-slider-slider' href = '#'></div>\n <div id='${sliderID}-update' class='dual-range-slider-value p-2'></div>\n </div>`);\n setUpRangeSlider(variable,min,max,defaultValue,step,sliderID,mode);\n}", "function createBubble(data, category){\n var mybubble = $('<div/>');\n var mybubblewrapper = $('<div/>');\n var title = $('<h2>').text(category.toUpperCase());\n var content = $('<div>').addClass('content');\n for( var i = 0; i<3; i++){\n var space = $('<span>').text('----');\n content.append(space);\n var article = $('<span>').text(data.posts[i].title);\n content.append(article);\n content.append($('<br>'))\n };\n mybubble.attr('data-popularity', data.totalResults);\n mybubble.append(title);\n mybubble.append(content);\n mybubble.addClass('bubble x1');\n mybubble.attr(\"id\", category);\n mybubblewrapper.addClass(\"bubblewrapper col-md-2\");\n\n\n var fontsize = data.totalResults/50;\n if(fontsize<18){\n fontsize = 18\n }\n else if(fontsize>35){\n fontsize = 35;\n }\n var size = setBubbleSize(data.totalResults);\n mybubble.css({\n width: size,\n height: size,\n paddingTop: \"50px\",\n backgroundColor: \"pink\",\n fontSize:fontsize + 'px'\n\n });\n\n mybubble.find('.content').css({fontSize:fontsize + 'px'});\n mybubblewrapper.append(mybubble);\n\n $('#bubble-container').append(mybubblewrapper);\n\n  \n }", "function Badge(_ref) {\n var className = _ref.className,\n type = _ref.type,\n children = _ref.children,\n props = objectWithoutProperties(_ref, [\"className\", \"type\", \"children\"]);\n\n return React__default.createElement(\n \"span\",\n { className: classnames(\"badge\", defineProperty({}, \"badge-\" + type, type), className) },\n children\n );\n}", "function setupVictoryModal(campaign, state, campaign_deltas) {\n\n var html = getBadgesHtml(campaign, state, campaign_deltas)\n + getCampaignMenuHtml(campaign, state) \n\n $(\"#victoryModalBody\").html(html)\n}", "static tickUiUpdate() {\n // Fill badge data\n let updateParcel = {\n text: \"\",\n color: \"#d352ad\",\n tooltip: \"\"\n };\n\n this.setUpdateObjTexts(updateParcel);\n\n // Apply to UI\n if (this.networkOk) {\n this.applyBadgeConfig(updateParcel);\n }\n\n this.updatePopupUi(updateParcel);\n }", "function selectionRequired() {\n console.log('The selectionRequired function ran');\n //popup selection required gif\n $('body').append(`\n <div class=\"overlay\">\n <div class=\"popup\">\n <a class=\"close\" href=\"#\">&times;</a>\n <h2>Please, pick an answer.</h2>\n <div class=\"gif-container\">\n <img src=\"https://media.giphy.com/media/lH6mJIKkCwQo0/giphy.gif\" alt=\"Please make a selection GIF - Mrs. White is fed up\" class=\"popup-gif\">\n </div>\n </div>\n </div>`);\n $('.close').click(function () {\n $('.overlay').remove();\n })\n\n\n}", "function createPopBox() {\n var parent = jQuery('<div/>').addClass('popbox');\n var open = jQuery('<button/>').addClass('open').text('Click Here!');\n var collapse = jQuery('<div/>').addClass('collapse');\n collapse.html(\n '<div class=\"box\">' +\n ' <div class=\"arrow\"></div>' +\n ' <div class=\"arrow-border\"></div>' +\n ' <div class=\"popbox-content\">' +\n ' </div>' +\n ' <a href=\"#\" class=\"close\">close</a>' +\n '</div>');\n parent.append(open).append(collapse);\n\n var content = collapse.find('.popbox-content');\n content.text('Content Here :)');\n\n parent.data('onPopBox', function() {\n parent.find('.viewport').parent().width(content.width() + 20);\n });\n\n return {\n parent: parent,\n button: open,\n content: content\n };\n }", "function addNotification (title, author, authorAvatar, date, url) {\n const divBlocNotif = document.createElement('div')\n divBlocNotif.id = 'blocNotif'\n const divDate = document.createElement('div')\n divDate.id = 'date'\n divDate.innerText = date\n const divPseudo = document.createElement('div')\n divPseudo.id = 'pseudo'\n divPseudo.innerText = author\n const divTitle = document.createElement('div')\n divTitle.id = 'title'\n divTitle.innerText = title\n const imgAvatar = document.createElement('img')\n imgAvatar.src = authorAvatar\n const divNotif = document.createElement('div')\n divNotif.id = 'notification'\n const a = document.createElement('a')\n a.href = url\n a.target = '_blank' // Open the notification in a new window\n\n divBlocNotif.appendChild(divDate)\n divBlocNotif.appendChild(divPseudo)\n divBlocNotif.appendChild(divTitle)\n divNotif.appendChild(imgAvatar)\n divNotif.appendChild(divBlocNotif)\n a.appendChild(divNotif)\n contentDiv.appendChild(a)\n}", "function CreateBadgeReqLinks() {\r\n //Find the div that holds the badge requirements, there might be 2\r\n var divs = document.getElementsByClassName(\"badge_description\");\r\n console.log(\"div num: \" + divs.length);\r\n \r\n for (var dl=0; dl<divs.length; dl++) {\r\n //Get each <li> list item from the <ul> unordered list inside the div\r\n var li = divs[dl].getElementsByTagName(\"li\");\r\n console.log(\"li num: \" + li.length);\r\n for (var num=0; num<li.length; num++) {\r\n //For each <li> list item, replace the innerHTML with the search code\r\n li[num].innerHTML = \"<a href='http://search2.bestbuylearninglounge.com/?q=\" + li[num].innerHTML + \";q1=eLearning;x=0;x1=type;y=0' style='color:blue;' target='_blank'>\" + li[num].innerHTML + \"</a>\";\r\n console.log(\"replaced html with link\");\r\n }\r\n }\r\n }", "function letsJQuery() {\n get_layout();\n}", "function createEmptyNotifications(){\n\n let notDiv = document.createElement('div');\n notDiv.classList.add('notify-box', 'row', 'mx-0');\n notDiv.setAttribute('style', 'width:100%;');\n\n let notButton = document.createElement('a');\n notButton.classList.add('dropdown-item', 'col-sm-10');\n notButton.innerHTML = \"No new notifications\";\n notDiv.appendChild(notButton);\n\n return notDiv;\n}" ]
[ "0.59173167", "0.5785946", "0.5717268", "0.5693721", "0.568547", "0.559854", "0.55637395", "0.5508648", "0.5456458", "0.5445251", "0.5441511", "0.5347231", "0.5330223", "0.5285532", "0.5285411", "0.5273717", "0.5269101", "0.5268989", "0.5258898", "0.51993954", "0.51597714", "0.51410466", "0.51135653", "0.50953245", "0.5063908", "0.50577414", "0.50288033", "0.5027755", "0.5017054", "0.50093585", "0.49807397", "0.49801433", "0.4976162", "0.49722287", "0.49699917", "0.49568424", "0.49554113", "0.49550474", "0.49424985", "0.49217072", "0.49141178", "0.4911801", "0.49074832", "0.4899808", "0.4899302", "0.48974383", "0.4891837", "0.4856498", "0.4854139", "0.48528796", "0.48526233", "0.4847857", "0.4842973", "0.4836844", "0.48325765", "0.48302934", "0.48269248", "0.4817945", "0.4813255", "0.48129275", "0.48117602", "0.4810654", "0.4807243", "0.47880507", "0.4786623", "0.47860605", "0.47833997", "0.47784013", "0.47773182", "0.47731492", "0.4773069", "0.47682208", "0.47632957", "0.47618815", "0.4760978", "0.4755744", "0.475257", "0.47517467", "0.47508064", "0.4745296", "0.474258", "0.47362888", "0.47289246", "0.47275853", "0.4726358", "0.4722628", "0.47210783", "0.47084814", "0.47083718", "0.4706915", "0.47064605", "0.47060356", "0.4698393", "0.46955", "0.46941987", "0.46923602", "0.46917427", "0.46882296", "0.46872246", "0.46851036" ]
0.61223
0
notify object that gets created when you call the plugin
function RT_Notify(userOpts) { this.$el = null; this.destroyTimer = null; this.opts = { theme : "google", duration : 2000, position : "bottomright", animate : "fade", title : "", msg : "" }; this.die = function(msg) { clearTimeout(this.destroyNotify); this.$el.stop().remove(); } // destroy the notify box this.destroyNotify = function(self) { // this needs to be the object self.$el.stop().fadeOut(function() { self.die(); }); } // show the notify box this.show = function(userOpts) { this.opts = $.extend(this.opts,userOpts); // clear any existing timer clearTimeout(this.destroyTimer); // create element if it doesnt exist if(!this.$el) { this.$el = $("\ <div class='notifyBox'>\ <div class='notifyTitle'></div>\ <div class='notifyBody'></div>\ </div>\ "); $("body").append(this.$el); } var self = this; // stay on hover this.$el.hover(function() { clearTimeout(self.destroyTimer); }, function() { self.destroyTimer = setTimeout(self.destroyNotify,self.opts.duration,self); }); // put the text in this.$el.find(".notifyTitle").html(this.opts.title); this.$el.find(".notifyBody").html(this.opts.msg); // trick for icons if(!this.opts.title) { this.$el.find(".notifyTitle").css("float","left"); } else { this.$el.find(".notifyTitle").css("float","none"); } // theme this.$el.addClass(this.opts.theme); // refresh this.$el.css({ "bottom":"auto", "top":"auto", "right":"auto", "left":"auto" }); // place it switch(this.opts.position) { case "bottomright": this.$el.css({ "bottom":0, "right":0 }); break; case "bottomleft": this.$el.css({ "bottom":0, "left":0 }); break; case "topright": this.$el.css({ "top":0, "right":0 }); break; case "topleft": this.$el.css({ "top":0, "left":0 }); break; case "top": this.$el.css({ "top":0, "left":0, "max-width":"none", "width":"100%", "margin":"0px" }).addClass("full"); break; case "bottom": this.$el.css({ "bottom":0, "left":0, "max-width":"none", "width":"100%", "margin":"0px" }).addClass("full"); break; default: break; } // animate in clearTimeout(this.destroyTimer); self = this; switch(this.opts.animate) { case "fade": this.$el.stop().fadeIn(function() { self.destroyTimer = setTimeout(self.destroyNotify,self.opts.duration,self); }); break; case "slide": this.$el.stop().slideToggle(function() { self.destroyTimer = setTimeout(self.destroyNotify,self.opts.duration,self); }); break; default: break; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "onConstructed() {}", "onConstructed() {}", "createdCallback() {}", "function createNotify()\n{\n\n\t\tif( get[ 'msg' ] == 'insert' )\n\t\t{\n\n\t\t\t\tnotifySuccess( 'El menú <b>' + get[ 'element' ] + '</b> ha sido creado correctamente.' );\n\n\t\t}\n\n}", "create() {\n\t}", "afterCreate(result) {}", "async created() {\n\n\t}", "async created() {\n\n\t}", "createdCallback() {\r\n this.init()\r\n }", "afterCreation( ) {\n\n }", "create(){\n\n }", "constructor(){\n this.onNotify = (instance, payload) => {};\n }", "createdCallback() {\n self = this\n self.init()\n }", "function Notification() {\n\t\n}", "function Notification() {\n\n }", "function Notification(){}", "created() {\n this.onCreatedHandler();\n }", "InitNew() {\n\n }", "onObjectAdded(obj) {\n // obj._roomName = obj._roomName || this.DEFAULT_ROOM_NAME;\n /* this.networkTransmitter.addNetworkedEvent('objectCreate', {\n stepCount: this.gameEngine.world.stepCount,\n objectInstance: obj\n });*/\n\n if (this.options.updateOnObjectCreation) ;\n }", "create() {\n\n }", "create() {\n\n }", "create() {\n\n }", "onComponentConstructed() {}", "onComponentConstructed() {}", "function Notification() {\n\n}", "consstructor(){\n \n\n }", "function contruct() {\n\n if ( !$[pluginName] ) {\n $.loading = function( opts ) {\n $( \"body\" ).loading( opts );\n };\n }\n }", "function callCreate(object){ object.create(); }", "addedToWorld() { }", "notifyUnderConstruction() {\n UX.createNotificationForResult({ success : true, type : \"INFO\", icon : \"TRIANGLE\", key : \"common.label_under_construction\"})\n }", "onObjectAdded(obj) {\n console.log('object created event');\n this.networkTransmitter.addNetworkedEvent(\"objectCreate\", {\n stepCount: this.gameEngine.world.stepCount,\n objectInstance: obj\n });\n }", "created(broker) {}", "register() {\n this.last_notify = null;\n }", "create () {}", "create () {}", "constructor() {\n this.plugins = [];\n this.plugins_by_events = [];\n this.callbacks_by_events = [];\n \n window.custom_plugins.concrete = {}; // this is where loaded plugins are stored\n }", "attach() {}", "create() {}", "create() {}", "init() {\n }", "created () {}", "attachedCallback() {}", "attachedCallback() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "created() {}", "initPlugins() {}", "initPlugins() {}", "added(vrobject){}", "onAttach() {}", "init() {\n\t\tDebug.success(`${this.name} initialized`);\n\t}", "function NewObj(){}", "initAPI (obj, className) {\n this.plugin.eventDispatcher.registerListenersFor(obj, className);\n }", "init() {\n this.attach();\n }", "attach() { }", "attach() { }", "init() { }", "init() { }", "init() { }", "init() { }", "init() { }", "created_() {\n\t\tthis.addSurfacesFromTemplates_();\n\t\tsuper.created_();\n\t}", "init(){\n\n\n }", "monitor() {\n this.init();\n }", "function create() {\n\n}", "ready() {\n super.ready();\n\n\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "ready() {\n super.ready();\n }", "init() {\n }", "init() {\n }", "init() {\n }", "init() {\n\n }", "init() {\n\n }", "beforeCreateHook () {\n // will override by prototypes\n }", "function Plugin( element, options ) {\n this.ele = element; \n this.$ele = $(element); \n this.options = $.extend( {}, defaults, options) ; \n \n this._defaults = defaults; \n this._name = pgn; \n\n this.init(); \n }", "ready() {\r\n\t\tsuper.ready();\r\n\t}", "init(){\n }", "init() {\n //todo: other init stuff here\n }", "init() {\n this._isInitialised = true;\n this.emitBaseBubblingEvent('itemCreated');\n this.emitUnknownBubblingEvent(this.type + 'Created');\n }", "created() {\r\n\r\n\t}", "init () {\n }", "init () {}" ]
[ "0.6902134", "0.6902134", "0.6621747", "0.64504045", "0.6387139", "0.63606274", "0.6359962", "0.6359962", "0.63494164", "0.62965804", "0.6286886", "0.6279907", "0.6230027", "0.6199827", "0.6179049", "0.61629844", "0.61342055", "0.6060661", "0.6044944", "0.60363925", "0.60363925", "0.60363925", "0.59838194", "0.59838194", "0.59736526", "0.5932402", "0.58991545", "0.5894983", "0.588382", "0.5857191", "0.58395237", "0.58029157", "0.57728815", "0.57517874", "0.57517874", "0.57369083", "0.5736807", "0.5718445", "0.5718445", "0.57149017", "0.5714557", "0.57120866", "0.57120866", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710325", "0.5710223", "0.5710223", "0.5706919", "0.5705201", "0.57030755", "0.5701267", "0.5686379", "0.56843525", "0.56646377", "0.56646377", "0.5661121", "0.5661121", "0.5661121", "0.5661121", "0.5661121", "0.5657681", "0.5649482", "0.56450164", "0.5644789", "0.5638998", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.5631453", "0.56248826", "0.56248826", "0.56248826", "0.56232595", "0.56232595", "0.5620104", "0.56190556", "0.5618181", "0.5609524", "0.56076723", "0.5605137", "0.5603659", "0.5601096", "0.5585383" ]
0.0
-1
========================================================================================== Testing helper functions
function runTest(testName, f, input, output, expectFail) { if (output === void 0) { output = undefined; } if (expectFail === void 0) { expectFail = false; } try { console.log("test " + testName); console.log(" input: " + input.toString()); var result = f(input); console.log(" result: " + result.toString()); var success = !result || (result && !expectFail || !result && expectFail); console.log(success ? " passed" : " FAILED"); } catch (e) { if (expectFail) { console.log(" passed: expected fail, error caught: " + e.message); } else { console.log(" FAILED: error caught = " + e.message); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "expected(_utils) {\n return 'nothing';\n }", "function sharedTests() {\n var result;\n beforeEach(function (done) {\n result = txtToIntObj.getIntObj(this.txtdata);\n done();\n });\n it('check for existence and type', function (done) {\n expect(result).to.exist;\n expect(result).to.be.an('object');\n done();\n });\n\n it('make sure intermediate format has all titles', function (done) {\n var titles = txtToIntObj.getTitles(this.txtdata);\n done();\n });\n\n it('make sure there are no bad keys', function (done) {\n var badKeysResult = checkForBadKeys(result);\n expect(badKeysResult).to.be.true;\n done();\n });\n}", "expected( _utils ) {\n\t\t\treturn 'nothing';\n\t\t}", "function testFunction() {\n\t\t\treturn true;\n\t\t}", "function testFunction() {\n\t\t\treturn true;\n\t\t}", "function AssertTests() {\n}", "testInvalidInputParameters() {\n // invalid source directory path\n assert.throws(() => findPointsWithinRange(null, SOURCE_COORDINATES, 100), (err) => {\n if ((err instanceof InvalidDataError) && /Invalid Path name/.test(err)) {\n return true;\n }\n return false;\n }, 'Expected to throw Invalid Path name exception');\n\n // null source point\n assert.throws(() => findPointsWithinRange('./data/data.txt', null, 100), (err) => {\n if ((err instanceof InvalidDataError) && /Invalid sourcePoint/.test(err)) {\n return true;\n }\n return false;\n }, 'Expected to throw Invalid sourcePoint exception');\n\n // missing latitude source point\n assert.throws(() => findPointsWithinRange('./data/data.txt', { longitude: 0 }, 100), (err) => {\n if ((err instanceof InvalidDataError) && /Invalid sourcePoint/.test(err)) {\n return true;\n }\n return false;\n }, 'Expected to throw Invalid sourcePoint exception');\n\n // missing longitude source point\n assert.throws(() => findPointsWithinRange('./data/data.txt', { latitude: 0 }, 100), (err) => {\n if ((err instanceof InvalidDataError) && /Invalid sourcePoint/.test(err)) {\n return true;\n }\n return false;\n }, 'Expected to throw Invalid sourcePoint exception');\n\n // invalid source directory path\n assert.throws(() => findPointsWithinRange('./data/data.txt', SOURCE_COORDINATES, null), (err) => {\n if ((err instanceof InvalidDataError) && /Invalid max_distance/.test(err)) {\n return true;\n }\n return false;\n }, 'Expected to throw Invalid max_distance exception');\n console.log('testInvalidInputParameters => Successfully Completed');\n }", "function testAll() {\n testAssert()\n testRemainder()\n testConversions()\n}", "function test_missing_thumb() {\n\n}", "function commonBehaviour() {\n\t\tit(\"should not save changes when the cancel button is clicked\", () => {\n\t\t\ttransactionIndexView.getRowValues(targetRow).then(values => {\n\t\t\t\ttransactionEditView.cancel();\n\n\t\t\t\t// Row count should not have changed\n\t\t\t\ttransactionIndexView.table.rows.count().should.eventually.equal(originalRowCount);\n\n\t\t\t\t// Transaction in the target row should not have changed\n\t\t\t\ttransactionIndexView.checkRowValues(targetRow, values);\n\t\t\t});\n\t\t});\n\n\t\tdescribe(\"invalid data\", () => {\n\t\t\tbeforeEach(() => transactionEditView.clearTransactionDetails());\n\n\t\t\tit(\"should not enable the save button\", () => transactionEditView.saveButton.isEnabled().should.eventually.be.false);\n\n\t\t\t// MISSING - category name, parent & direction should show red cross when invalid\n\n\t\t\t// MISSING - form group around category name & parent should have 'has-error' class when invalid\n\n\t\t\t// MISSING - parent should behave like non-editable typeahead\n\t\t});\n\n\t\t// MISSING - error message should display when present\n\n\t\t// MISSING - category name & parent text should be selected when input gets focus\n\t}", "function TestMethods() {}", "function testQueryProcessingFunctions() {\n testEvalQueryShow();\n testEvalQueryTopK();\n testEvalQuerySliceCompare();\n\n testGetTable();\n\n testCallGcpToGetQueryResultShow();\n testCallGcpToGetQueryResultTopK(); \n testCallGcpToGetQueryResultSliceCompare();\n\n testCallGcpToGetQueryResultUsingJsonShow();\n testCallGcpToGetQueryResultUsingJsonTopK(); \n testCallGcpToGetQueryResultUsingJsonSliceCompare();\n}", "function testBadCall()\n{\n assert( 1 / 0);\n}", "function PerformanceTestCase() {\n}", "function test(a, b, s) {\n var r = extract(a, b)\n assert(r, s);\n }", "function test_utilization_host() {}", "test() {\n return true\n }", "function test_office_objects(){\n\toffice_one = new AuthorizedToRepresentOfficeLocation()\n\toffice_one.name = \"office one\"\n\t\n\n\tconsole.log(\"office_one's name: \" + office_one.name)\n\tconsole.log(\"office_one's city: \" + office_one.city)\n\t\n\tconsole.assert(office_one.name == \"office ones\")\n\tconsole.assert(office_one.city == \"\")\n}", "function error_handlingSuite () {\n return {\n test_returns_an_error_if_collection_idenifier_is_missing: function() {\n let cmd = \"/_api/document\";\n let body = \"{}\";\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_ARANGO_COLLECTION_PARAMETER_MISSING.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n },\n\n test_returns_an_error_if_the_collection_identifier_is_unknown: function() {\n let cmd = \"/_api/document?collection=123456\";\n let body = \"{}\";\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertEqual(doc.headers['content-type'], contentType);\n },\n\n test_returns_an_error_if_the_collection_name_is_unknown: function() {\n let cmd = \"/_api/document?collection=unknown_collection\";\n let body = \"{}\";\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_ARANGO_DATA_SOURCE_NOT_FOUND.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertEqual(doc.headers['content-type'], contentType);\n },\n\n test_returns_an_error_if_the_JSON_body_is_corrupted: function() {\n let cn = \"UnitTestsCollectionBasics\";\n let id = db._create(cn);\n\n try {\n let cmd = `/_api/document?collection=${id._id}`;\n let body = \"{ 1 : 2 }\";\n let doc = arango.POST_RAW(cmd, body);\n \n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_HTTP_CORRUPTED_JSON.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n \n assertEqual(db[cn].count(), 0);\n } finally {\n db._drop(cn);\n }\n },\n\n test_returns_an_error_if_an_object_sub_attribute_in_the_JSON_body_is_corrupted: function() {\n let cn = \"UnitTestsCollectionBasics\";\n let id = db._create(cn);\n\n try {\n let cmd = `/_api/document?collection=${id._id}`;\n let body = \"{ \\\"foo\\\" : { \\\"bar\\\" : \\\"baz\\\", \\\"blue\\\" : moo } }\";\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_HTTP_CORRUPTED_JSON.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n\n assertEqual(db[cn].count(), 0);\n } finally {\n db._drop(cn);\n }\n },\n\n test_returns_an_error_if_an_array_attribute_in_the_JSON_body_is_corrupted: function() {\n let cn = \"UnitTestsCollectionBasics\";\n let id = db._create(cn);\n try {\n let cmd = `/_api/document?collection=${id._id}`;\n let body = \"{ \\\"foo\\\" : [ 1, 2, \\\"bar\\\", moo ] }\";\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_HTTP_CORRUPTED_JSON.code);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n\n assertEqual(db[cn].count(), 0);\n\n } finally {\n db._drop(cn);\n }\n }\n };\n}", "function test () {\n/* eslint-enable no-unused-vars */\n var tests = []\n var validToken = 'valid'\n var invalidToken = Math.random()\n var thisFolder = DriveApp.getFolderById(thisFolderId)\n\n tokens[validToken] = 'description'\n\n tests.push(function missingOrInvalidTokenCausesError () {\n assertEqual(\n stringGetResponse({\n token: invalidToken\n }),\n errorPrefix + invalidTokenError\n )\n })\n\n tests.push(function missingPathCausesError () {\n assertEqual(\n stringGetResponse({\n token: validToken\n }),\n errorPrefix + missingPathError\n )\n })\n\n tests.push(function fileOfWrongTypeCausesError () {\n var fileName = 'secrets server invalid format test file'\n var file = thisFolder.createFile(fileName, 'content')\n\n assertEqual(\n stringGetResponse({\n token: validToken,\n path: fileName\n }),\n errorPrefix + unreadableFileError\n )\n\n file.setTrashed(true)\n })\n\n tests.push(function missingFileCausesError () {\n assertEqual(\n stringGetResponse({\n token: validToken,\n path: 'not a real file'\n }),\n errorPrefix + missingFileError\n )\n })\n\n tests.push(function missingDirectoryCausesError () {\n assertEqual(\n stringGetResponse({\n token: validToken,\n path: 'missingDir/someFile'\n }).indexOf(missingFolderError) !== -1,\n true\n )\n })\n\n tests.push(function nestedFileOfCorrectTypeIsRetrieved () {\n var dirName = 'valid directory test'\n var nextDirName = 'valid directory test subdirectory'\n var fileName = 'valid test file'\n var fileContent = 'content'\n var topDir = thisFolder.createFolder(dirName)\n var nextDir = topDir.createFolder(nextDirName)\n var file = DocumentApp.create(fileName)\n\n file.getBody().setText(fileContent)\n nextDir.addFile(DriveApp.getFileById(file.getId()))\n\n assertEqual(\n stringGetResponse({\n token: validToken,\n path: [dirName, nextDirName, fileName].join('/')\n }),\n fileContent\n )\n\n topDir.setTrashed(true)\n })\n\n tests.forEach(function (test) { test() })\n Logger.log('all tests passed')\n}", "function startAllTests(){ \n testGetObjectFromArrays();\n testNormalizeHeader();\n testFillInTemplateFromObject();\n testIsCellEmpty();\n testIsAlnum();\n testIsDigit();\n}", "function test_candu_graphs_datastore_vsphere6() {}", "function generateTest() {\n // TODO\n}", "function testInternalFunction(f) {\n var exec = f.factory();\n var args = [];\n\n for (var i = 1; i < arguments.length; i++) {\n args.push(new Result(arguments[i]));\n }\n return exec.execute(args);\n}", "function _test(fnName){\n return function(){\n var input = arguments;\n return function(output){\n return function(testText){\n\tvar result = _[fnName].apply(null,input);\n\tif(_.isEqual(result,output)){\n\t console.log(\"Passed: \" + fnName + \": \" + testText);\n\t}\n\telse{\n\t console.log(\"Failed: \" + fnName + \": \" + testText);\n\t console.log(\"input\");\n\t console.log(input);\n\t console.log(\"expected output:\");\n\t console.log(output);\n\t console.log(\"returned:\");\n\t console.log(result);\n\t}\n };\n };\n };\n}", "function testIt() {\n const objectA = {\n id: 2,\n name: 'Jane Doe',\n age: 34,\n city: 'Chicago',\n };\n \n const objectB = {\n id: 3,\n age: 33,\n city: 'Peoria',\n };\n \n const objectC = {\n id: 9,\n name: 'Billy Bear',\n age: 62,\n city: 'Milwaukee',\n status: 'paused',\n };\n \n const objectD = {\n foo: 2,\n bar: 'Jane Doe',\n bizz: 34,\n bang: 'Chicago',\n };\n \n const expectedKeys = ['id', 'name', 'age', 'city'];\n \n if (typeof validateKeys(objectA, expectedKeys) !== 'boolean') {\n console.error('FAILURE: validateKeys should return a boolean value');\n return;\n }\n \n if (!validateKeys(objectA, expectedKeys)) {\n console.error(\n `FAILURE: running validateKeys with the following object and keys\n should return true but returned false:\n Object: ${JSON.stringify(objectA)}\n Expected keys: ${expectedKeys}`\n );\n return;\n }\n \n if (validateKeys(objectB, expectedKeys)) {\n console.error(\n `FAILURE: running validateKeys with the following object and keys\n should return false but returned true:\n Object: ${JSON.stringify(objectB)}\n Expected keys: ${expectedKeys}`\n );\n return;\n }\n \n if (validateKeys(objectC, expectedKeys)) {\n console.error(\n `FAILURE: running validateKeys with the following object and keys\n should return false but returned true:\n Object: ${JSON.stringify(objectC)}\n Expected keys: ${expectedKeys}`\n );\n return;\n }\n \n if (validateKeys(objectD, expectedKeys)) {\n console.error(\n `FAILURE: running validateKeys with the following object and keys\n should return false but returned true:\n Object: ${JSON.stringify(objectD)}\n Expected keys: ${expectedKeys}`\n );\n return;\n }\n \n console.log('SUCCESS: validateKeys is working');\n }", "function test_candu_collection_tab() {}", "function test_bottleneck_provider() {}", "function UriTestSuite() {\n\n this.name = \"Uri\";\n this.tag = \"utils\";\n\n // convenience names\n var LOCALHOST = SDUri_FILE_HOSTNAME,\n PAGE_HOSTNAME = SDUri_PAGE_HOSTNAME;\n\n // this function was tested manually\n function randomlyCapitalize(str) {\n return str.replace(/\\w/g, function (letter) {\n return Math.random() < 0.5 ? letter.toUpperCase() : letter.toLowerCase();\n });\n }\n\n function verifyHostname(url, expHostname) {\n var hostname = SDUri_getHostname(url);\n expectTypeof(hostname, \"string\");\n expectEqual(hostname, expHostname || PAGE_HOSTNAME);\n };\n\n this.hostname = function () {\n\n function verify(url, expHostname) {\n verifyHostname(url, expHostname);\n };\n\n // Testing hostname edge cases...\n verify(\"\"); // assuming an empty URL is legal\n verify(\".\");\n verify(\"./\");\n verify(\"..\");\n verify(\"../\");\n verify(\"/\");\n verify(\"/.\");\n verify(\"/..\");\n verify(\"/../.\");\n\n // Testing hostname for relative URLs...\n verify(\"foo.jpg\");\n verify(\"../foo.jpg\");\n verify(\"images/foo.jpg\");\n verify(\"../images/foo.jpg\");\n verify(\"images/foo/../bar/\");\n verify(\"../../images/foo/bar/\");\n verify(\"/images/foo/bar.jpg\");\n verify(\"/images/foo/../bar/image.jpg\");\n verify(\"www.example.com/foo/bar/\"); // examples of incorrectly relative URLs\n verify(\"foo.bar.org/images/../../image.jpg\");\n\n // Testing hostname for absolute URLs...\n verify(\"http://example.com/\", \"example.com\");\n verify(\"http://example.com:80/\", \"example.com\"); // port numbers...\n verify(\"http://example.com:9999/\", \"example.com\"); // shouldn't matter!\n verify(\"http://sub.example.com/\", \"sub.example.com\");\n verify(\"http://foo.bar.baz.example.com/\", \"foo.bar.baz.example.com\");\n verify(\"http://example.com/foo/bar/baz/\", \"example.com\");\n verify(\"http://example.com/foo/bar/baz.jpg\", \"example.com\");\n verify(\"http://foo.bar.example.com/baz/image.jpg\", \"foo.bar.example.com\");\n verify(\"http://t2.tiles.virtualearth.net/tiles/h02123012?g=282\", \"t2.tiles.virtualearth.net\");\n verify(\"http://t0.tiles.virtualearth.net/tiles/r02123010?g=282&shading=hill\", \"t0.tiles.virtualearth.net\");\n\n // Testing hostname for file:// URLs...\n verify(\"file:///C:/\", LOCALHOST);\n verify(\"file:///C:/Windows/\", LOCALHOST);\n verify(\"file:///C:/Windows/System32/mshtml.dll\", LOCALHOST);\n verify(\"file:///Users/\", LOCALHOST);\n verify(\"file:///Users/me/\", LOCALHOST);\n verify(\"file:///Users/me/Sites/index.html\", LOCALHOST);\n\n // Testing hostname for https:// URLs...\n verify(\"https://sub.example.com/\", \"sub.example.com\");\n verify(\"https://foo.bar.baz.example.com/\", \"foo.bar.baz.example.com\");\n verify(\"https://example.com/foo/bar/baz/\", \"example.com\");\n verify(\"https://example.com/foo/bar/baz.jpg\", \"example.com\");\n }\n\n this.hostnameCaps = function () {\n\n function verify(url, expHostname) {\n // hostname should remain all lowercase\n verifyHostname(randomlyCapitalize(url), expHostname);\n };\n\n // Testing hostname random capitalizations...\n // all of these examples are taken from test cases above, but are now being\n // randomly capitalized, letter by letter...\n verify(\"http://foo.bar.example.com/baz/image.jpg\", \"foo.bar.example.com\");\n verify(\"https://t2.tiles.virtualearth.net/tiles/h02123012?g=282\", \"t2.tiles.virtualearth.net\");\n verify(\"images/foo/../bar/\");\n verify(\"/images/foo/../bar/image.jpg\");\n verify(\"www.example.com/foo/bar/\");\n verify(\"file:///C:/Windows/System32/mshtml.dll\", LOCALHOST);\n verify(\"file:///Users/me/Sites/index.html\", LOCALHOST);\n }\n}", "verify() {\n // TODO\n }", "function ct_test() {\n return ok;\n}", "function test_testApiKey() {\n hfapi.testApiKey((error, valid) => {\n assert.isNull(error, 'The request should not generate any errors.');\n assert.isTrue(valid, 'Valid should be true if API key is valid.');\n });\n}", "function testNoteList() {\n var noteList = new NoteList;\n\n assert.isTrue(noteList);\n\n assert.isTrue(Array.isArray(noteList.getNotes()));\n\n //assert.isTrue(noteList.createNote());\n \n}", "function testIt() {\n\n var testData = [\n {name: 'Jane Doe', grade: 'A'},\n {name: 'John Dough', grade: 'B'},\n {name: 'Jill Do', grade: 'A'}\n ];\n\n var expectations = [\n 'Jane Doe: A',\n 'John Dough: B',\n 'Jill Do: A'\n ];\n\n var results = makeStudentsReport(testData);\n\n if (!(results && results instanceof Array)) {\n console.error(\n 'FAILURE: `makeStudentsReport` must return an object');\n return\n }\n if (results.length !== testData.length) {\n console.error(\n 'FAILURE: test data had length of ' + testData.length +\n ' but `makeStudentsReport` returned array of length ' + results.length);\n return\n }\n for (var i=0; i < expectations.length; i++) {\n var expect = expectations[i];\n if (!results.find(function(item) {\n return item === expect;\n })) {\n console.error(\n 'FAILURE: `makeStudentsReport` is not ' +\n 'producing expected strings'\n );\n return\n }\n }\n console.log('SUCCESS: `makeStudentsReport` is working');\n}", "function setUp() {\n}", "function test_service_bundle_vms() {}", "function zg(e,t){if(!e){const r=new Error(t||\"Assertion failed\");throw Error.captureStackTrace&&Error.captureStackTrace(r,zg),r}}", "function TestUtil(cmd)\r\n{\r\n try\r\n {\r\n return (0 == WshShell.Run(cmd + \" /?\", 0, true));\r\n }\r\n catch (e) {}\r\n \r\n return false;\r\n}", "private public function m246() {}", "function main(a, b){\n testTopLevelAccessors()\n\n//FIXME: once worked\n// testNestedAccessors()\n \n// testKeyedVariant2()\n \n testNumberSubScripting()\n \n testNestedAssignment()\n\n testClassPropertyAssignmentSubscripting()\n\n var zero = 0\n return zero.intValue\n}", "testAdvanced() {\n var a = 3;\n var b = a;\n this.assertIdentical(a, b, \"A rose by any other name is still a rose\");\n this.assertInRange(\n 3,\n 1,\n 10,\n \"You must be kidding, 3 can never be outside [1,10]!\"\n );\n }", "function exposeTestFunctionNames()\n{\nreturn ['XPathResult_resultType'];\n}", "function test_hasProperty_null (){ assertFalse( compare.hasProperty( null, 'a' ) ) }", "function bonusGame(){\n\tdescribe(\"Bonus Game\", function(){\n\t\tdescribe(\"XML Verification\", function(){\n\t\t\tit(\"Math XML should contain 12 elements in the 'wheelWedges' field\", function(){\n\n\t\t\t\txmlData.wheelWedges[0].split(',').length.should.equal(12);\n\t\t\t});\n\n\t\t\tit(\"Math XML should contain 10 elements in the 'pickObjects' field\", function(){\n\n\t\t\t\txmlData.pickObjects[0].split(',').length.should.equal(10);\n\t\t\t});\n\n\t\t\tit(\"'pickObjects' should be in the correct format\", function(){\n\n\t\t\t\tvar pickArray = xmlData.pickObjects[0].split(',');\n\n\t\t\t\tfor (var i=0; i<pickArray.length; i++)\n\t\t\t\t{\n\t\t\t\t\t// The pick objects must be equal to or greater than -2\n\t\t\t\t\tif (parseInt(pickArray[i]) < -2)\n\t\t\t\t\t{\n\t\t\t\t\t\tthrow new Error(\"Invalid 'pickObjects' element of \" + pickArray[i] + \" (must be >= -2)\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\tdescribe(\"Bonus Gameplay\", function(){\n\n\t\t\t// Run a whole bunch of spins to try and get a bonus state\n\t\t\tbonusPick = null;\n\n\t\t\tit (\"Should get a bonus state after at most \" + numberOfSpins + \" spins\", function(){\n\n\t\t\t\t// Run full games until we get a bonus state (up to however many spins)\n\t\t\t\tspinCount = 0;\n\n\t\t\t\twhile (spinCount++ <= numberOfSpins && !bonusPick)\n\t\t\t\t{\n\t\t\t\t\tspinState = game.createState(totalSpins, totalSeconds);\n\n\t\t\t\t\twhile (spinState.spinsLeft > 0)\n\t\t\t\t\t{\n\t\t\t\t\t\tvar spinData = game.spin(spinState);\n\t\t\t\t\t\tspinState = spinData.state;\n\n\t\t\t\t\t\tif (spinState.bonusPick)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tbonusPick = spinState.bonusPick\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Error if we never got a bonus pick\n\t\t\t\tif (!bonusPick) throw new Error(\"No bonusPick after \" + numberOfSpins + \" spins!\");\n\t\t\t});\n\n\t\t\tit (\"'bonusPick.wheel' should be identical to 'wheelWedges' in math XML\", function(){\n\n\t\t\t\tbonusPick.should.have.property(\"wheel\");\n\n\t\t\t\twedgesArr = xmlData.wheelWedges[0].split(',');\n\t\t\t\tbonusPick.wheel.length.should.equal(wedgesArr.length);\n\n\t\t\t\tfor (var i=0; i<bonusPick.wheel.length; i++)\n\t\t\t\t{\n\t\t\t\t\tparseInt(bonusPick.wheel[i]).should.equal(parseInt(wedgesArr[i]));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tit (\"'bonusPick.mods' should contain all of the pickObjects defined in math XML\", function(){\n\n\t\t\t\tbonusPick.should.have.property(\"mods\");\n\n\t\t\t\t// Populate an array with the expected values from the math XML, in the expected format,\n\t\t\t\t// FROM MATH XML \"Numbers > 0 are multipliers, 0 is a spin of the wheel, -1 are pointers that are added, -2 is a pooper\"\n\n\t\t\t\tvar pickArray = xmlData.pickObjects[0].split(',');\n\t\t\t\tbonusPick.mods.length.should.equal(pickArray.length);\n\n\t\t\t\t// Parse the numeric values from the xml into the format expected by the client and check values\n\t\t\t\tfor (var i=0; i<pickArray.length; i++)\n\t\t\t\t{\t\n\t\t\t\t\tif (parseInt(pickArray[i]) > 0){\n\t\t\t\t\t\tpickArray[i] = pickArray[i] + \"x\";\n\t\t\t\t\t}\n\t\t\t\t\telse if (parseInt(pickArray[i]) == 0){\n\n\t\t\t\t\t\tpickArray[i] = \"freespin\";\n\t\t\t\t\t}\n\t\t\t\t\telse if (parseInt(pickArray[i]) == -1){\n\n\t\t\t\t\t\tpickArray[i] = \"pointer\";\n\t\t\t\t\t}\n\t\t\t\t\telse if (parseInt(pickArray[i]) == -2){\n\n\t\t\t\t\t\tpickArray[i] = \"pooper\";\n\t\t\t\t\t}\n\n\t\t\t\t\t// Search the returned picks for the parsed value\n\t\t\t\t\tfor (var j=0; j<bonusPick.mods.length; j++)\n\t\t\t\t\t{\n\t\t\t\t\t\tif (bonusPick.mods[j].indexOf(pickArray[i]) != -1)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpickArray.splice(i--, 1);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// If there are still any bonus picks left, it means we didn't include them all\n\t\t\t\tpickArray.length.should.equal(0);\n\t\t\t});\n\n\t\t\tit (\"'bonusPick' field should contain 'bonusWin'\", function(){\n\n\t\t\t\tbonusPick.should.have.property(\"bonusWin\");\n\t\t\t});\n\n\t\t\tit (\"'bonusPick' field should contain 'totalWin'\", function (){\n\n\t\t\t\tbonusPick.should.have.property(\"totalWin\");\n\t\t\t});\n\n\t\t\tit (\"Score should match calulations based off of provided mods\", function (){\n\n\t\t\t\tvar mult = 0;\n\t\t\t\tvar pointArr = [1];\n\t\t\t\tvar score = 0;\n\n\t\t\t\t// First calculate the multiplyer and pointers\n\t\t\t\tfor (var i=0; i<bonusPick.mods.length; i++){\n\n\t\t\t\t\tif (bonusPick.mods[i].indexOf('x') != -1){\n\n\t\t\t\t\t\tmult += parseInt(bonusPick.mods[i].slice(0, -1))\n\t\t\t\t\t}\n\t\t\t\t\telse if (bonusPick.mods[i].indexOf(\"pointer\") != -1){\n\n\t\t\t\t\t\tpointArr.push(parseInt(bonusPick.mods[i].slice(7)))\n\t\t\t\t\t}\n\t\t\t\t\telse if (bonusPick.mods[i].indexOf(\"pooper\") != -1){\n\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Now calculate spins\n\t\t\t\tfor (var i=0; i<bonusPick.mods.length; i++)\n\t\t\t\t{\n\n\t\t\t\t\tif (bonusPick.mods[i].indexOf(\"freespin\") != -1){\n\n\t\t\t\t\t\toffset = parseInt(bonusPick.mods[i].slice(8));\n\n\t\t\t\t\t\tscore += calcSpinScore(bonusPick.wheel, offset, mult, pointArr);\n\t\t\t\t\t}\n\t\t\t\t\telse if (bonusPick.mods[i].indexOf(\"pooper\") != -1){\n\n\t\t\t\t\t\toffset = parseInt(bonusPick.mods[i].slice(6));\n\n\t\t\t\t\t\tscore += calcSpinScore(bonusPick.wheel, offset, mult, pointArr);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tbonusPick.bonusWin.should.equal(score);\n\t\t\t});\n\t\t});\n\n\t\tdescribe(\"Bonus Game Aspects\", function(){\n\n\t\t\tit (\"Should always get pointers in new positions over \" + numberOfBonus + \" bonuses\", function(){\n\n\t\t\t\tthis.timeout(0);\n\n\t\t\t\tbonusCount = 0;\n\n\t\t\t\twhile (bonusCount < numberOfBonus){\n\n\t\t\t\t\tspinState = game.createState(totalSpins, totalSeconds);\n\n\t\t\t\t\twhile (spinState.spinsLeft > 0){\n\n\t\t\t\t\t\tvar spinData = game.spin(spinState);\n\t\t\t\t\t\tspinState = spinData.state;\n\n\t\t\t\t\t\tif (spinState.bonusPick){\n\n\t\t\t\t\t\t\tbonusCount++;\n\t\t\t\t\t\t\t//Log the current bonus count every 100 bonuses\n\t\t\t\t\t\t\tif (bonusCount % 100 == 0)\n\t\t\t\t\t\t\t\tconsole.log(\"Curent Bonus Count: \" + bonusCount);\n\n\t\t\t\t\t\t\tvar currentPointers = [1];\n\n\t\t\t\t\t\t\tvar bonusPick = spinState.bonusPick\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (var i=0; i<bonusPick.mods.length; i++){\n\n\t\t\t\t\t\t\t\tif (bonusPick.mods[i].indexOf(\"pointer\") != -1){\n\n\t\t\t\t\t\t\t\t\t// For every pointer returned, make sure that it is a new pointer\n\t\t\t\t\t\t\t\t\tvar pointerValue = parseInt(bonusPick.mods[i].slice(7))\n\n\t\t\t\t\t\t\t\t\tfor (var j=0; j<currentPointers.length; j++){\n\n\t\t\t\t\t\t\t\t\t\tcurrentPointers[j].should.not.equal(pointerValue);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\tcurrentPointers.push(pointerValue);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tit (\"Should never get a pooper in the first four bonus picks over \" + numberOfBonus + \" bonuses\", function(){\n\n\t\t\t\tthis.timeout(0);\n\n\t\t\t\tbonusCount = 0;\n\n\t\t\t\twhile (bonusCount < numberOfBonus){\n\n\t\t\t\t\tspinState = game.createState(totalSpins, totalSeconds);\n\n\t\t\t\t\twhile (spinState.spinsLeft > 0){\n\n\t\t\t\t\t\tvar spinData = game.spin(spinState);\n\t\t\t\t\t\tspinState = spinData.state;\n\n\t\t\t\t\t\tif (spinState.bonusPick){\n\n\t\t\t\t\t\t\tbonusCount++;\n\t\t\t\t\t\t\t//Log the current bonus count every 100 bonuses\n\t\t\t\t\t\t\tif (bonusCount % 100 == 0)\n\t\t\t\t\t\t\t\tconsole.log(\"Curent Bonus Count: \" + bonusCount);\n\n\t\t\t\t\t\t\tvar bonusPick = spinState.bonusPick\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tfor (var i=0; i<bonusPick.mods.length; i++){\n\n\t\t\t\t\t\t\t\tif (bonusPick.mods[i].indexOf(\"pooper\") != -1){\n\n\t\t\t\t\t\t\t\t\tif (i < 4)\n\t\t\t\t\t\t\t\t\t\tthrow new Error(\"Pooper in a bonus pick index less than 4!\")\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t});\n}", "testObjectAssertions() {\n var objConstructor = {}.constructor;\n\n this.assertIdentical({ a: 12 }.constructor, objConstructor);\n /* eslint-disable-next-line no-new-object */\n this.assertIdentical(new Object().constructor, objConstructor);\n\n var qxObj = new qx.core.Object();\n this.assertNotIdentical(qxObj.constructor, objConstructor);\n this.assertNotIdentical((1).constructor, objConstructor);\n this.assertNotIdentical(\"Juhu\".constructor, objConstructor);\n this.assertNotIdentical(/abc/.constructor, objConstructor);\n qxObj.dispose();\n }", "function test_candu_graphs_vm_compare_host_vsphere65() {}", "function testRun()\r\n{\r\n}", "function TestRoot() {}", "function compareMethods(path) {\n var new_data = safeLoadFile(path);\n var old_data = safeRequire(path);\n if (JSON.stringify(new_data) === JSON.stringify(old_data) ) {\n console.log(\"test passed\", new_data, old_data); \n } else {\n console.log(\"test failed\"); \n }\n}", "function DrawTest(){\n describe(\"Is it a draw?\", () => {\n it(\"Should return that there was a draw\", () => {\n expect(winning.isWinner(draw,\"X\",9)).toEqual({ \"winner\": \"Draw\" });\n });\n});\n}", "beforeEach() {}", "test() {\n return this.hexSHA1(\"abc\") === \"a9993e364706816aba3e25717850c26c9cd0d89d\";\n }", "function testAddSuccess() {\r\n assertEquals(2, add(1,1));\r\n}", "function test_getRequestCount() {\n assert.isNumber(hfapi.getRequestCount(), 'Total request count should be a number.');\n}", "function testReturnData() {\n describe('Return Test Data', function() {\n it('should return data from the database and return data or error', function(done) {\n var session = driver.session();\n session\n .run('MATCH (t:Test) RETURN t')\n .then(function (result) {\n session.close();\n result.records.forEach(function (record) {\n describe('Data Returned Result', function() {\n\n it('should return test data from database', function(done) {\n assert(record);\n done();\n });\n\n it('should have length of one', function(done) {\n assert.equal(record.length, 1);\n done();\n });\n\n var result = record._fields[0];\n\n it('should return correct label type', function(done) {\n assert.equal(typeof result.labels[0], 'string');\n done();\n });\n\n it('should have label \\'Test\\'', function(done) {\n assert.equal(result.labels[0], 'Test');\n done();\n });\n\n it('should return correct testdata type', function(done) {\n assert.equal(typeof result.properties.testdata,'string');\n done();\n });\n\n it('should have property \\'Testdata\\' containing \\'This is an integration test\\'', function(done) {\n assert.equal(result.properties.testdata, 'This is an integration test');\n done();\n });\n });\n });\n done();\n })\n .catch(function (error) {\n session.close();\n console.log(error);\n describe('Data Returned Error', function() {\n it('should return error', function(done) {\n assert(error);\n done();\n });\n });\n done();\n });\n });\n });\n}", "function test_Ball_LessThan_Zebra() {\n var result = comparer.compareStrings(\"Ball\", \"Zebra\");\n fx.assert(result < 0);\n}", "function ok(test, desc) { expect(test).toBe(true); }", "function fullTest(Srl){\n\tGen = Srl.Generative;\n\tAlgo = Srl.Algorithmic;\n\tMod = Srl.Transform;\n\tRand = Srl.Stochastic;\n\tStat = Srl.Statistic;\n\tTL = Srl.Translate;\n\tUtil = Srl.Utility;\n\n\t// testSerial();\n\ttestGenerative();\n\ttestAlgorithmic();\n\ttestStochastic();\n\ttestTransform();\n\ttestStatistic();\n\ttestTranslate();\n\ttestUtility();\n}", "function test_notification_banner_vm_provisioning_notification_and_service_request_should_be_in_syn() {}", "function testIt() {\n var toDos = ['get milk', 'walk dog', 'pay bills', 'eat dinner'];\n var owner = 'Steve';\n var myToDos = makeToDos(owner, toDos);\n if (!myToDos || !myToDos instanceof Object) {\n console.error('FAILURE: `makeToDos` must return an object');\n return;\n }\n\n var expectedKeys = ['owner', 'toDos', 'generateHtml'];\n if (Object.keys(myToDos).length !== expectedKeys.length || !expectedKeys.every(function(key) {\n return key in myToDos;\n })) {\n console.error('FAILURE: expected `makeToDos` to have a `.toDos` property ' +\n 'whose value is an array of todo items');\n return;\n }\n\n if (myToDos.owner !== owner) {\n console.error('FAILURE: expected `makeToDos` to return an object with `.owner` ' +\n 'set to value passed in for `owner`, in this case ' + owner);\n return;\n }\n if (!toDos.every(function(toDo) {\n return myToDos.toDos.find(function(_toDo) {\n return _toDo === toDo;\n })\n })) {\n console.error('FAILURE: makeToDos toDos property returned' + Object.values(myToDos.toDos) + '. Expected: ' + Object.values(todos));\n }\n\n var element = $(myToDos.generateHtml());\n\n if (element.length !== 1) {\n console.error('FAILURE: `makeToDos` must return an object with a `generateHtml` ' +\n 'method that returns an unordered list');\n return;\n }\n\n if (!toDos.every(function(toDo) {\n return element.find('li:contains(\"' + toDo + '\")').length === 1;\n })) {\n console.error('FAILURE: generateHtml must return li element for every todo');\n return\n }\n\n console.log('SUCCESS: `makeToDos` is working');\n\n}", "function testStringEncodings(){\n\t\tvar StringUtils = LanguageModule.StringUtils;\n\t\tvar stringUtils = new StringUtils();\n\t\tvar encodings = stringUtils.stringEncodings;\n\t\texpect(_.isObject(encodings)).to.eql(true);\n\t\texpect(_.has(encodings, \"ASCII\")).to.eql(true);\n\t\texpect(_.has(encodings, \"UTF8_BINARY\")).to.eql(true);\n\t\texpect(_.has(encodings, \"ISO_8859_1\")).to.eql(true);\n\t\texpect(encodings.UTF8_BINARY).to.eql(0);\n\t\texpect(encodings.ASCII).to.eql(1);\n\t\texpect(encodings.ISO_8859_1).to.eql(2);\n\t}", "private internal function m248() {}", "static private internal function m121() {}", "function testGetBase() {\n\n var yoke = new Yoke();\n // all resources are OK\n yoke.use(function (request) {\n request.response.end('OK');\n });\n\n new YokeTester(yoke).request('GET', '/', function(resp) {\n vassert.assertTrue(200 == resp.statusCode);\n vassert.testComplete();\n });\n}", "function __JUAssert(){;}", "function GetTestability() {}", "function GetTestability() {}", "function GetTestability() {}", "function GetTestability(){}", "function testFunction() {\n return 'this is a test'\n}", "function fn2(data) {\n assert.strictEqual(data, 'data', 'should not be null err argument');\n}", "toBeObject(expected) {\n if (typeof expected === \"object\" && !Array.isArray(expected)) {\n // typeof is not safe. Must explicitidly check null values and arrays too.\n return {\n message: \"Is Object\",\n pass: true,\n };\n }\n return {\n message: () => `This is not an object, it's::::${typeof expect}`,\n pass: false,\n };\n }", "function test_abc_EqualTo_Abc() {\n var result = comparer.compareStrings(\"abc\", \"Abc\");\n fx.assert(result === 0);\n}", "function fooTest() { }", "function test_bottleneck_datastore() {}", "function mock() {\n\twindow.SegmentString = Rng.Range;\n}", "function error_handlinSuite () {\n return {\n test_add_function__without_name: function() {\n let body = \"{ \\\"code\\\" : \\\"function () { return 1; }\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.code);\n },\n\n test_add_function__invalid_name_1: function() {\n let body = \"{ \\\"name\\\" : \\\"\\\", \\\"code\\\" : \\\"function () { return 1; }\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.code);\n },\n\n test_add_function__invalid_name_2: function() {\n let body = \"{ \\\"name\\\" : \\\"_aql::foobar\\\", \\\"code\\\" : \\\"function () { return 1; }\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.code);\n },\n\n test_add_function__invalid_name_3: function() {\n let body = \"{ \\\"name\\\" : \\\"foobar\\\", \\\"code\\\" : \\\"function () { return 1; }\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_NAME.code);\n },\n\n test_add_function__no_code: function() {\n let body = \"{ \\\"name\\\" : \\\"myfunc::mytest\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.code);\n },\n\n test_add_function__invalid_code: function() {\n let body = \"{ \\\"name\\\" : \\\"myfunc::mytest\\\", \\\"code\\\" : \\\"function ()\\\" }\";\n let doc = arango.POST_RAW(api, body);\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_BAD_PARAMETER.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_INVALID_CODE.code);\n },\n\n test_deleting_non_existing_function: function() {\n let doc = arango.DELETE_RAW(api + \"/mytest%3A%3Amynonfunc\");\n\n assertEqual(doc.code, internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertEqual(doc.headers['content-type'], contentType);\n assertTrue(doc.parsedBody['error']);\n assertEqual(doc.parsedBody['code'], internal.errors.ERROR_HTTP_NOT_FOUND.code);\n assertEqual(doc.parsedBody['errorNum'], internal.errors.ERROR_QUERY_FUNCTION_NOT_FOUND.code);\n }\n };\n}", "function test_a123_LessThan_a456() {\n var result = comparer.compareStrings(\"a123\", \"a456\");\n fx.assert(result < 0);\n}", "function test_timepicker_should_pass_correct_timing_on_service_order() {}", "function Tile_Test() {\r\n 'use strict';\r\n\r\n QUnit.module('Tile');\r\n\r\n QUnit.test('basic', function(assert) {\r\n\r\n\t var bad = Tile._kBadTile;\r\n\t var char1 = new Tile(Tile.TileType.CHARACTER, 1);\r\n\t var char3 = new Tile(Tile.TileType.CHARACTER, 3);\r\n\t var wind3 = new Tile(Tile.TileType.WIND, 3);\r\n\t var drag1 = new Tile(Tile.TileType.DRAGON, 1);\r\n\t var char1b = new Tile(Tile.TileType.CHARACTER, 1);\r\n\t var flower2 = new Tile(Tile.TileType.FLOWER, 2);\r\n\r\n\t // Check each method\r\n\t assert.equal(bad.isValid(), false);\r\n\t assert.equal(char1.isValid(), true);\r\n\r\n\t // Warning: all \"kBadTile\" are considered different\r\n\t assert.equal(bad.sameAs(Tile._kBadTile), false);\r\n\t assert.equal(char1.sameAs(bad), false);\r\n\t assert.equal(char1.sameAs(drag1), false);\r\n\t assert.equal(char1.sameAs(char1b), true);\r\n\r\n\t assert.equal(bad.isFlower(), false);\r\n\t assert.equal(char1.isFlower(), false);\r\n\t assert.equal(char1.isFlower(), false);\r\n\t assert.equal(wind3.isFlower(), false);\r\n\t assert.equal(drag1.isFlower(), false);\r\n\t assert.equal(flower2.isFlower(), true);\r\n\r\n\t assert.equal(bad.isHonor(), false);\r\n\t assert.equal(char1.isHonor(), false);\r\n\t assert.equal(wind3.isHonor(), true);\r\n\t assert.equal(drag1.isHonor(), true);\r\n\t assert.equal(flower2.isHonor(), false);\r\n\r\n\t assert.equal(bad.isTerminal(), false);\r\n\t assert.equal(char1.isTerminal(), true);\r\n\t assert.equal(char3.isTerminal(), false);\r\n\t assert.equal(wind3.isTerminal(), false);\r\n\t assert.equal(drag1.isTerminal(), false);\r\n\t assert.equal(flower2.isTerminal(), false);\r\n\r\n\t assert.equal(bad.isRegular(), false);\r\n\t assert.equal(char1.isRegular(), true);\r\n\t assert.equal(char3.isRegular(), true);\r\n\t assert.equal(wind3.isRegular(), false);\r\n\t assert.equal(drag1.isRegular(), false);\r\n\t assert.equal(flower2.isRegular(), false);\r\n\r\n\t assert.equal(bad.toString(),\t 'Bad Tile (-10,bamboo)');\r\n\t assert.equal(char1.toString(), 'character-1');\r\n\t assert.equal(char3.toString(), 'character-3');\r\n\t assert.equal(wind3.toString(), 'West');\r\n\t assert.equal(drag1.toString(), 'White Dragon');\r\n\t assert.equal(flower2.toString(), 'Orchid');\r\n });\r\n}", "function test_false_string_case (){ assertFalse( compare.isValue( 'wa', 'Wa', false ) ); }", "function do_test_uri_basic(aTest) {\n var URI;\n\n try {\n URI = gIoService.newURI(aTest.spec);\n } catch (e) {\n var url=aTest.relativeURI ? (aTest.spec +\"<\"+aTest.relativeURI) : aTest.spec;\n //do_info(\"Caught error on parse of\" + aTest.spec + \" Error: \"+e.name+\" \" + e.result);\n dump(\"\\n{\\\"url\\\":\\\"\"+ url+\"\\\", \\\"exception\\\":\\\"\"+e.name+\" \"+e.result+\"\\\"}\");\n if (aTest.fail) {\n Assert.equal(e.result, aTest.result);\n return;\n }\n do_throw(e.result);\n \n }\n\n if (aTest.relativeURI) {\n var relURI;\n\n try {\n relURI = gIoService.newURI(aTest.relativeURI, null, URI);\n } catch (e) {\n /*do_info(\n \"Caught error on Relative parse of \" +\n aTest.spec +\n \" + \" +\n aTest.relativeURI +\n \" Error: \" +\n e.result\n );*/\n var url=aTest.spec +\"<\"+aTest.relativeURI;\n //do_info(\"Caught error on parse of\" + aTest.spec + \" Error: \"+e.name+\" \" + e.result);\n dump(\"\\n{\\\"url\\\":\\\"\"+ url+\"\\\", \\\"exception\\\":\\\"\"+e.name+\" \"+e.result+\"\\\"}\");\n\n if (aTest.relativeFail) {\n Assert.equal(e.result, aTest.relativeFail);\n return;\n }\n \n do_throw(e.result);\n \n }\n URI=relURI;\n }\n\n \n // Check the various components \n try {\n do_check_property(aTest, URI, \"scheme\");\n do_check_property(aTest, URI, \"query\");\n do_check_property(aTest, URI, \"ref\");\n do_check_property(aTest, URI, \"port\");\n do_check_property(aTest, URI, \"username\");\n do_check_property(aTest, URI, \"password\");\n do_check_property(aTest, URI, \"host\");\n do_check_property(aTest, URI, \"specIgnoringRef\");\n do_check_property(aTest, URI, \"hasRef\");\n do_check_property(aTest, URI, \"prePath\");\n do_check_property(aTest, URI, \"pathQueryRef\");\n } catch (e) {\n dump(\"caught exception from components\");\n return;\n }\n}", "function test_crosshair_op_azone_ec2() {}", "function testURLinFeed(feed, nr) {\n it('the feed at position '+nr+' has a non-empty URL', function() {\n var url = feed.url;\n expect(url).toBeDefined();\n expect(url.length).not.toBe(0);\n });\n }", "function test_Names (name) {\n it('should be defined', function() {\n expect(name).toBeDefined();\n expect(name).not.toBeNull();\n expect(name).not.toBe('');\n });\n }", "safeAsserts(verification, actual, friendlyText, expected) {\n switch (verification) {\n\n case 'equal':\n expect(expected, friendlyText).to.equal(actual);\n break;\n case 'contains':\n expect(actual, friendlyText).to.contains(expected);\n break;\n case 'true':\n expect(actual, friendlyText).to.be.true;\n break;\n case 'false':\n expect(actual, friendlyText).to.be.false;\n break;\n case 'deepEqual':\n expect(actual, friendlyText).to.deep.equal(expected);\n break;\n case 'notNull':\n expect(actual,friendlyText).to.not.be.null;\n break;\n }\n }", "myTestFunction1(str){\r\n return str;\r\n\r\n }", "function testFunction() {\n return 1;\n }", "function testAllTests() {\n testExtremal();\n testDifference();\n testSpearman();\n testSerial()\n}", "function tearDown() {\n}", "function setup() {\n /**\n * Expect the content of a file with an optional encoding.\n */\n expect.file = (filename, encoding) => {\n return expect(readFileSync(filename, encoding));\n };\n}", "function expectItemFunctions(item) {\n expect(item.getName).to.be.a(\"function\");\n expect(item.getNote).to.be.a(\"function\");\n expect(item.getId).to.be.a(\"function\");\n expect(item.getId()).to.be.a(\"string\");\n expect(item.getAncestors).to.be.a(\"function\");\n expect(item.getAncestors()).to.be.an(\"array\");\n expect(item.getChildren).to.be.a(\"function\");\n expect(item.getChildren()).to.be.an(\"array\");\n expect(item.getNumDescendants).to.be.a(\"function\");\n expect(item.getNumDescendants()).to.be.a(\"number\");\n expect(item.getUrl).to.be.a(\"function\");\n expect(item.getUrl()).to.be.a(\"string\");\n expect(item.isEmbedded).to.be.a(\"function\");\n expect(item.isEmbedded()).to.be.a(\"boolean\");\n }", "function AeUtil() {}", "function testSubstrings(callback)\n{\n\ttesting.assertEquals('hi.there.you'.substringUpTo('.'), 'hi', 'String.substringUpTo() not working!', callback);\n\ttesting.assertEquals('hi.there.you'.substringUpToLast('.'), 'hi.there', 'String.substringUpToLast() not working!', callback);\n\ttesting.assertEquals('hi.there.you'.substringFrom('.'), 'there.you', 'String.substringFrom() not working!', callback);\n\ttesting.assertEquals('hi.there.you'.substringFromLast('.'), 'you', 'String.substringFromLast() not working!', callback);\n\ttesting.success(callback);\n}", "function test_123_LessThan_423() {\n var result = comparer.compareStrings(\"123\", \"423\");\n fx.assert(result < 0);\n}", "function testStringLength(){\n\t\tvar StringUtils = LanguageModule.StringUtils;\n\t\tvar stringUtils = new StringUtils();\n\t\tvar length = stringUtils.length(\"hiccup\", 0);\n\t\texpect(length).to.eql(6);\n\t}", "function known_collection_nameSuite () {\n let cn = \"UnitTestsCollectionBasics\";\n return {\n setUp: function() {\n db._create(cn, { waitForSync: true});\n },\n\n tearDown: function() {\n db._drop(cn);\n },\n\n test_creating_a_new_document: function() {\n let cmd = `/_api/document?collection=${cn}`;\n let body = { \"Hallo\" : \"World\" };\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, 201, doc);\n assertEqual(doc.headers['content-type'], contentType);\n\n let etag = doc.headers['etag'];\n assertEqual(typeof etag, 'string');\n\n let location = doc.headers['location'];\n assertEqual(typeof location, 'string');\n\n let rev = doc.parsedBody['_rev'];\n assertEqual(typeof rev, 'string');\n\n let did = doc.parsedBody['_id'];\n assertEqual(typeof did, 'string');\n\n let match = didRegex.exec(did);\n\n assertEqual(match[1], cn);\n\n assertEqual(etag, `\\\"${rev}\\\"`);\n assertEqual(location, `/_db/_system/_api/document/${did}`);\n\n arango.DELETE_RAW(location);\n\n assertEqual(db[cn].count(), 0);\n },\n\n test_creating_a_new_document__setting_compatibility_header: function() {\n let cmd = `/_api/document?collection=${cn}`;\n let body = { \"Hallo\" : \"World\" };\n let doc = arango.POST_RAW(cmd, body);\n\n assertEqual(doc.code, 201, doc);\n assertEqual(doc.headers['content-type'], contentType);\n\n let etag = doc.headers['etag'];\n assertEqual(typeof etag, 'string');\n\n let location = doc.headers['location'];\n assertEqual(typeof location, 'string');\n\n let rev = doc.parsedBody['_rev'];\n assertEqual(typeof rev, 'string');\n\n let did = doc.parsedBody['_id'];\n assertEqual(typeof did, 'string');\n\n let match = didRegex.exec(did);\n\n assertEqual(match[1], cn);\n\n assertEqual(etag, `\\\"${rev}\\\"`);\n assertEqual(location, `/_db/_system/_api/document/${did}`);\n\n arango.DELETE_RAW(location);\n\n assertEqual(db[cn].count(), 0);\n },\n };\n}", "function test_utilization_utilization_graphs() {}", "function test(){\n cleanup();\n let fails = 0;\n function assert(condition, message){\n if (!condition){\n fails++;\n console.error(message);\n }\n }\n\n doBitcoinDe(';;;;;;;;;;;;;;\\n' +\n`\"2015-01-05 10:19:02\";Kauf;BTC;REF01;;239.88;\"BTC / EUR\";1.50000000;359.82;EUR;1.48500000;358.02;EUR;1.48500000;3.60140000\n\"2015-01-05 22:55:36\";Auszahlung;BTC;;;;;;;;;;;-0.60140000;3.00000000\n\"2015-01-06 11:23:03\";Kauf;BTC;REF02;;227.00;\"BTC / EUR\";0.50000000;113.50;EUR;0.49500000;112.93;EUR;0.49500000;3.49500000\n\"2015-01-07 23:56:01\";Verkauf;BTC;REF03;;244.59;\"BTC / EUR\";0.50000000;122.29;EUR;0.49500000;121.68;EUR;-0.50000000;2.99500000`);\n\n assert(_S.buys.length === 2, 'invalid number of buys: ' + _S.buys.length);\n assert(_S.sells.length === 1, 'invalid number of sells: ' + _S.sells.length);\n assert(Object.keys(_S.buys[0]).length === 9, 'invalid number of buy properties');\n assert(Object.keys(_S.sells[0]).length === 9, 'invalid number of sell properties');\n\n assert(_S.buys[0].date.getTime() === 1420449542000, _S.buys[0].date.getTime());\n assert(_S.buys[0].source === 'btcde', _S.buys[0].source);\n assert(_S.buys[0].index === 1, _S.buys[0].index);\n assert(_S.buys[0].ref === 'REF01', _S.buys[0].ref);\n assert(_S.buys[0].vol_btc === 1.5, _S.buys[0].vol_btc);\n assert(_S.buys[0].vol_eur === 359.82, _S.buys[0].vol_eur);\n assert(_S.buys[0].fee_eur === 1.8, _S.buys[0].fee_eur);\n assert(_S.buys[0].rate === 239.88, _S.buys[0].rate);\n assert(_S.buys[0].rest === 1, _S.buys[0].rest);\n\n assert(_S.sells[0].date.getTime() === 1420671361000, _S.sells[0].date.getTime());\n assert(_S.sells[0].source === 'btcde', _S.sells[0].source);\n assert(_S.sells[0].index === 4, _S.sells[0].index);\n assert(_S.sells[0].ref === 'REF03', _S.sells[0].ref);\n assert(_S.sells[0].vol_btc === 0.5, _S.sells[0].vol_btc);\n assert(_S.sells[0].vol_eur === 122.29, _S.sells[0].vol_eur);\n assert(_S.sells[0].fee_eur === 0.61, _S.sells[0].fee_eur);\n assert(_S.sells[0].rate === 244.59,_S.sells[0].rate);\n assert(_S.sells[0].rest === 1, _S.sells[0].rest);\n assert(_S.sells[0].index === 4, _S.sells[0].index);\n\n\n // simple fifo rest check\n cleanup();\n doBitcoinDe(`;;;;;;;;;;;;;;\n\"2015-01-01 01:00:00\";Kauf;\"BTC\";\"1\";;100;\"BTC / EUR\";0.5;50;EUR;0.5;50;0.5;0;\n\"2015-01-02 02:00:00\";Kauf;\"BTC\";\"2\";;200;\"BTC / EUR\";0.5;100;EUR;0.5;100;0.5;0;\n\"2015-01-03 03:00:00\";Verkauf;\"BTC\";\"3\";;300;\"BTC / EUR\";0.7;210;EUR;0.7;210;-0.7;0;`);\n doMath();\n assert(_S.buys[0].rest === 0, 'fifo should sell first first');\n assert(_S.buys[1].rest.r4() === 0.6, 'wrong fraction remaining');\n assert(_S.sells[0].rest === 0, 'did no sell all');\n\n assert(_S.years['2015'].invest === 150, 'wrong invested euro:'+_S.years['2015'].invest);\n assert(_S.years['2015'].liquidated === 210, 'wrong liquidated euro:'+_S.years['2015'].liquidated);\n assert(_S.years['2015'].bought_for === 90, 'wrong bought for:'+_S.years['2015'].bought_for);\n assert(_S.years['2015'].profit === 120, 'wrong profit:'+_S.years['2015'].profit);\n\n assert(_S.stake[2].btc.r4() === 0.3, 'wrong remaining btc stake');\n assert(_S.stake[2].avg_eur.r4() === -200, 'wrong avg_eur stake');\n\n // simple lifo rest check and wrong order\n cleanup();\n _S.fifo = false;\n doBitcoinDe(`;;;;;;;;;;;;;;\n\"2015-01-03 03:00:00\";Verkauf;\"BTC\";\"3\";;300;\"BTC / EUR\";0.7;210;EUR;0.7;210;-0.7;0;\n\"2015-01-02 02:00:00\";Kauf;\"BTC\";\"2\";;200;\"BTC / EUR\";0.5;100;EUR;0.5;100;0.5;0;\n\"2015-01-01 01:00:00\";Kauf;\"BTC\";\"1\";;100;\"BTC / EUR\";0.5;50;EUR;0.5;50;0.5;0;`);\n doMath();\n assert(_S.buys[0].rest.r4() === 0.6, 'wrong fraction remaining');\n assert(_S.buys[1].rest === 0, 'lifo should sell last first');\n assert(_S.sells[0].rest === 0, 'did no sell all');\n\n assert(_S.years['2015'].invest === 150, 'wrong invested euro');\n assert(_S.years['2015'].liquidated === 210, 'wrong liquidated euro');\n assert(_S.years['2015'].bought_for === 120, 'wrong bought for');\n assert(_S.years['2015'].profit === 90, 'wrong profit');\n\n assert(_S.stake[2].btc.r4() === 0.3, 'wrong remaining btc stake');\n assert(_S.stake[2].avg_eur.r4() === -200, 'wrong avg_eur stake');\n\n // test sell more than bought fails\n cleanup();\n doBitcoinDe(`;;;;;;;;;;;;;;\n\"2015-01-01 01:00:00\";Kauf;\"BTC\";\"1\";;100;\"BTC / EUR\";0.5;50;EUR;0.5;50;0.5;0;\n\"2015-01-02 02:00:00\";Kauf;\"BTC\";\"2\";;200;\"BTC / EUR\";0.5;100;EUR;0.5;100; 0.5;0;\n\"2015-01-03 03:00:00\";Verkauf;\"BTC\";\"3\";;300;\"BTC / EUR\";1.5;450;EUR;1.5;450;-1.5;0;`);\n try {\n doMath();\n } catch (e) {\n assert(e.indexOf('nothing to sell') >= 0);\n }\n\n // test with sell rate of 0 (donation)\n cleanup();\n doBitcoinDe(`;;;;;;;;;;;;;;\n\"2015-01-01 01:00:00\";Kauf;\"BTC\";\"1\";;100;\"BTC / EUR\";0.5;50;EUR;0.5;50 ; 0.5;0;\n\"2015-01-02 02:00:00\";Kauf;\"BTC\";\"2\";;200;\"BTC / EUR\";0.5;100;EUR;0.5;100; 0.5;0;\n\"2015-01-03 03:00:00\";Verkauf;\"BTC\";\"3\";;0;\"BTC / EUR\";0.7;0;EUR;0.7;0;-0.7;0;`);\n doMath();\n assert(_S.sells[0].profit_eur === -90);\n assert(_S.stake[2].btc.r4() === 0.3);\n assert(_S.years['2015'].profit === -90);\n assert(_S.years['all'].profit === -90);\n\n // TODO: trace profits and taxable profits separately\n // TODO: check avg_eur per btc maybe calculated incorrectly\n // TODO: test for fee calculation\n // TODO: moar tests\n // replace $.each with proper looping when not gui related\n\n if (fails > 0) alert('There were unit tests failures, check console!');\n else console.log('Unit tests passed.');\n}", "function createTest() {\n function Test(props: UseTreeInput) {\n Test.result(useTopicTree(props));\n return null;\n }\n Test.result = jest.fn();\n return Test;\n }", "expectContents(src, expected) {\n const exp = new Uint8Array(expected.buffer, expected.byteOffset, expected.byteLength);\n const dst = this.createCopyForMapRead(src, expected.buffer.byteLength);\n this.eventualAsyncExpectation(async niceStack => {\n const actual = new Uint8Array((await dst.mapReadAsync()));\n const check = this.checkBuffer(actual, exp);\n\n if (check !== undefined) {\n niceStack.message = check;\n this.rec.fail(niceStack);\n }\n\n dst.destroy();\n });\n }" ]
[ "0.62763774", "0.6242734", "0.6218219", "0.57459897", "0.57459897", "0.56912947", "0.56694794", "0.5645008", "0.56223613", "0.5574177", "0.55618995", "0.5545621", "0.5538197", "0.5513998", "0.5489837", "0.5464236", "0.54594535", "0.54523635", "0.544861", "0.5445681", "0.5440456", "0.54360926", "0.5414834", "0.54056805", "0.5400747", "0.53970915", "0.5389496", "0.5383285", "0.5375068", "0.53582585", "0.5357765", "0.53325635", "0.5329522", "0.53270835", "0.5300966", "0.5293975", "0.5291976", "0.52857494", "0.52771837", "0.52624154", "0.52601445", "0.5258384", "0.5239614", "0.5221367", "0.52191347", "0.5212472", "0.52093816", "0.5198011", "0.51954174", "0.51928014", "0.51879185", "0.51873493", "0.5182611", "0.5181608", "0.5180564", "0.5177715", "0.51753235", "0.51707345", "0.51699847", "0.5168255", "0.5166322", "0.51656103", "0.51574045", "0.51512897", "0.5150913", "0.51428056", "0.51428056", "0.51428056", "0.51417553", "0.5141716", "0.5136704", "0.5135639", "0.51355433", "0.5130844", "0.5125921", "0.5121027", "0.5109759", "0.5109493", "0.51086754", "0.51027524", "0.5096837", "0.50956875", "0.50944626", "0.5091868", "0.5090985", "0.50895846", "0.50895053", "0.50889146", "0.50875443", "0.50847113", "0.50843096", "0.5082747", "0.5080765", "0.5078563", "0.50767255", "0.5076519", "0.5072708", "0.507243", "0.50716996", "0.50698805", "0.50624347" ]
0.0
-1
nothing in the textbox
function clearScreen() { document.calculator.resultbox.value=""; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function emptyBoxes(){\n inputBox.val(\"\")\n }", "function form_raz(txt, initial_value) {\n\n if(txt.value == initial_value) txt.value = '';\n \n }", "function textboxhastext(id){\n\treturn !(id.length === 0 || !id.trim());\n}", "function clairtxtBoxAmAut(){\n document.getElementById(\"txtedNomAuteur\").value = \"\";\n document.getElementById(\"txtedPreAuteur\").value = \"\";\n}", "function clearBox(){\r\n\t\tthis.value = \"\";\r\n\t}", "function clearText() {\n var inputText = document.getElementById(\"inputText\");\n inputText.value = null;\n }", "function clairtxtBoxAmEdi(){\n document.getElementById(\"txtedNomEditeur\").value = \"\";\n // document.getElementById(\"cboxedPays\").value = 0;\n document.getElementById(\"cboxedVill\").value = 0;\n} // end clairtxtBoxAmEdi()", "function clrInput(){\n $(\"#txtbx\").val(\"\");\n}", "function myFunction(){\r\n\t\tif (document.getElementById('textview').value === 'undefined') {\r\n\t\t\tdocument.getElementById('textview').value = 0;\r\n\t\t}\r\n\r\n\t\tif (document.getElementById('textview').value === 'Infinity') {\r\n\t\t\tdocument.getElementById('textview').value = 'fuck you';\r\n\t\t}\r\n\t\tif (document.getElementById('textview').value === '') {\r\n\t\t\tdocument.getElementById('textview').value = 0;\r\n\t\t}\r\n\t\t//document.getElementById('textview').value = \"\"\r\n\t\t\r\n\t\t\r\n\r\n\r\n\r\n}", "function clearText(thefield)\t{\r\n\tif (thefield.defaultValue == thefield.value)\r\n\t\tthefield.value = \"\";\r\n\t}", "function ClearTextboxValues(txt) {\r\n txt.value = '';\r\n}", "function clairtxtBoxAmVil(){\n document.getElementById(\"txtedaddVille\").value = \"\";\n // document.getElementById(\"cboxedPays\").value = 0;\n} // end clairtxtBoxAmVil()", "function inputTextField(e , message){\n if ($(e.currentTarget).val() === ''){\n $(e.currentTarget).val(message);\n $(e.currentTarget).css(\"color\" , \"#999999\");\n }\n}", "function clean(num){\r\n\t//var x = document.getElementById('textview');\r\n\tdocument.getElementById('textview').value = \"\"\r\n}", "function clean() {\r\n document.form.textview.value = \"\";\r\n}", "function inputGotFocus() {\r\n\tthis.value = '';\r\n\tsetSearchButtonEnabled(false);\r\n}", "function inputText(inputEl, msg = \"\") {\n inputEl.value = \"\";\n inputEl.placeholder = msg;\n inputEl.focus();\n}", "function clearText () {\n\tdocument.getElementById('userName').placeholder = \"\";\n}", "function clearText(e){\n\t$.originalText.value= \"\";\n\t$.originalText.focus();\n\t$.encryptedText.text = \"\";\n\t$.label2.enabled = false;\n\t$.encryptedText.enabled = false;\n}", "function limpia(campo){\n\t\tcampo.value=\"\";\n\t\tcampo.focus();\n\t}", "function clr()\r\n{\r\ndocument.getElementById(\"box\").value = \"\";\r\n}", "function clearText() {\n let textBox = document.getElementById('textbox');\n textBox.value = \"\"\n }", "clear() {\n this.value = \"\";\n }", "function cleartextbox(){\n $(\"#final_span\").val('');\n // $('#MessageBox').val('');\n}", "function clearText(thefield) {\r\n if (thefield.defaultValue==thefield.value) { thefield.value = \"\" }\r\n}", "function del(){\n document.getElementById(\"text-box\").value = \"\";\n }", "textEnter() {}", "function clearText(theField)\n{\nif (theField.defaultValue == theField.value)\ntheField.value = '';\n}", "textChange() {\n core.dxp.log.debug('Inside textChange');\n this.assignPlaceholderText();\n }", "function tes() {\r\n if (document.getElementById('text-field-hero-input').value == '') {\r\n alert('Lengkapi Data');\r\n return false; // stop submission until textbox is not ''\r\n }\r\n}", "function clairtxtBoxLan(){\n document.getElementById(\"txtlanId\").value = \"\";\n document.getElementById(\"txtlanLangue\").value = \"\";\n} // clairtxtBoxLan()", "function tarea() {\n var boxTextoValue = getInputValue();\n if (boxTextoValue !== \"\") {\n doTarea(boxTextoValue);\n clean();\n }\n}", "function clairtxtBoxPlusEditeur(){\n document.getElementById(\"txtedNomAuteur\").value=\"\";\n document.getElementById(\"txtedPreAuteur\").value=\"\";\n document.getElementById(\"txtedNomEditeur\").value=\"\";\n // document.getElementById(\"cboxedPays\").value=0;\n document.getElementById(\"cboxedVill\").value=0;\n document.getElementById(\"txtedaddClas\").value=\"\";\n document.getElementById(\"txtedaddFami\").value=\"\";\n}// end clairtxtBoxPlusEditeur()", "function clearTextValue(){\n\t\t$(\"#\" + g.k).val(\"\");\n\t\t$(\"#clearbtn\").hide();\n\t}", "function clr() {\n document.getElementById(\"userInput\").value = \" \";\n}", "function setKeywordTextbox(textBox) {\n if (textBox != null) {\n if (textBox.value == \"Enter keyword(s)\") {\n textBox.value = \"\";\n textBox.className = \"\";\n }\n else if (textBox.value == \"\") {\n textBox.value = \"Enter keyword(s)\";\n textBox.className = \"disabled\";\n }\n }\n}", "function clr()\n{\ndocument.getElementById(\"ans\").value=\"\";\n}", "function clr() {\n document.getElementById(\"inp\").value = \"\"\n}", "function taskTextInput(){\n\t// If error was displayed and user is focusing/clicking on textfield input to take corrective action\n\tif (document.getElementById(\"errorMsgCont\").innerText !== \"\"){\n\t\tdocument.getElementById(\"errorMsgCont\").innerText = \"\";\n\t\tdocument.getElementById(\"taskTitle\").value = \"\";\n\t}\n}", "clear () {\n this.setValue('');\n }", "function compruebaTexto() {\n\tvar elemento = document.getElementById(\"texto_area\");\n\tvar span_texto = document.getElementById(\"texto_span\");\n\t\n\tif(elemento.value.length == 0 ) {\n\tspan_texto.style.color=\"red\";\n\tspan_texto.innerHTML = \" Debe escribir una pequeña descripción personal\";\n\ttexto=false;\n\t}\n\t\n\telse {\n\tspan_texto.innerHTML = \"\";\n\ttexto=true;\n\t}\t\n}", "function makingInputEmpty(input){\n input.value = \"\";\n}", "function clear(cityInputText){\n cityInputText.value = \"\"; \n }", "function clairtxtBoxUti(){\n //document.getElementById(\"txtutiId\").readOnly = true;\n //document.getElementById(\"txtutiNom\").readOnly = true;\n document.getElementById(\"txtutiId\").value = \"\";\n document.getElementById(\"txtutiNom\").value = \"\";\n document.getElementById(\"txtutiPrenom\").value = \"\";\n document.getElementById(\"txtutiMotdepass\").value = \"\";\n document.getElementById(\"txtutiAdmin\").value = \"\";\n document.getElementById(\"txtutiInactif\").value = \"\";\n}", "function limparInput(){\n input.value = ' ';\n input.focus();\n \n}", "function clairtxtBoxAut(){\n document.getElementById(\"txtautId\").readOnly = true;\n document.getElementById(\"txtautId\").value = 0;\n document.getElementById(\"txtautNom\").value = \"\";\n document.getElementById(\"txtautPrenom\").value = \"\";\n}", "function zeroPlaceholder() {\n\t\"use strict\";\n\tmessageBox.style.color = \"black\";\n\tif (messageBox.value === messageBox.placeholder) {\n\t\tmessageBox.value = \"\";\n\t}\n}", "function resetText(){\n \t$(\"#id\").val(\"\");\n \t$(\"#tenDanhMuc\").val(\"\");\n }", "function clairtxtBoxCar(){\n document.getElementById(\"txtcarId\").readOnly = true;\n document.getElementById(\"txtcarId\").value = 0;\n document.getElementById(\"txtcarNom\").value = \"\";\n //document.getElementById(\"txtcarChemin\").value = \"\";\n}", "function limpiarCaja() {\n cajaTexto.value = \"\";\n cajaTexto.focus();\n}", "function emptyinput(input){\n input.value = '';\n}", "function clear() {\n $txt.val(\"\");\n $tbl.children(\"tbody\").find(\"tr\").show();\n }", "function clearText(element) {\n element.value = '';\n}", "function clearTextBox() {\n $('#Name').val(\"\");\n myKeyUp();\n}", "function render(){\n\t\t$element.find('input').val('')\n\t}", "function CleandFieldSearch(){\n\t$(\"#txtSearch\").val(\"\");\n}", "function CleandFieldSearchPContract(){\n\t$('#textSearchContractPeople').val(\"\");\n}", "function clearText(field){\n\n if (field.defaultValue == field.value) field.value = '';\n else if (field.value == '') field.value = field.defaultValue;\n\n}", "function maybeClearOptText() {\n\t\t/*jshint validthis:true */\n\t\tif ( this.value === frm_admin_js.new_option ) {\n\t\t\tthis.value = '';\n\t\t}\n\t}", "function clearTextBox() {\n $('#idTraining').val(\"\");\n $('#NameTraining').val(\"\");\n $('#DescrTraining').val(\"\");\n $('#NameUser').val(\"\");\n $('#Surname').val(\"\");\n $('#UserBirthdate').val(\"\");\n $('#btnUpdate').hide();\n $('#btnAdd').show();\n $('#NameTraining').css('border-color', 'lightgrey');\n $('#DescrTraining').css('border-color', 'lightgrey');\n}", "function clrTxt() {\n\n document.getElementById(\"latitude\").value = \"\";\n document.getElementById(\"longitude\").value = \"\";\n document.getElementById(\"latitude2\").value = \"\";\n document.getElementById(\"longitude2\").value = \"\"; \n\n}", "function clear() {\n toValue.value = '';\n}", "function zeroPlaceholder() {\n\tvar instrBox = document.getElementById(\"instructions\");\n\tinstrBox.style.color = \"black\";\n\tif (instrBox.value === instrBox.placeholder) {\n\t\tinstrBox.value = \"\";\n\t}\n}", "function clairtxtBoxTra(){\n document.getElementById(\"txttraId\").readOnly = true;\n document.getElementById(\"txttraId\").value = 0;\n document.getElementById(\"txttraControle\").value = \"\";\n document.getElementById(\"txttraModule\").value = \"\";\n document.getElementById(\"txttraFrancais\").value = \"\";\n document.getElementById(\"txttraAnglais\").value = \"\";\n}", "function clearTextField() {\r\n\r\n\t/* Set default to 0 */\r\n\t$(\"#cargo_id\").val(\"0\");\r\n\t$(\"#cargo_driver\").val(null);\r\n\t$(\"#cargo_vehicletype\").val(null);\r\n\t$(\"#truck_plate_number\").val(null);\r\n\t$(\"#cargo_company\").val(null);\r\n\r\n\t/* Clear error validation message */\r\n\t$(\"#error\").empty();\r\n\r\n}", "function clearInput()\n {\n input.val('');\n }", "function clearFields() {\n document.getElementById(\"text-field\").value = \"\";\n }", "function clearTextBox() {\n\n $('#txtid').val(\"\");\n\n $('#txtname').val(\"\"),\n $('#txtemail').val(\"\"),\n $('#txtpassword').val(\"\"),\n $('#txtphone').val(\"\"),\n $('#rdorole').val(\"\"),\n $('#rdoactivate').val(\"\"),\n\n $('#btnUpdate').hide();\n $('#btnAdd').show();\n\n}", "function clearBox(){\n output.innerHTML = \"\";\n zipCode.value = \"\"\n date.value = 7;\n }", "function setRuntypeNoInput(input){\n\tinput.css(\"background-color\",\"gray\");\n\tinput.attr('maxlength', \"0\");\n\tinput.css(\"border\",\"\");\n}", "function limpiar() {\n $('#txtSerie').val('');\n $('#txtNombre').val('');\n $('#txtSemestre').val('');\n $('#txtCarrera').val('');\n $('#txtHPracticas').val('');\n}", "function clearTextBox() {\n $('#txtUsuarioId').val(\"\");\n $('#txtNombre').val(\"\");\n $('#txtNombreUsuario').val(\"\"); \n $('#btnUpdate').hide();\n $('#btnAdd').show();\n $('#txtNombre').css('border-color', 'lightgrey');\n $('#txtNombreUsuario').css('border-color', 'lightgrey');\n $('#txtEstado').css('border-color', 'lightgrey'); \n}", "function retablir(txt, id_controle) {\r\n if(document.getElementById(id_controle).value==''){\r\n document.getElementById(id_controle).value=txt;\r\n \r\n }\r\n}", "function clearInput() {\n $(\".text\").val('').focusout();\n }", "function clearField(x) {\n\t x.value = '';\n\t}", "clearInputFieldValue() {\r\n /** HTMLInputElement : To make the element as HTMLInputElement and provides special properties and methods for manipulating the layout and presentation of input elements */\r\n const inputElement = this.getInputElement();\r\n if (inputElement) {\r\n inputElement.value = '';\r\n this.searchValue = '';\r\n this.showSearchBoxList = !this.showSearchBoxList;\r\n }\r\n }", "clearTitle() {\n this.inputValue = \"\";\n this.not_found = false;\n }", "function cleanTypingNumber() {\n document.getElementById(\"showingTypingNumber\").value = \"\";\n}", "function cleanData() {\r\n messenge.value = ''\r\n}", "function clearText() {\n $('#user-answer').val(\"\");\n }", "function clear(){\n\tdocument.getElementById('userInputBox').value = '';\n}", "function valideBlank(F) { \n if( vacio(F.campo.value) == false ) {\n alert(\"Introduzca un cadena de texto.\");\n return false;\n } else {\n alert(\"OK\");\n //cambiar la linea siguiente por return true para que ejecute la accion del formulario\n return false;\n } \n}", "function inputClear() {\n $(\"#input\").val('');\n }", "clearMessageBox() {\n App.elements.input.val('');\n }", "function maybeAddText() {\n if($(\"#m\").val().trim()=='') {\n $(\"#m\").val('Enter your message here...');\n $(\"#m\").addClass(\"italic\");\n disablepost();\n }\n}", "function clr() {\n document.getElementById(\"result\").value = \"\"\n}", "function clr() {\n document.getElementById(\"result\").value = \"\"\n}", "function clearTextBox() {\n\n /* Mengganti Judul Utility Modal */\n $(\"#modalTitle\").text(\"Formulir Penambahan Data Master BatchFile\");\n\n /* Mengosongkan Field Id */\n $(\"#id\").val(\"\");\n\n /* Mengosongkan Field Nama */\n $(\"#name\").val(\"\");\n\n /* Menghilangkan Tombol Update */\n $(\"#btnUpdate\").hide();\n\n /* Menghilangkan Tombol Delete */\n $(\"#btnDelete\").hide();\n\n /* Menampilkan Tombol Add */\n $(\"#btnAdd\").show();\n\n /* Mengaktifkan Semua Form Field Yang Ada Pada Utility Modal */\n enabledFormAllField();\n\n}", "function getfocus(text){\n if (!text.replace(/\\s/g, '').length && (text.length==0)) {\n $(\"md-autocomplete\").css(\"border\",\"1px solid blue\");\n $(\"#errorhandle\").css(\"visibility\", \"hidden\");\n $scope.mydisabled= true;\n }\n }", "function setText(ntext){\n document.getElementsByClassName(\"newText\")[0].value = ntext;\n var resdiv = document.getElementsByClassName(\"result\")[0];\n resdiv.innerHTML = \"\";\n resdiv.style.visibility = \"hidden\";\n }", "function clearText() {\n $('#userGuess').val('');\n }", "function highlightText(){\n\t\tevent.preventDefault();\n\t\t$('#city-type').val(\"\");\n\t}", "function startUp() {\nnumberValue.value = \" \";\n}", "function clairtxtBoxCla(){\n document.getElementById(\"txtclaId\").readOnly = true;\n document.getElementById(\"txtclaId\").value = 0;\n document.getElementById(\"txtclaClassement\").value = \"\";\n document.getElementById(\"chBclaLoop\").unchecked;\n} // clairtxtBoxCla()", "function resetFieldText(obj, inputClassName) {\n /// <summary>重設輸入框預設值</summary>\n /// <param name=\"obj\">對應物件</param>\n /// <param name=\"inputClassName\">CSS Class 樣式</param>\n\n if (obj.value == '') {\n obj.value = obj.defaultValue;\n obj.className = inputClassName;\n }\n}", "function emptyField(event){\n\t\tvar thisObj = $(this);\n\t\tvar currVal=thisObj.val();\n\t\t\n\t\tif (currVal == thisObj.data(\"defaultValue\")){\n\t\t\tthisObj.val(\"\");\n\t\t}\n\t}", "function maybeClearText() {\n if($(\"#m\").val()=='Enter your message here...') {\n $(\"#m\").val(\"\");\n $(\"#m\").removeClass(\"italic\");\n document.getElementById(\"post\").disabled=false;\n }\n}", "function checkInput() {\n if (inputText.value === \"\") {\n hideButton();\n } else {\n showButton();\n }\n }", "function defocusUsername() {\n\t\tvar selection = window.getSelection();\n\t\tdocument.activeElement.blur();\n\t\tthis.usernameText.contentEditable = false;\n\t\tselection.removeAllRanges();\n\t\tif(this.usernameText.textContent.length === 0) this.usernameText.textContent = username; // no username entered? revert back to what it was\n\t\tthis.usernameText.textContent = this.usernameText.textContent.trim(); // remove spaces on either side\n\t}", "onTextboxCreated() {\n if (this._textboxCreated) {\n this._textboxCreated.raise(this.textbox);\n }\n if (latte._isString(this.placeholder) && this.placeholder.length > 0) {\n this.textbox.placeholder = this.placeholder;\n }\n }", "function clearBMI() {\r\n document.getElementById('txt_bmiHeight').value = \"\";\r\n}" ]
[ "0.69003224", "0.68426996", "0.68396264", "0.68312436", "0.68013006", "0.67483205", "0.6722218", "0.67139494", "0.67133504", "0.6646603", "0.6634525", "0.6605064", "0.6583088", "0.6559398", "0.6557453", "0.6549761", "0.6548784", "0.65420127", "0.6540705", "0.6532717", "0.65170187", "0.6514233", "0.6499303", "0.64981306", "0.64817697", "0.6476022", "0.64601374", "0.6459139", "0.6451934", "0.6416631", "0.64005417", "0.6387137", "0.6384596", "0.6377259", "0.6375168", "0.6374362", "0.6342222", "0.6339872", "0.6316669", "0.63089126", "0.63069475", "0.63031226", "0.6302362", "0.62985945", "0.62908304", "0.628991", "0.6289661", "0.6285676", "0.62830377", "0.6282146", "0.6281235", "0.6273601", "0.62621176", "0.6254575", "0.62489444", "0.6243713", "0.6236908", "0.6224056", "0.6222727", "0.6215531", "0.620826", "0.62002444", "0.6200067", "0.61881644", "0.61875737", "0.6187544", "0.618344", "0.6182358", "0.6182303", "0.6176649", "0.6166664", "0.6164857", "0.6162427", "0.6160704", "0.61587286", "0.6146695", "0.6146449", "0.6140459", "0.6134116", "0.61325", "0.61267436", "0.61203176", "0.6120213", "0.6117192", "0.6115031", "0.6106871", "0.6106871", "0.6104749", "0.60972285", "0.60953724", "0.6094896", "0.60893506", "0.60858065", "0.6083286", "0.6078478", "0.6072825", "0.6072524", "0.6071327", "0.60682476", "0.606337", "0.6063027" ]
0.0
-1
calculate resule using eval()
function calculateResult() { try { //eval(string) will work for */+- (https://www.w3schools.com/jsref/jsref_eval.asp) var input = eval(document.calculator.resultbox.value); document.calculator.resultbox.value=input; } catch(err) { document.calculator.resultbox.value="Err"; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "Evaluate() {}", "function calculate() {\r\n\teval();\r\n\tstopAll();\r\n}", "function calculate(){}", "function evaluate(payload) {\n const { rule, mainData, dataKey } = payload;\n\n // string expressions of the rule evaluation.\n const conditions = {\n eq: \"==\",\n neq: \"!=\",\n gt: \">\",\n gte: \">=\",\n contains: \"==\",\n }\n\n // validation object to be returned.\n const validation = {\n field: rule.field,\n field_value: mainData[dataKey],\n condition: rule.condition,\n condition_value: rule.condition_value\n }\n\n // execution of the valid string expression.\n if (!eval(`mainData[dataKey] ${conditions[rule.condition]} rule.condition_value`)) {\n\n // returns error - error validation fields - object.\n return {\n error: {\n msg: `field ${rule.field} failed validation.`,\n data: {\n validation: {\n error: true,\n ...validation\n }\n }\n }\n }\n }\n\n // returns value - success validation fields - object.\n return {\n value: {\n message: `field ${rule.field} successfully validated.`,\n status: 'success',\n data: {\n error: false,\n ...validation\n }\n }\n }\n}", "function evaluation(expression) {\n var resultado = 0, s = s.match(/[+\\-]*(\\.\\d+|\\d+(\\.\\d+)?)/g) || [];\n\n while (s.length) {\n total += parseFloat(s.shift());\n }\n return resultado;\n}", "function calculate(){\r\n var output = document.getElementById(\"ans\").value;\r\n var sol = eval(output);\r\n document.getElementById(\"ans\").value = sol;\r\n}", "function calcular(){\n document.calculadora.visor.value = eval(document.calculadora.visor.value);\n}", "calculate(equation){\n console.log( typeof eval(equation))\n if(eval(equation)%1==0) return eval(equation);\n return eval(equation).toFixed(3);\n }", "function calculate() {\n console.log(evaluationString)\n try {\n evaluationString = eval(evaluationString)\n } catch (e) {\n document.getElementById(\"output\").value = \"error\";\n }\n display = evaluationString\n document.getElementById(\"output\").value = evaluationString\n}", "function solve(val)\n{\n let x= document.getElementById(\"cal\").value;\n let y=eval(x);\ndocument.getElementById(\"cal\").value=y;\n\n}", "function evaluation(expression) {\n\n return parseInt(eval(expression)); // No se como explicarlo, en javascript hay una funcion que se llama eval, esta funcion recibe un string y pues basicamente\n // hace todo el trabajo por ti y te devuelve el valor de la funcion aritmetica que introdujiste, no hay mucho mas que decir.\n // Mentira, eval te duvuelve un string, por eso que es que tengo que usar parseInt para cambiarlo de tipo string a tipo entero, \n // Esto funciona por que los resultados van a ser numero enteros de por si y al ser estos digitos parseInt entiende que son numeros en base 10\n // y puede hacer el cambio apropiado. \n}", "function Evaluation_calculate(eval, symbol){\r\n a=0,b=0;\r\n switch(symbol){\r\n case \"|\"://System.out.print(\"\\n\"+temp);\r\n eval.push(Math.sqrt(eval.pop()));\r\n break;\r\n case \"^\"://System.out.print(\"\\n\"+temp);\r\n b=parseFloat(eval.pop());\r\n a=parseFloat(eval.pop());\r\n eval.push(Math.pow(a, b));\r\n break;\r\n case \"*\"://System.out.print(\"\\n\"+temp);\r\n b=parseFloat(eval.pop());\r\n a=parseFloat(eval.pop());\r\n eval.push(a*b);\r\n break;\r\n case \"/\"://System.out.print(\"\\n\"+temp);\r\n b=parseFloat(eval.pop());\r\n a=parseFloat(eval.pop());\r\n eval.push(a/b);\r\n break;\r\n case \"+\"://System.out.print(\"\\n\"+temp);\r\n b=parseFloat(eval.pop());\r\n a=parseFloat(eval.pop());\r\n eval.push(a+b);\r\n break;\r\n case \"-\"://System.out.print(\"\\n\"+temp);\r\n b=parseFloat(eval.pop());\r\n a=parseFloat(eval.pop());\r\n eval.push(a-b);\r\n break;\r\n }\r\n return eval;\r\n}", "function evaluate(){\n\t\t// var express_arr = expression_string.split(\"\");\n\t\tif(jQuery.inArray( expression_string[expression_string.length -1], operation ) !== -1){\n\t\t\texpression_string = expression_string.slice(0,-1)\n\t\t}\n\t\ttry {\n\t\t\tvar result = eval(expression_string);\n\t\t\t$(\".history\").append(\"<p class='history_value' >\"+result+\"</p>\");\n\t\t\t$(\".history\").find('p').css('font-size', '14px');\n\t\t\t$(\".history\").find('p:last').css('font-size', '25px');\n\t\t}catch(err){\n\t\t\t$(\".error_display\").text(\"Malformed Expression\");\n\t\t}\n\t}", "function calcular(){\n\tvar result = eval(document.fo.valores.value);\n document.fo.valores.value = resultado;\n}", "function calc() {\n\tvar input = document.getElementById('calcArea').value\n\tdocument.getElementById('calcArea').value = eval(input)\n\t\n}", "function print(){\n var res=document.querySelector(\".result\").value;\nvar out=eval(res) // eval(\"45+67+4\") \ndocument.querySelector(\".result\").value=out\n}", "function calculate(text){\n var pattern=/\\d+|\\+|\\-|\\*|\\/|\\(|\\)/g;\n var tokens=text.match(pattern);\n try {\n\n var val = evaluate(tokens);\n if (tokens.length>0){\n throw \"ill-formed expression\";\n }\n return String(val);\n }\n catch (err){\n\n return err; // error message will be printed as the answer\n }\n \n}", "calculate(){\r\n \r\n switch(this.operator){//evaluate the operator \r\n case \"^\"://if the operator is ^, then use the power formula\r\n return Math.pow(this.num1,this.num2); \r\n case \"*\"://if the operator is *, multiple the two numbers\r\n return this.num1*this.num2;\r\n case \"/\"://if the operator is ^,divide the two numbers\r\n return this.num1/this.num2; \r\n case \"+\"://if the operator is ^, add the two numbers\r\n return this.num1+this.num2;\r\n case \"-\"://if the operator is ^, subtract the two numbers\r\n return this.num1-this.num2; \r\n default://else error\r\n return \"ERROR\" \r\n }\r\n }", "function calculator(str) {\n return eval(str);\n }", "function getTotal(){//basically, if we have a string of 8 + 8 - 5.2, getTotal will then evaluate it and return u a single number\n //we want to evaluate to that with getTotal similar to previous function i think\n //set totalString=inputs array and then join it together as a string\n totalString = inputs.join(\"\");\n //target our steps array and evaluate it and then return the total of it \n //to evaluate a string as a math operator, u r gonna use eval method to do that for u\n $(\"#steps\").html(eval(totalString));\n \n }", "function solve2(inputStr) {\n let arr = []\n let result = inputStr.split('\\n').forEach((str, index) => {\n let [reg, func, amount, ifCond, regCond, opCond, amCond] = str.split(' ')\n \n if(!registers[reg]) registers[reg] = 0\n if(!registers[regCond]) registers[regCond] = 0\n \n if (eval(`registers[regCond] ${opCond} ${amCond}`)) {\n let mixer = eval(`${func}(\"${reg}\", ${amount})`)\n arr.push(mixer)\n \n }\n \n })\n \n // Object.keys(registers).forEach(i => {\n // console.log(i, registers[i])\n // })\n \n return Math.max(...arr)\n}", "function calculate(expression) {\n let field = document.getElementById(\"res\");\n let operands = expression.split(selectedOper.charAt(0));\n let res = \"\";\n switch (selectedOper.charAt(0)) {\n case '+':\n res = `${parseInt(operands[0], 2) + parseInt(operands[1], 2)}`;\n field.innerHTML = `${parseInt(res, 10).toString(2)}`;\n break;\n case '-':\n res = `${parseInt(operands[0], 2) - parseInt(operands[1], 2)}`;\n field.innerHTML = `${parseInt(res, 10).toString(2)}`;\n break;\n case '*':\n res = `${parseInt(operands[0], 2) * parseInt(operands[1], 2)}`;\n field.innerHTML = `${parseInt(res, 10).toString(2)}`;\n break;\n case '/':\n if (parseInt(operands[1], 2) > 0) {\n res = `${parseInt(operands[0], 2) / parseInt(operands[1], 2)}`; \n } else {\n res = 0;\n }\n\n field.innerHTML = `${parseInt(res, 10).toString(2)}`; \n break;\n\n default:\n break;\n }\n}", "function Evaluate() {\n var formula = document.getElementById('FormulaDisplay').getElementsByTagName('span')[0].innerHTML;\n if (formula == \"Formula\") {\n return;\n }\n\n var status = document.getElementById('AlgoSwitchBtn').innerHTML;\n var ret = 0;\n if (status == \"eval()\") {\n ret = EvaluateWithInnerEval(formula);\n } else if (status == \"Shunt-Yard\") {\n ret = EvaluateWithShuntingYardAlgo(formula);\n } else {\n // Something happened\n console.log(\"Internal error: We do not have a calculating method called \", status.tostring, \".\");\n }\n\n if (ret != null) {\n document.getElementById('ResultDisplay').getElementsByTagName('span')[0].innerHTML = ret;\n } else {} // Something happened (already handled).\n}", "function calculate(rpn) {\n var v1, v2;\n var value = null;\n var values = [];\n for (var i = 0; i < rpn.length; i++) {\n value = rpn[i];\n switch (value) {\n case '+':\n v2 = values.pop();\n v1 = values.pop();\n values.push(v1 + v2);\n break;\n case '-':\n v2 = values.pop();\n v1 = values.pop();\n values.push(v1 - v2);\n break;\n case '*':\n v2 = values.pop();\n v1 = values.pop();\n values.push(v1 * v2);\n break;\n case '/':\n v2 = values.pop();\n v1 = values.pop();\n values.push(v1 / v2);\n break;\n default:\n values.push(parseFloat(value));\n }\n }\n return values[0];\n }", "function calc(){\n let y = document.getElementById(\"text-box\").value;\n let z = eval(y);\ndocument.getElementById(\"text-box\").value=z;\n}", "getResult() {\n return eval(this._operation.join(''));\n }", "function Eval() {\r\n}", "function calculate () {\r\n\tif (num1 == \"\" && num2 == \"\") {\r\n\t\tresult == \"0\";\r\n\t} \r\n\telse if (num1==0){result = num2}\r\n\telse if (num2==0){result = num1}\r\n\telse{\r\n\t\tresult = eval(num1 + operator + num2);\r\n\t\tif (isFinite(result) && !isNaN(result)){\r\n\t\t\tnum1 = String(result);\r\n\t\t\tdisplay.value = num1 = Math.round(num1*1000000000)/1000000000;\r\n\t\t} else {\r\n\t\t\tdisplay.value = \"ERROR\"\r\n\t\t}\r\n\t}\r\n\tnum2 = operator = \"\";\r\n\tconsole.log(\"num1 \" + num1);\r\n\tconsole.log(\"operator \"+ operator);\r\n\tconsole.log(\"num2 \" + num2);\r\n\tconsole.log(\"result \" + result);\r\n}", "function RuleEvaluator(Operator, OperandValuesArray) {\r\n try {\r\n let Engine_Operator = _operators[Operator];\r\n return Engine_Operator.apply(OperandValuesArray);\r\n } catch (error) {\r\n throw \"RuleEvaluator -> [Operator: \" + Operator + \", Operands: \" + OperandValuesArray + \"] \" + error;\r\n }\r\n}", "function evaluate(x,op,y){\n if(op == \"+\") return x+y;\n if(op == \"-\") return x-y;\n if(op == \"X\") return x*y;\n else return x/y;\n\n}", "function calcExpression(env, node) {\n switch (node.type) {\n case \"Literal\":\n return node.value;\n case \"Identifier\":\n return calcIdentifier(env, node.name);\n case \"UnaryExpression\":\n return calcUnaryExpression(env, node);\n case \"BinaryExpression\":\n return calcBinaryExpression(env, node);\n case \"MemberExpression\":\n return calcMemberExpression(env, node);\n case \"ArrayExpression\":\n return node.elements.map(node => calcExpression(env, node));\n break;\n case \"ConditionalExpression\":\n return calcConditionalExpression(env, node);\n case \"CallExpression\":\n return calcCallExpression(env, node);\n default:\n console.log(node);\n throw new Error(\"Unknown type \" + node.type);\n }\n}", "function evaluate(){\n number = math[operand](x,y)\n x = number\n display(number)\n number = 0\n operand = ''\n console.log('x', x)\n}", "function v6_rle_dec(a){\n v6_rle_dec=eval('('+v6_function_rle_dec+')')\n return v6_rle_dec(a)}", "function calculation(oper, v, field, rc) {\r\n\t\t\t\tvar ret;\r\n\t\t\t\tswitch (oper) {\r\n\t\t\t\t\tcase \"sum\" : \r\n\t\t\t\t\t\tret = parseFloat(v||0) + parseFloat((rc[field]||0));\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"count\" :\r\n\t\t\t\t\t\tif(v===\"\" || v == null) {\r\n\t\t\t\t\t\t\tv=0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(rc.hasOwnProperty(field)) {\r\n\t\t\t\t\t\t\tret = v+1;\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tret = 0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"min\" : \r\n\t\t\t\t\t\tif(v===\"\" || v == null) {\r\n\t\t\t\t\t\t\tret = parseFloat(rc[field]||0);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tret =Math.min(parseFloat(v),parseFloat(rc[field]||0));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"max\" : \r\n\t\t\t\t\t\tif(v===\"\" || v == null) {\r\n\t\t\t\t\t\t\tret = parseFloat(rc[field]||0);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tret = Math.max(parseFloat(v),parseFloat(rc[field]||0));\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\treturn ret;\r\n\t\t\t}", "function calc(a, log){\n if (udfp(log))log = function (){};\n log(\"Input\", \"$1\", a);\n a = prs(a, log);\n a = evl(a, log);\n log(\"Finish evl\", \"$1\", a);\n a = dsp(a);\n log(\"Finish dsp\", \"$1\", a);\n \n return a;\n }", "function evaluarReglasValidacion(){\n objReglasValidacion = eval(reglasValidacion);\n for(var i=0;i<objReglasValidacion.length;i++){\n var objTmp = Ext.decode(objReglasValidacion[i].CRTSE_CAMPO_EVALUACION)[0]; //[0].INPARAMETRO1);\n for (var key in objTmp) {\n objTmp[key] = eval(objTmp[key]);\n }\n objReglasValidacion[i].CRTSE_CAMPO_EVALUACION ='['+Ext.encode(objTmp)+']';\n }\n return(Ext.encode(objReglasValidacion));\n }", "function resolver(){\n var res = 0;\n switch(operacion){\n case \"+\":\n res += parseFloat(operandoa) + parseFloat(operandob);\n break;\n case \"-\":\n res += parseFloat(operandoa) - parseFloat(operandob);\n break;\n case \"*\":\n res += parseFloat(operandoa) * parseFloat(operandob);\n break;\n case \"/\":\n res += parseFloat(operandoa) / parseFloat(operandob);\n break;\n }\n limpiar();\n resultado.innerHTML += (Math.round(res * 100) / 100).toFixed(2);;\n }", "evaluate(expr) {\n const result = compile(this.get_('eval.env'), expr).flatMap((f) => f());\n if (fail.match(result)) throw result.get();\n else return result.get();\n }", "function computedRule(tmpOperator,textarea,calledFrom)\n{\n var rightExp = document.getElementById('RExp');\n var vParentform = document.getElementById(\"RuleForm\");\n var ContextName = vParentform.hContextNameForIR.value;\n \t\t\t\t\t\n\t\n\tpassComparisonParam = document.getElementById('comparisonOperator').value;\n\t\n\tvar rightExpText = \"\";\n\tfor (var i = 0; i < rightExp.length; i++){\n\t\trightExpText = rightExpText + document.getElementById(\"RExp\").options[i].text + \"\\n\";\n }\n //var url=\"../configuration/RuleDialogValidationUtil.jsp?mode=getExpressionIR&leftExp=\"+encodeURIComponent(ContextName)+\"&rightExp=\"+encodeURIComponent(rightExpText)+\"&compType=\"+passComparisonParam;\n //var vRes = emxUICore.getData(url);\n\tvar url=\"../configuration/RuleDialogValidationUtil.jsp?mode=getExpressionIR\";\n\tvar queryString = \"leftExp=\"+encodeURIComponent(ContextName)+\"&rightExp=\"+encodeURIComponent(rightExpText)+\"&compType=\"+passComparisonParam;\n\tvar vRes = emxUICore.getDataPost(url,queryString);\n var iIndex = vRes.indexOf(\"irExp=\");\n var iLastIndex = vRes.indexOf(\"#\");\n var irExp = vRes.substring(iIndex+\"irExp=\".length , iLastIndex );\n computeRule = irExp ;\n\tvar objDIV = document.getElementById(\"divRuleText\"); \n\tobjDIV.innerHTML = computeRule.toString();\n \t\n}", "function evaluate(indexStart, indexEnd, operators, operands) {\r\n\r\n for (var index = indexStart; index < indexEnd; index++) {\r\n\r\n var indexFirstOperand = index\r\n var indexNextOperand = index + 1\r\n var indexNextOperator = index\r\n\r\n if (operators[indexNextOperator] == null) {\r\n for (var indexNext = indexNextOperator + 1; indexNext < operators.length; indexNext++) {\r\n if (operators[indexNext] != null) {\r\n indexNextOperator = indexNext\r\n indexFirstOperand = indexNext\r\n indexNextOperand = indexNext + 1\r\n index = indexNext - 1\r\n break\r\n }\r\n }\r\n }\r\n\r\n if (operands[indexNextOperand] == null) {\r\n for (var indexNext = indexNextOperand + 1; indexNext < operands.length; indexNext++) {\r\n if (operands[indexNext] != null) {\r\n indexNextOperand = indexNext\r\n index = indexNext - 1\r\n break\r\n }\r\n }\r\n }\r\n\r\n // MULTIPLICATION \r\n if (operators[indexNextOperator] == '*') {\r\n result = operands[indexFirstOperand] * operands[indexNextOperand]\r\n\r\n operands[indexNextOperand] = result\r\n operands[indexFirstOperand] = null\r\n operators[indexNextOperator] = null\r\n finalResult = result\r\n result = 0\r\n\r\n console.log(operands)\r\n console.log(operators)\r\n }\r\n // DIVISION\r\n else if (operators[indexNextOperator] == '/') {\r\n result = operands[indexFirstOperand] / operands[indexNextOperand]\r\n\r\n operands[indexNextOperand] = result\r\n operands[indexFirstOperand] = null\r\n operators[indexNextOperator] = null\r\n finalResult = result\r\n result = 0\r\n\r\n console.log(operands)\r\n console.log(operators)\r\n }\r\n }\r\n\r\n // ADDITION and SUBSTRACTION\r\n for (var index = indexStart; index < indexEnd; index++) {\r\n\r\n var indexFirstOperand = index\r\n var indexNextOperand = index + 1\r\n var indexNextOperator = index\r\n\r\n if (operators[indexNextOperator] == null) {\r\n for (var indexNext = indexNextOperator + 1; indexNext < operators.length; indexNext++) {\r\n if (operators[indexNext] != null) {\r\n indexNextOperator = indexNext\r\n indexFirstOperand = indexNext\r\n indexNextOperand = indexNext + 1\r\n index = indexNext - 1\r\n break\r\n }\r\n }\r\n }\r\n\r\n if (operands[indexNextOperand] == null) {\r\n for (var indexNext = indexNextOperand + 1; indexNext < operands.length; indexNext++) {\r\n if (operands[indexNext] != null) {\r\n indexNextOperand = indexNext\r\n index = indexNext - 1\r\n break\r\n }\r\n }\r\n }\r\n\r\n // ADDITION \r\n if (operators[indexNextOperator] == '+') {\r\n result = operands[indexFirstOperand] + operands[indexNextOperand]\r\n\r\n operands[indexNextOperand] = result\r\n operands[indexFirstOperand] = null\r\n operators[indexNextOperator] = null\r\n finalResult = result\r\n result = 0\r\n\r\n console.log(operands)\r\n console.log(operators)\r\n }\r\n // SUBSTRACTION\r\n else if (operators[indexNextOperator] == '-') {\r\n result = operands[indexFirstOperand] - operands[indexNextOperand]\r\n\r\n operands[indexNextOperand] = result\r\n operands[indexFirstOperand] = null\r\n operators[indexNextOperator] = null\r\n finalResult = result\r\n result = 0\r\n\r\n console.log(operands)\r\n console.log(operators)\r\n }\r\n }\r\n return finalResult\r\n}", "function evaluate() {\n var operand = resultdiv.innerHTML.split(operator);\n resultdiv.innerHTML = Math.floor(eval(parseInt(operand[0],2)\n + operator + parseInt(operand[1],2)\n )).toString(2);\n operator = '';\n}", "function LogicEvaluator() {}", "function calculate()\n {\n if (operator == 1)\n {\n current_input = eval(memory) * eval(current_input);\n };\n if (operator == 2)\n {\n current_input = eval(memory) / eval(current_input);\n // If divide by 0 give an ERROR message\n var initial_value = current_input.toString();\n if (initial_value == \"Infinity\")\n {\n current_input = \"ERROR\"\n };\n };\n if (operator == 3)\n {\n current_input = eval(memory) + eval(current_input);\n };\n if (operator == 4)\n {\n current_input = eval(memory) - eval(current_input);\n };\n if (operator == 5)\n {\n current_input = Math.pow(eval(memory), eval(current_input));\n };\n operator = 0; //clear operator\n memory = \"0\"; //clear memory\n displayCurrentInput();\n }", "function calc(params) {\n return 22; \n}", "function cal(p,r){\n return p + r\n}", "function calculate(operation) {\r\n let result;\r\n try {\r\n result = eval(operation); \r\n } catch (error) {}\r\n\r\n if ( result === 0 || isFinite(result) && Boolean(result) ) {\r\n document.getElementById('display').value = result;\r\n } else {\r\n document.getElementById('display').value = 'Invalid operation';\r\n }\r\n\r\n}", "function evaluate (tokens) {\n if (tokens.length===0){\n throw \"missing operand\";\n }\n \n \n var value=read_operand(tokens);\n \n while (tokens.length>0) {\n var operator = tokens[0];\n if(operator==\")\"){\n return value;\n }\n tokens.shift();\n if (operator !=\"+\" && operator !=\"-\" && operator !=\"*\" && operator !=\"/\" ) \n {\n throw \"unrecognized operator\"; \n }\n if (tokens.length===0){\n throw \"missing operand\";\n }\n var temp = read_operand(tokens);\n if(operator==\"+\"){\n value=value+temp;\n }\n else if(operator==\"-\"){\n value=value-temp;\n }\n else if(operator==\"*\"){\n value=value*temp;\n }\n else if(operator==\"/\"){\n value=value/temp;\n }\n \n }\n return value;\n}", "function evaluateExpression() {\n\n try {\n var result = eval($('.equation').html());\n $('.result').text(result);\n } catch (e) {\n if (e instanceof SyntaxError) {\n //$('.result').text(\"Syntax Error\");\n }\n }\n\n }", "function evaluateRule()\n{\n\t$(\"#Info\").text(\"Evaluating (6 second trial delay)...\");\n\t// The codeeffects.extract() method returns rule's data\n\tpost(\"/EvaluateRule\", JSON.stringify({ Data: codeeffects.extract() }), ruleEvaluated);\n}", "function evalExpr( opRep, subTables ) {\n var opImpl = simpleOpImplMap[ opRep.operator ];\n var valArgs = opRep.valArgs.slice();\n var impFn = opImpl.apply( null, valArgs );\n var tres = impFn( subTables );\n return tres; \n }", "function evaluate(req, res) {\n let output2 = \" \";\n var options = {\n mode: 'text',\n args: [epochVal, reverseVal]\n };\n\n PythonShell.run('scripts/evaluateNeuralNetwork.py', options, function (err, results) {\n if (err) throw err;\n // results is an array consisting of messages collected during execution\n results.forEach(function (value) {\n console.log(value);\n output2 = output2 + value + \"\\n\";\n });\n res.write(output2);\n });\n}", "function F(x){\r\n\tvar funcion=document.getElementById('funcion').value; \r\n\r\n\r\n\r\n\t//REEMPLAZAR EQUIS\r\n\tvar equis = [];\r\n\tfor(var i = 0; i < funcion.length; i++) {\r\n\t\tif (funcion[i].toLowerCase() === \"x\") equis.push(i);\r\n\t}\r\n\r\n\tvar totalX = equis.length;\r\n\r\n\tfor(var i=0; i<totalX; i++){\r\n\t\tfuncion = funcion.replace('x', x)\r\n\t}\r\n\t\r\n\ttry {\r\n\t math.eval(funcion); \r\n\t} catch (e) {\r\n\t if (e instanceof SyntaxError) {\r\n\t alert(e.message);\r\n\t }\r\n\t}\r\n\r\n\tconsole.log(funcion);\r\n\t\r\n return math.eval(funcion);\r\n //6*Math.pow(x,3)-2*Math.pow(x,2)-x-1\r\n\r\n}", "compute() {\n let result;\n let lastnum = parseFloat(this.lastOperand);\n let currnum = parseFloat(this.currOperand);\n if (isNaN(lastnum) || isNaN(currnum)) {\n return;\n }\n switch (this.operator) {\n case \"+\":\n result = lastnum + currnum;\n break;\n case \"-\":\n result = lastnum - currnum;\n break;\n case \"*\":\n result = lastnum * currnum;\n break;\n case \"/\":\n result = lastnum / currnum;\n break;\n default:\n return;\n }\n this.currOperand = result;\n this.lastOperand = \"\";\n this.operator = undefined;\n }", "function evaluateFormula(formula) {\r\n // ( A1 + A2 )\r\n let formulaTokens = formula.split(\" \"); // split on the base of spacing (\" \") -> [(,A1,+,A2,)]\r\n for (let i = 0; i < formulaTokens.length; i++) {\r\n let ascii = formulaTokens[i].charCodeAt(0);\r\n // check ascii valid or not\r\n if (ascii >= 65 && ascii <= 90) {\r\n let { rid, cid } = getRIDCIDfromAddress(formulaTokens[i]); //find row id/col id\r\n let value = sheetDB[rid][cid].value; //get value from data base\r\n formulaTokens[i] = value; //put value on formula tokens -> basically A1 changing to 10\r\n }\r\n }\r\n // [(,10,+,20,)]\r\n let evaluatedFormula = formulaTokens.join(\" \");\r\n // ( 10 + 20 )\r\n // eval() -> evaluates the expression\r\n let solvingValue = eval(evaluatedFormula);\r\n return solvingValue;\r\n}", "calculate() {\n\treturn this.exercise.calculate(this.weight, this.distance, this.time);\n }", "function evalComplexOperator(el) {\n switch (el.value) {\n case \"LOG\":\n display = eval(\"Math.log(\" + lastDigitClicked + \")\")\n if(!isNaN(display)){\n evaluationString = eval(\"Math.log(\" + lastDigitClicked + \")\")\n }else{\n display = evaluationString =0;\n }\n lastDigitClicked = display\n break\n case \"SQRT\":\n display = eval(\"Math.sqrt(\" + lastDigitClicked + \")\")\n if(!isNaN(display)){\n evaluationString = eval(\"Math.sqrt(\" + lastDigitClicked + \")\")\n }else{\n display = evaluationString =0;\n }\n lastDigitClicked = display\n break\n case \"CUBRT\":\n display = eval(\"Math.cbrt(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.cbrt(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"TAN\":\n display = eval(\"Math.tan(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.tan(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"COS\":\n display = eval(\"Math.cos(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.cos(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"SIN\":\n display = eval(\"Math.sin(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.sin(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n default:\n return false\n }\n console.log(evaluationString)\n return true\n\n}", "function eval(str){\n return 1* (str+ '').split(/[^0-9.+-]/)[0]; \n}", "function func1(x,y) {\n funcion = document.equation.equat.value; \n return (eval(funcion));\n}", "function calculate() {\n if (operator == 1) { currentInput = eval(memory) * eval(currentInput); };\n if (operator == 2) { currentInput = eval(memory) / eval(currentInput); };\n if (operator == 3) { currentInput = eval(memory) + eval(currentInput); };\n if (operator == 4) { currentInput = eval(memory) - eval(currentInput); };\n\n operator = 0; //clear operator\n memory = \"0\"; //clear memory\n displayCurrentInput();\n}", "evaluate() {\n // If the last character in the\n // current display is a number\n // (For the case where an operator\n // was input last)\n if (this.state.display.match(/\\d$/)) {\n // Remove unnecessary operators\n let evaluate = this.state.display.replace(\n /[\\*\\-\\+\\/]+(?!\\-?\\d)/g,\n ''\n );\n // Evaluate answer\n let answer = eval(evaluate);\n // Update display to show answer\n // and formula to show the\n // evaluated equation\n this.setState({\n display: answer.toString(),\n formula: this.state.display + '=' + answer,\n });\n }\n }", "function solve() {\n let y = eval(document.getElementById(\"result\").value)\n document.getElementById(\"result\").value = y\n}", "function solve() {\n let x = document.getElementById(\"result\").value\n let y = eval(x)\n document.getElementById(\"result\").value = y\n}", "function solve() {\n let x = document.getElementById(\"result\").value\n let y = eval(x)\n document.getElementById(\"result\").value = y\n}", "function evaluateExpression(exp) {\n if (exp[0] !== \"=\") {\n return exp;\n }\n\n exp = exp.substring(1, exp.length);\n\n if (/^SUM/.test(exp)) {\n exp = expandSUM(exp);\n }\n\n exp = exp.replace(/[A-Z]+\\d+/g, getValueByCellName);\n\n return new Function(\"return \" + exp)();\n }", "function evalPair(num1, num2, op) {\nvar eval = 0;\nswitch(op) {\n case '+': \n eval = num1+num2;\n break;\n case '-':\n eval = num1-num2;\n break;\n case '*':\n eval = num1*num2;\n break;\n case '/':\n eval = num1/num2;\n break;\n }\n return eval;\n}", "function result(operator, num1, num2){\n var result = eval(num1 + operator + num2);\n $('#result').text(result);\n return result;\n\n}", "function evalData() {\n // convert selected values to numbers\n const readingScore = typeof PLACEMENT.reading == 'string' && PLACEMENT.reading.length > 0 ? PLACEMENT.reading : false;\n const listeningScore = typeof PLACEMENT.listen == 'string' && PLACEMENT.listen.length > 0 ? PLACEMENT.listen : false;\n let results = null;\n\n // if all values present\n if (readingScore && listeningScore) {\n //save scores\n PLACEMENT.readingScore = readingScore;\n PLACEMENT.listeningScore = listeningScore;\n //save results\n results = evaluateScores(readingScore, listeningScore);\n PLACEMENT.readingCourse = results.readingCourse;\n PLACEMENT.listeningCourse = results.listeningCourse;\n PLACEMENT.level = results.level;\n\n console.log('PLACEMENT Eval', PLACEMENT);\n } else {\n // need to display error to user\n console.error('missing scores');\n }\n displayRecos(results);\n //for testing purposes\n if(config.testingVersion) {\n displayLevels(results, readingScore, listeningScore);\n }\n\n\n }", "function ExpressionEval() {\n var binops = {\n '||': function (a, b) { return a || b; },\n '&&': function (a, b) { return a && b; },\n '|': function (a, b) { return a | b; },\n '^': function (a, b) { return a ^ b; },\n '&': function (a, b) { return a & b; },\n '==': function (a, b) { return a == b; }, // jshint ignore:line\n '!=': function (a, b) { return a != b; }, // jshint ignore:line\n '===': function (a, b) { return a === b; },\n '!==': function (a, b) { return a !== b; },\n '<': function (a, b) { return a < b; },\n '>': function (a, b) { return a > b; },\n '<=': function (a, b) { return a <= b; },\n '>=': function (a, b) { return a >= b; },\n '<<': function (a, b) { return a << b; },\n '>>': function (a, b) { return a >> b; },\n '>>>': function (a, b) { return a >>> b; },\n '+': function (a, b) { return a + b; },\n '-': function (a, b) { return a - b; },\n '*': function (a, b) { return a * b; },\n '/': function (a, b) { return a / b; },\n '%': function (a, b) { return a % b; }\n };\n var binopsCallback = null;\n\n var unops = {\n '-': function (a) { return -a; },\n '+': function (a) { return a; },\n '~': function (a) { return ~a; },\n '!': function (a) { return !a; },\n };\n var unopsCallback = null;\n\n function evaluateArray(list, context) {\n return list.map((v) => evaluate(v, context));\n }\n\n function evaluateMember(node, context) {\n const object = evaluate(node.object, context);\n if (node.computed) {\n return [object, object[evaluate(node.property, context)]];\n } else {\n return [object, object[node.property.name]];\n }\n }\n\n function evaluateBinop(op, left, right) {\n return binopsCallback ? binopsCallback(op, left, right) : binops[op](left, right);\n }\n\n function evaluateUnop(op, arg) {\n return unopsCallback ? unopsCallback(op, arg) : unops[op](arg);\n }\n\n function evaluate(node, context) {\n\n switch (node.type) {\n\n case 'ArrayExpression':\n return evaluateArray(node.elements, context);\n\n case 'BinaryExpression':\n return evaluateBinop(node.operator, evaluate(node.left, context), evaluate(node.right, context));\n\n case 'CallExpression':\n let caller, fn;\n if (node.callee.type === 'MemberExpression') {\n [caller, fn] = evaluateMember(node.callee, context);\n } else {\n fn = evaluate(node.callee, context);\n }\n if (typeof fn !== 'function') return undefined;\n return fn.apply(caller, evaluateArray(node.arguments, context));\n\n case 'ConditionalExpression':\n return evaluate(node.test, context)\n ? evaluate(node.consequent, context)\n : evaluate(node.alternate, context);\n\n case 'Identifier':\n return context[node.name];\n\n case 'Literal':\n return node.value;\n\n case 'LogicalExpression':\n return evaluateBinop(node.operator, evaluate(node.left, context), evaluate(node.right, context));\n\n case 'MemberExpression':\n return evaluateMember(node, context)[1];\n\n case 'ThisExpression':\n return context;\n\n case 'UnaryExpression':\n return evaluateUnop(node.operator, evaluate(node.argument, context));\n\n default:\n return undefined;\n }\n }\n\n function compile(expression) {\n return evaluate.bind(null, jsep(expression));\n }\n\n function setBinopsCallback(callback) {\n binopsCallback = callback;\n }\n\n function setUnopsCallback(callback) {\n unopsCallback = callback;\n }\n\n function addUnaryOp(op, fun) {\n unops[op] = fun;\n }\n\n function addBinaryOp(op, fun) {\n binops[op] = fun;\n }\n\n this.evaluate = evaluate;\n this.compile = compile;\n this.addUnaryOp = addUnaryOp;\n this.addBinaryOp = addBinaryOp;\n}", "evaluation() {\n if (!this.lockOperators(this.state.formula, this.state.currentValue)) {\n let expression = this.state.formula;\n if (endsWithOperator.test(expression)) {\n expression = expression.slice(0, -1);\n }\n expression = expression.replace(/x/g, \"*\").replace(/‑/g, \"-\");\n expression = expression.lastIndexOf('(') > expression.lastIndexOf(')') ?\n expression + ')' : expression;\n let answer = Math.round(10000000 * eval(expression)) / 10000000;\n this.setState({\n currentValue: answer.toString(),\n formula: expression.replace(/\\*/g, \"⋅\").replace(/-/g, \"‑\") + \"=\" + answer,\n previousValue: answer,\n currentSign: answer[0] == '-' ?\n 'neg' :\n 'pos',\n lastClicked: 'evaluated' });\n\n }\n }", "function calc(exp) { return \"calc(\" + exp + \")\"; }", "function calculateResult() {\n return function () {\n changeDivideMultiply();\n screenResult.innerHTML = eval(screenResult.innerHTML);\n };\n }", "function compute () {\n\t // set value\n\t util.forEach(expressions, function(exp, index) {\n\t var v = that.$exec(exp)\n\t if (!v[0]) caches[index] = v[1]\n\t })\n\t // get content\n\t var frags = []\n\t util.forEach(parts, function(item, index) {\n\t frags.push(item)\n\t if (index < expressions.length) {\n\t frags.push(caches[index])\n\t }\n\t })\n\t return Expression.unveil(frags.join(''))\n\t }", "function evaluate(tokens) {\r\n try {\r\n if(tokens.length<1) throw \"Missing operand.\";\r\n }\r\n catch(err) {\r\n return \"Error: \"+err;\r\n }\r\n var value = read_operand(tokens);\r\n\tif(isNaN(value)) return value;\r\n while (tokens.length>0) {\r\n var operator = tokens.shift();\r\n if (operator==\")\") {\r\n return value;\r\n }\r\n try {\r\n if(operator!='+' && operator!='-' && operator!='*' && operator!='/') throw \"Unrecognized operator.\";\r\n if(tokens.length<1) throw \"Missing operand.\";\r\n }\r\n catch(err) {\r\n return \"Error: \"+err;\r\n }\r\n var temp = read_operand(tokens);\r\n\t\ttry {\r\n\t\t\tif(operator=='+') {\r\n\t\t\t\tvalue = value+temp;\r\n\t\t\t} else if(operator=='-') {\r\n\t\t\t\tvalue = value-temp;\r\n\t\t\t} else if(operator=='*') {\r\n\t\t\t\tvalue = value*temp;\r\n\t\t\t} else if(operator=='/') {\r\n\t\t\t\tvalue = value/temp;\r\n\t\t\t}\r\n\t\t\tif(isNaN(value)) throw \"Number expected\";\r\n\t\t}\r\n\t\tcatch(err) {\r\n\t\t\treturn \"Error: \"+err;\r\n\t\t}\r\n }\r\n return value;\r\n}", "function execVars(node) {\n let left, right, expr, args;\n if (node.hasOwnProperty('Expression')) {\n return execVars(node.Expression);\n }\n\n if (node.hasOwnProperty('Number')) {\n if (node.Number.indexOf(\"f\") >= 0) {\n return node.Number;\n }\n return parseFloat(node.Number);\n // return parseFloat(node.Number);\n }\n\n if (node.hasOwnProperty('Binary')) {\n node = node.Binary;\n left = execVars(node.left);\n right = execVars(node.right);\n switch (node.operator) {\n case '>':\n return 1;\n case '+':\n return left + right;\n case '-':\n return left - right;\n case '*':\n return left * right;\n case '/':\n return left / right;\n default:\n throw new SyntaxError('Unknown operator ' + node.operator);\n }\n }\n if (node.hasOwnProperty('Unary')) {\n node = node.Unary;\n expr = execVars(node.expression);\n switch (node.operator) {\n case '+':\n return expr;\n case '-':\n return -expr;\n default:\n throw new SyntaxError('Unknown operator ' + node.operator);\n }\n }\n\n if (node.hasOwnProperty('Identifier')) {\n if (context.Constants.hasOwnProperty(node.Identifier)) {\n return context.Constants[node.Identifier];\n }\n if (context.Variables.hasOwnProperty(node.Identifier)) {\n ctxVarsCur.push(node.Identifier);\n return context.Variables[node.Identifier];\n }\n else { //it never execute this\n //console.log(\"context.datarules..\" + JSON.stringify(datarules[node.Identifier]));\n context.Variables[node.Identifier] = util.getRandomByRules(datarules[node.Identifier])\n // context.Variables[node.Identifier] = util.getFromShuffle(node.Identifier);\n //console.log(\"context.Variables..\" + JSON.stringify(context.Variables));\n return context.Variables[node.Identifier];\n\n }\n //throw new SyntaxError('Unknown identifier');\n }\n if (node.hasOwnProperty('Assignment')) {\n right = execVars(node.Assignment.value);\n context.Variables[node.Assignment.name.Identifier] = right;\n return right;\n }\n\n if (node.hasOwnProperty('FunctionCall')) {\n expr = node.FunctionCall;\n if (context.Functions.hasOwnProperty(expr.name)) {\n console.log('node FunctionCall:' + expr.name + \"args.length:\" + expr.args.length)\n args = [];\n for (let i = 0; i < expr.args.length; i += 1) {\n args.push(exec(expr.args[i]));\n }\n return context.Functions[expr.name].apply(null, args);\n }\n throw new SyntaxError('Unknown function ' + expr.name);\n }\n throw new SyntaxError('Unknown syntax node');\n }", "function add(a, b) {\n console.log(a,b);\n return eval(a + b);\n}", "function equation(s) {\n return eval(s);\n }", "function evalExp(arr) {\n //Base case: When arr is length 1, return the value it contains.\n if(arr.length === 1){\n return Number.parseFloat(arr.pop());\n }\n //Calculate mult. and div. first.\n if (arr.includes('*') || arr.includes('/')){\n for (let i = 0; i < arr.length; i++){\n //Replace '*' and number on either side with their product or\n //replace '/' and numbers on either side with their quotient.\n //Recursively pass new array.\n if(arr[i] === '*'){\n return evalExp(arr.slice(0, i-1).concat(arr[i-1]*arr[i+1]).concat(arr.slice(i+2, arr.length)));\n }\n else if (arr[i] === '/'){\n return evalExp(arr.slice(0, i-1).concat(arr[i-1]/arr[i+1]).concat(arr.slice(i+2, arr.length)));\n }\n }\n }\n //Next evaluate addition and subtraction in same manner as above.\n else if (arr.includes('+') || arr.includes('-')){\n for (let i = 0; i < arr.length; i++){\n if(arr[i] === '+'){\n return evalExp(arr.slice(0, i-1).concat(arr[i-1]+arr[i+1]).concat(arr.slice(i+2, arr.length)));\n }\n else if (arr[i] === '-'){\n return evalExp(arr.slice(0, i-1).concat(arr[i-1]-arr[i+1]).concat(arr.slice(i+2, arr.length)));\n }\n }\n\n }\n\n\n}", "function evaluate(expr) {\n var result = eval(expr).toString();\n if (result.indexOf('.') !== -1) {\n var idx = result.indexOf('.');\n result = result.slice(0, idx) + result.slice(idx, idx + 3);\n }\n return result;\n }", "function recalc(){\n var tot = 0;\n var myChildren = $('.hrs').children(\"input[name*='hr']\"); // get the values of hour field\n var names = $('.hrs').children(\"input[name*='name']\"); // get the values of resource name field\n // iterate through the array and check if hour is not a number, throw an error\n for ( var i=0; i<myChildren.length; i++){\n var tmp = ($(myChildren[i]).val().trim());\n // check only if the length of the field > 1\n if (tmp.length >= 1) {\n if(isNaN(tmp)){\n alert('Hours has to be a valid number');\n return;\n } else {\n var num = Math.floor($(myChildren[i]).val());\n tot = tot+num;\n }\n }\n }\n // iterate thru and check if resource name is alpha characters.\n for ( var i=0; i<names.length; i++){\n var tmp = ($(names[i]).val().trim());\n // check only if the length of the field > 1\n if (tmp.length >= 1) {\n var regexLetter = /[a-zA-z]/;\n if(!regexLetter.test(tmp)){\n alert('Name is invalid, please enter alphabets');\n return false;\n }\n }\n }\n // Array to hold rates of resources by type\n var rates = {\"D\":100, \"T\" :75 , \"B\": 85, \"A\":120};\n // select all the resources by the drop down box\n var res = $('.hrs').children('select');\n\n var dollar =0; var rate=0 ;\n // iterate through to populate the values on the preview pane dynamically and calculate the total amount and hours\n // Apply the appropriate hourly rate based on the resource type\n for ( var i=0; i<res.length; i++){\n var opt = ($(res[i]).val());\n var cnt = i+2;\n if(opt == 'D'){\n rate = rates['D']* Math.floor($(myChildren[i]).val());\n $('table tr:nth-child('+cnt+') td:nth-child(6)').html(rates['D']);\n } else if (opt == 'A'){\n rate = rates['A']* Math.floor($(myChildren[i]).val());\n $('table tr:nth-child('+cnt+') td:nth-child(6)').html(rates['A']);\n } else if (opt == 'B'){\n rate = rates['B']* Math.floor($(myChildren[i]).val());\n $('table tr:nth-child('+cnt+') td:nth-child(6)').html(rates['B']);\n } else if (opt == 'T'){\n rate = rates['T']* Math.floor($(myChildren[i]).val());\n $('table tr:nth-child('+cnt+') td:nth-child(6)').html(rates['T']);\n } else if(opt == ''){\n rate = 0;\n $('table tr:nth-child('+cnt+') td:nth-child(6)').html('');\n }\n $('table tr:nth-child('+cnt+') td:nth-child(5)').html($(myChildren[i]).val());\n $('table tr:nth-child('+cnt+') td:nth-child(7)').html($(names[i]).val());\n //if drop down box value is empty, then set the text value to blank for the display purposes on the preview\n var resDesc = $(res[i]).find(\"option:selected\").text();\n if(rate == 0){\n resDesc = '';\n }\n $('table tr:nth-child('+cnt+') td:nth-child(4)').html(resDesc);\n dollar = dollar + rate; // calculate the dollar amount in a loop\n }\n // set the output divs for the preview\n $('#total-hours-output').html('Total Hours : '+ tot);\n $('#total-amount-output').html('Total Amount : '+dollar);\n\n }", "function ans(){\n if(calc.input.value !== \"\"){\n calc.input.value =eval( calc.input.value);\n} else {\n calc.input.value = \"0\";\n} \n end =false; \n}", "function resolver(){\r\n\t\tvar res = 0;//variable que me guarda los resultados\r\n\r\n\t\tswitch(operacion){\r\n\t\t\tcase \"+\":\r\n\t\t\tres = parseFloat(operandoA) + parseFloat(operandoB);\r\n\t\t\tbreak;\r\n\t\t\tcase \"-\":\r\n\t\t\tres = parseFloat(operandoA) - parseFloat(operandoB);\r\n\t\t\tbreak;\r\n\t\t\tcase \"*\":\r\n\t\t\tres = parseFloat(operandoA) * parseFloat(operandoB);\r\n\t\t\tbreak;\r\n\t\t\tcase \"/\":\r\n\t\t\tres = parseFloat(operandoA) / parseFloat(operandoB);\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\tresetear();//esta linea invoca la funcion de reiniciar la calculadora\r\n\t\tresultado.textContent = res.toString().substring(0,8);//esta linea realiza una conversion del resultado a texto para mostralo en pantalla hasta max 8 num.\r\n\t}", "function solveMath(req) {\n var operand1 = req.query.operand1;\n var operand2 = req.query.operand2;\n var operation = req.query.operation;\n\n if (operation == \"+\") {\n var result = +operand1 + +operand2;\n\n }\n if (operation == \"-\") {\n var result = +operand1 - +operand2;\n\n }\n if (operation == \"*\") {\n var result = +operand1 * +operand2;\n\n }\n if (operation == \"/\") {\n var result = +operand1 / +operand2;\n\n }\n console.log(operation);\n console.log(operand2);\n console.log(operand1);\n console.log(result);\n // res.render('/results', () => {\n // answer: result \n // })\n return result;\n}", "getResult() {\n try {\n return eval(this.operation.join(\"\"));\n } catch {\n this.setError();\n }\n }", "function exam(a)\n{\n\n//Assign fexm the final result from the math equation\nlet fexam = (60/100)*a\n\n//return value for fexam\nreturn fexam\n\n}", "evaluate(data, audience) {\n\n if(!this.expression || !this.expression.length) {\n return true;\n }\n\n function _resolveValue(v) {\n if(v.type === \"model\") {\n return data.getFieldValue(v.value);\n } else if(v.type === \"function\") {\n const arg = v.argument ? _resolveValue(v.argument) : undefined;\n return _resolveFunction(v.function, arg);\n } else if(v.type === \"enum\" || v.type === \"enum-set\") {\n return audience === 'client' ? v._clientValue : v._serverValue;\n }\n return v.value;\n }\n\n function _resolveFunction(fnName, v) {\n\n if(ConditionFunctions.hasOwnProperty(fnName)) {\n return ConditionFunctions[fnName](v);\n }\n return undefined;\n }\n\n function _reduceExpressionList(expressions) {\n\n return expressions.reduce((accumulator, e, index) => {\n\n if(index === 0) {\n return _evalExpression(e);\n }\n\n const r = _evalExpression(e);\n\n if(e.op === \"||\") {\n return accumulator || r;\n }\n\n return accumulator && r;\n\n }, true);\n }\n\n function _evalExpression(e) {\n\n if(!e) {\n return false;\n }\n\n if(e instanceof Array) {\n return _reduceExpressionList(e);\n }\n\n if(e.op === \"function\") {\n\n const arg = _resolveValue(e.argument);\n return _resolveFunction(e.function, arg);\n\n } else if(e.op === \"!=\" || e.op === \"==\" || e.op === \"in\" ||\n e.op === \">=\" || e.op === \"<=\" || e.op === \">\" || e.op === \"<\" ) {\n\n const lhs = _resolveValue(e.lhs);\n const rhs = _resolveValue(e.rhs);\n\n switch(e.op) {\n case \"!=\":\n return lhs !== rhs;\n case \"==\":\n return lhs === rhs;\n\n case \">=\":\n return lhs >= rhs;\n case \"<=\":\n return lhs <= rhs;\n case \">\":\n return lhs > rhs;\n case \"<\":\n return lhs < rhs;\n\n case \"in\":\n return (rhs instanceof Array ? rhs : [rhs]).indexOf(lhs) !== -1;\n }\n\n return false;\n }\n\n if(e.expression) {\n return _evalExpression(e.expression);\n }\n\n return false;\n }\n\n return _evalExpression(this.expression);\n }", "function equation(s) {\n return eval(s)\n}", "function cal(num1,num2,op){\n let y ;\n if(op == \"*\"){\n return duplicate(num1,num2);\n }\n else if(op == \"/\"){\n return division(num1,num2);\n }\n else if(op == \"-\"){\n y = num1.valueOf() - num2.valueOf(); \n return y.toString();\n }\n else if(op == \"+\"){\n num1 = parseFloat(num1);\n num2 = parseFloat(num2);\n y = num1+ num2;\n return y.toString();\n }\n\n }", "function calculate(operand1, operand2, operator) {\n if (operator == \"+\") {\n return operand1 + operand2;\n } else if (operator == \"-\") {\n return operand1 - operand2;\n } else if (operator == \"*\") {\n return operand1 * operand2;\n } else if (operator == \"/\") {\n return operand1 / operand2;\n }\n}", "function evaluate(currFormula) {\n let arr = currFormula.split(\" \");\n for (let i = 0; i < arr.length; i++) {\n let c = arr[i].charCodeAt(0);\n if (c >= 65 && c <= 90) {\n let { rid, cid } = getValueOfRC(arr[i]);\n arr[i] = sheetDB[rid][cid].value;\n }\n }\n\n let newFormula = arr.join(\" \");\n return eval(newFormula);\n}", "function calculate() {\n\n calculator.calculate();\n\n }", "function calculate(equality) {\n try {\n var content = splitInput(equality);\n rightContent(content);\n var cal = expression(content);\n if (String(cal) == \"NaN\") {\n alert(\"Error: Something is wrong.\");\n deleteContent();\n return;\n }\n }\n catch (err) {\n alert(\"Error: \" + err + \".\");\n deleteContent();\n return;\n }\n output.innerText = cal;\n}", "getResult(){\n try{\n return eval(this._operation.join(\"\"));\n }catch(e){\n setTimeout(()=>{\n this.setError();\n }, 1);\n \n }\n }", "function evaluate1(numArr, opArr) {\n const left = evalPair(parseFloat(numArr[0]),parseFloat(numArr[1]),opArr[0]);\n const right = evalPair(parseFloat(numArr[2]),parseFloat(numArr[3]),opArr[2]);\n \n return evalPair(left,right,opArr[1]);\n}", "function solvingRpn(exp) {\n const operator = {\n '+': b => a => a + b,\n '-': b => a => a - b,\n '*': b => a => a * b,\n '/': b => a => a / b,\n '#': a => -a\n }\n const queue = []\n \n exp.forEach(value => {\n if (isNumber(value)) {\n queue.push(parseFloat(value))\n } else {\n let result = operator[value]\n \n while (typeof result == 'function')\n result = result(queue.pop())\n\t \n queue.push(result)\n }\n })\n \n return queue[0]\n}", "function evaluate(operator) {\n let op2 = document.getElementById(\"lower\").value\n\n //Evaluating the expression \n let ch = expression.charAt((expression.length) - 1)\n if (ch == \"+\" || ch == \"-\" || ch == \"*\" || ch == \"/\") {\n //If user has clicked to evluate without the value of second operand,then add 0 automatically to complete it\n if (op2 == \"\") {\n op2 = 0\n }\n expression += op2;\n answer = calculate(parseInt(answer), parseInt(op2), operator)\n }\n\n //Updating the expression and displaying the result\n expressionSection.innerHTML = expression;\n inputSection.value = answer;\n}", "calculate($parsed) {\n const $calculator = new GeezCalculator($parsed);\n $calculator.calculate();\n\n return $calculator.getCalculated();\n }", "function evaluate(expr) {\n if (expr.constructor === Number) {\n // If this expression is just a number, return that number.\n return expr;\n } else {\n // If this is a binary operator expression, look up the function\n // that evaluates that operator and apply it to the operands.\n var operator_function = ops[expr[1]];\n var a = evaluate(expr[0]);\n var b = evaluate(expr[2]);\n return operator_function(a, b);\n }\n }", "function evaluate() {\n if (firstNum !== null && secondNum !== null) {\n switch (equation) {\n case \"add\":\n firstNum += secondNum;\n\n break;\n case \"subtract\":\n firstNum -= secondNum;\n\n break;\n case \"divide\":\n firstNum /= secondNum;\n\n break;\n case \"multiply\":\n firstNum *= secondNum;\n\n if (displayNum > 10000000) {\n setDisplayNum(\"8======D\");\n }\n break;\n default:\n break;\n }\n setDisplayNum(firstNum);\n }\n }", "function evaluate(criterios){\n for(let criterio of criterios){\n let modelo = criterio.notas.modelo\n let resultado = criterio.resultado\n \n /*\n #1\n modelo: {\n peso: 1,\n intervalo: {\n tipo: discreto,\n valor: [0, 5]\n }\n }\n resultado: 3\n \n #2\n modelo: {\n peso: 2,\n lista: [{\n texto: Danificada,\n valor: -1\n }, {...}, ...]\n }\n resultado: [0, 3]\n\n #3\n modelo: {\n peso: 2,\n boleano: {\n texto: Pets,\n valor: true/false\n }\n }\n resultado: true\n */\n \n let normal;\n if(modelo.intervalo){\n normal = (resultado - modelo.intervalo.valor[0])/(modelo.intervalo.valor[1] - modelo.intervalo.valor[0])\n }else if(modelo.booleano){\n normal = +(resultado == modelo.booleano.valor) * modelo.booleano.peso\n }else if(modelo.lista){\n let soma = modelo.lista.filter((v, i) => {\n return i in resultado\n }).reduce((acc, cur) => {\n return acc + cur.valor\n }, 0)\n let lista_ordenada = modelo.lista.sort((a, b) => a.valor - b.valor)\n let len_lista = modelo.lista.length\n \n let minimo = lista_ordenada[0].valor\n let maximo = lista_ordenada[len_lista-1].valor\n \n normal = (soma - minimo) / (maximo - minimo)\n }\n \n criterio.normal = normal\n criterio.normal_ponderada = normal * modelo.peso \n }\n \n let peso_total = criterios.reduce((acc, cur) => {\n return acc + cur.notas.peso\n }, 0)\n let nota_normal_ponderada_total = criterios.reduce((acc, cur) => acc + cur.normal_ponderada, 0)\n \n let nota_final = nota_normal_ponderada_total / peso_total\n \n return {\n final: nota_final,\n criterios: criterios.map(c => {\n return {\n resultado: c.resultado,\n normal: c.normal,\n peso: c.notas.peso,\n ponderada: c.ponderada\n }\n })\n }\n }", "async function updateEval() {\n const eval = await (await fetch( './getEvaluation', { method: 'POST'} )).json();\n fillElements( eval );\n }" ]
[ "0.66440064", "0.6313008", "0.6188879", "0.61792415", "0.6131308", "0.6063179", "0.60355437", "0.59934026", "0.5905516", "0.58724314", "0.58305293", "0.5818957", "0.58027273", "0.5801989", "0.57844806", "0.57700217", "0.5768657", "0.5754404", "0.572538", "0.5719303", "0.5716548", "0.56939745", "0.56906354", "0.56701726", "0.56478775", "0.56477714", "0.5623972", "0.55620885", "0.5556928", "0.55233735", "0.5514034", "0.54926914", "0.5485533", "0.54844826", "0.54702806", "0.5469546", "0.54510784", "0.54508823", "0.5444962", "0.5436185", "0.5427054", "0.5420149", "0.54197264", "0.5393336", "0.5392735", "0.5389593", "0.53858113", "0.53836155", "0.53795016", "0.5374524", "0.53732276", "0.53651804", "0.53610134", "0.53568476", "0.5351664", "0.5343853", "0.53421175", "0.53243935", "0.53149307", "0.531358", "0.5313541", "0.53088033", "0.53088033", "0.5301778", "0.5300885", "0.5275128", "0.52733976", "0.5264042", "0.5258736", "0.52570045", "0.52476454", "0.5244871", "0.52445143", "0.5236364", "0.52349734", "0.522818", "0.5228109", "0.5223493", "0.522173", "0.5217079", "0.5213474", "0.5208743", "0.5207072", "0.5204958", "0.52036273", "0.5201704", "0.52010655", "0.51960295", "0.51871663", "0.51847047", "0.517635", "0.51722157", "0.5171709", "0.51679075", "0.5164929", "0.5159105", "0.5152342", "0.5149959", "0.5146267", "0.51460284" ]
0.5662911
24
sqrt and ^2 will immediately display result once button is pressed
function doSqrt() { var input2 = document.calculator.resultbox.value; try { var result2 = Math.sqrt(input2); document.calculator.resultbox.value = result2; } catch (err) { document.calculator.resultbox.value="Err"; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function squareRoot()\n {\n current_input = Math.sqrt(current_input);\n displayCurrentInput();\n }", "function squareRoot() {\ncurrentInput = Math.sqrt(currentInput);\ndisplayCurrentInput();\n}", "function sqrt(){\n\tif (!this.classList.contains(\"disabled\")){\n\t\tevaluate();\n\t\tvar inputScreen = document.querySelector('.screen');\n\t\tvar value = inputScreen.innerHTML;\n\t\tinputScreen.innerHTML = Math.sqrt(value);\n\t\tstartNew = true;\n\t\tif (inputScreen.innerHTML.contains(\".\")){\n\t\t\tdecimalBool = false;\n\t\t\tfactorialBool = false;\n\t\t\tdocument.getElementById(\"deci\").classList.add(\"disabled\");\n\t\t\tdocument.getElementById(\"factorial\").classList.add(\"disabled\");\n\t\t}\n\t}\n}", "function squareRoot() {\n if (this.currentInput == -1) {\n this.currentInput = \"i\";\n }\n else if (this.currentInput < 0) {\n this.currentInput = Math.sqrt(this.currentInput * -1);\n this.currentInput = this.currentInput.toString() + \"i\";\n }\n else {\n this.currentInput = Math.sqrt(this.currentInput);\n }\n this.displayCurrentInput();\n}", "quadratic(){\nvar a=readlinesync.question(\"Enter the value of a:\");\nvar b=readlinesync.question(\"Enter the value of b:\");\nvar c=readlinesync.question(\"Enter the value of c:\");\nvar delta=Math.pow(b,2)-4*a*c;\nvar root1=(-b+Math.sqrt(delta)/(2*a*c));\nconsole.log(\"Root1 of x:\"+root1);\nvar root2=(-b-Math.sqrt(delta)/(2*a*c));\nconsole.log(\"Root2 of x:\"+root2);\n}", "function squareRoot() {\n if (current_input == -1) {\n current_input = \"i\";\n }\n else if (current_input < 0) {\n current_input = Math.sqrt(current_input * -1);\n current_input = current_input.toString() + \"i\";\n }\n else {\n current_input = Math.sqrt(current_input);\n }\n displayCurrentInput();\n}", "function sqrt() {\n document.getElementById(\"display\").innerHTML = \"&#8730;\" + document.getElementById(\"display1\").innerHTML;\n const x = Math.sqrt(parseFloat(document.getElementById(\"display1\").innerHTML));\n if (isNaN(x)) {\n console.error(\"Enter the number\");\n } else {\n console.log(x);\n document.getElementById(\"display1\").innerHTML = x.toFixed(3);;\n clipboard.push(\"= \" + document.getElementById(\"display1\").innerHTML + \"\\n\");\n }\n}", "function sqrt() {\n var cur = parseFloat(calcVals.cur);\n if (cur >= 0){\n calcVals.cur = Math.sqrt(cur).toString().substring(0, 11);\n calcVals.prevAttr = \"filler\";\n }\n}", "function mathFunctions() {\r\n var number = document.getElementById('number_input').value;\r\n var sqrt_result = Math.sqrt(number);\r\n if (!isNaN(sqrt_result)) {\r\n document.getElementById('sqrt_output').value = sqrt_result;\r\n }\r\n var round_result = Math.round(sqrt_result);\r\n if (!isNaN(round_result)) {\r\n document.getElementById('round_output').value = round_result;\r\n }\r\n var ceil_result = Math.ceil(sqrt_result);\r\n if (!isNaN(ceil_result)) {\r\n document.getElementById('ceil_output').value = ceil_result;\r\n }\r\n var floor_result = Math.floor(sqrt_result);\r\n if (!isNaN(floor_result)) {\r\n document.getElementById('floor_output').value = floor_result;\r\n }\r\n}", "function get1(n) {\n\t resultado = Math.sqrt(n);\n\tconsole.log(resultado) ;\n}", "function set2(n) {\n\tconsole.log(resultado = Math.sqrt(n))\n}", "function square()\n {\n current_input = current_input * current_input\n displayCurrentInput();\n }", "function sqrt(num1, num2) {\n var sqrtValue = 0;\n if (isNumber(num1)) {\n sqrtValue = returnNumberIntOrWithDecimal(Math.sqrt(num1));\n return `La raiz cuadrada de ${num1} es ${sqrtValue}`;\n } else if (isNumber(num2)) {\n sqrtValue = returnNumberIntOrWithDecimal(Math.sqrt(num2));\n return `La raiz cuadrada de ${num2} es ${sqrtValue}`;\n } else {\n return \"No has introducido ningún valor\";\n }\n}", "function advancedCalc() {\n var type = parseInt(prompt(\"please chose \\n\" + \"1 - Power\\n\" +\" 2- Square Root\\n\" ));\n if (type==1) {\n // call for 2 prompts\n var value_array = prompt_for_values(2);\n number_1 = value_array[0];\n number_2 = value_array[1];\n return alert(Math.pow(number_1, number_2));\n }else if (type==2) {\n //call for single prompt and return value used in the sqrt.\n return alert(Math.sqrt(prompt_for_values(1)));\n }\n}", "function Quadratic() {\n\n let calc = () => {\n\t\tconsole.log('huj');\n\t\tlet a = document.querySelector(\"#a\");\n\t\tlet b = document.querySelector(\"#b\");\n\t\tlet c = document.querySelector(\"#c\");\n\n\t\tlet D;\n\t\tlet x;\n\t\tlet x1;\n\t\tlet x2;\n\n\t\tD = (b.value**2) - (4*a.value*c.value);\n\t\tconsole.log(`D is ${D}`);\n\n\t\tif (D > 0) {\n\t\t\tx1 = (-b.value + Math.sqrt(D)) / (2*a.value);\n\t\t\tx2 = (-b.value - Math.sqrt(D)) / (2*a.value);\n\t\t\tconsole.log(`x1 = ${x1}, x2 = ${x2}`);\n\t\t} else if (D == 0) {\n\t\t\tx = -b.value / 2*a.value;\n\t\t\tconsole.log(`As D is 0, solution is ${x}`);\n\t\t} else {\n\t\t\tconsole.log(\"Equation has no solutions.\")\n\t\t}\n }\n \n return (\n <div className=\"App\">\n <div className=\"App\">\n\t\t\t<div>\n\t\t\t\t<div>\n\t\t\t\t\t<h2>You have next type expression: </h2>\n <h3>x&#178; + bx + c = 0</h3>\n\t\t\t\t</div>\n\t\t\t\t<p>Please enter needed numbers</p>\n\t\t\t\t<div>\n <input type=\"number\" style={{width: \"25px\"}} id=\"a\"></input>\n x&#178; + <input type=\"number\" style={{width: \"25px\"}} id=\"b\"></input>x + <input type=\"number\" style={{width: \"25px\"}} id=\"c\"></input> = 0\n </div>\n\t\t\t <div style={{marginTop: \"10px\"}}>\n\t\t\t <button onClick={calc}>Calculate</button>\n\t\t\t </div>\n\t\t\t</div>\n\t\t</div>\n </div>\n );\n}", "function squareroot(sqr)\r\n{\r\n document.write(\"Square root is \"+Math.sqrt(sqr))\r\n}", "function sqrt(number,root){\n root = root || 2;\n return pow(number,1/root);\n}", "function square() {\n current_input = current_input * current_input;\n displayCurrentInput();\n}", "function square() {\ncurrentInput = currentInput * currentInput;\ndisplayCurrentInput();\n\n}", "sqrt(value)\n { var t=value;\n \n while(Math.abs(t-value/t)>Number.EPSILON*t)//condition for the step by step process of acalculting the loop.\n {\n t=((value/t)+t)/2;\n }\n \n console.log(\"THe approx root of the value is: \"+t);\n }", "function calculateSquareArea() {\n var squareAreaInput = document.getElementById('squareAreaInput').value;\n var squareAreaAnswer = squareAreaInput ** 2;\n document.getElementById('squareAreaAnswer').innerHTML = squareAreaAnswer;\n}", "function clickedOn() {\n if (this.id === 'C' || this.id === '/' || this.id === 'X' || this.id === '-' || this.id === '+' || this.id === '=' || this.id === '.') {\n symPress(this.id);\n } else {\n numPress(this.id);\n }\n // If NaN (for example, from 0/0) clears the calc and displays a message)\n if (displayWindow.innerHTML === 'NaN') {\n clear();\n displayWindow.innerHTML = '-Undefined-';\n }\n // Debugging Logs:\n console.log(`Equation: ${num1} ${operand} ${num2}`);\n console.log(`Equal temp num: ${equalTemp}; eqPress: ${eqPress}`)\n console.log('---------------');\n}", "function doubleSquareRootOf(num) {\n // your code here\n}", "function calculate () {\n d = document.getElementById('input').value\n d = parseInt(d)\n r = d / 2\n document.getElementById('out3').innerHTML = r\n a = pi * r ** 2\n document.getElementById('out1').innerHTML = a\n c = 2 * pi * r\n document.getElementById('out2').innerHTML = c\n}", "function sqNum(num) {\n ​\n \n console.log(`The square root of ${num} is: ${num * 2}`)\n ​\n return num ** 2\n ​\n }", "function square() {\n this.currentInput = this.currentInput * this.currentInput;\n this.displayCurrentInput();\n}", "function squareroot(c) {\n // c = number;\n // var epsilon = 10-15;\n t = 0.0001;\n //c=((c/t)+t)/2;\n while (Math.abs(t*t - c) >= Math.pow(10,-15) )\n { \n t = ((c / t) + t) / 2;\n }\n console.log(`square Root of ${c} is ${t}`);\n return \"\";\n}", "function squareFeatures()\n{\n const squareSide = document.getElementById(\"main--form--output_01\");\n side = parseFloat(squareSide.value);\n sqResult_01 = side * 4;\n sqResult_02 = side ** 2;\n document.getElementById(\"main--form__divInteractivo__input01\").innerHTML = parseFloat(sqResult_01).toFixed(1);\n document.getElementById(\"main--form__divInteractivo__input02\").innerHTML = parseFloat(sqResult_02).toFixed(1);\n}", "function squareRoot(num){\n\n return (num**0.5)\n}", "distance() {\n\tvar x, y;\n\tvar x = readlinesync.question(\"Enter the first points:\");\n\tvar y = readlinesync.question(\"Enter the second points:\");\n\tvar x1 = Math.pow(x, 2);\n\tvar y1 = Math.pow(y, 2);\n\tvar distance = Math.sqrt(x1 + y1);\n\tconsole.log(\"Euclidean Distance is:\" + distance);\n}", "function doMath() {\n let n1 = Number( document.getElementById(\"number1\").value );\n let n2 = Number( document.getElementById(\"number2\").value );\n let total = n1 * n2;\n document.getElementById(\"calculator-output\").innerHTML = total;\n}", "function calculateSquare(value){\r\n return value**2\r\n}", "function sqrt(x) {\r\n var y;\r\n y = Math.sqrt(x);\r\n return y;\r\n}", "entfernungVomUrsprung(){\n let a = this.x;\n let b = this.y;\n let c;\n let py = (a*a) + (b*b);\n c= Math.sqrt(py);\n return c;\n }", "function square(x) {\n console.log(Math.sqrt(x));\n}", "function calculate() {\n secondNumber = resultDisplay.innerText;\n let result = calculateResult(firstNumber, secondNumber, operatorSymbol);\n changeDisplay(result);\n // This allows the user to keep calculating after a result\n firstNumber = result;\n}", "function equal(){\n\nsecondnumber =parseInt(document.getElementById('display').value);\n\nif (operation == \"+\")\n\n{\n\nresult = firstnumber + secondnumber;\n\n}\n\nelse if (operation == \"*\"){\n\nresult = firstnumber * secondnumber;\n\n}\n\nelse if (operation == \"-\"){\n\nresult = firstnumber - secondnumber;\n\n}\n\nelse if (operation == \"/\"){\n\nresult = firstnumber / secondnumber;\n\n}\n\n\n\n\n\ndocument.getElementById('display').value =\"\";\n\ndocument.getElementById('display').value = result.toString();\n\ndocument.getElementById('display').value = firstnumber + operation + secondnumber + \" = \" + result.toString(); // display value\n\n\n\nreturn;\n\n}", "function calc(){\n\nlet n1 = parseFloat(document.getElementById(\"n1\").value)\nlet n2 = parseFloat(document.getElementById(\"n2\").value)\n\n\nlet op = document.getElementById(\"opr\").value\n\nif(op === \"+\"){\n\ndocument.getElementById('result').value = n1+n2;\n\n}\nif(op === \"-\"){\n\ndocument.getElementById('result').value = n1-n2;\n\n}\nif(op === \"x\"){\n\ndocument.getElementById('result').value = n1*n2;\n\n}\nif(op === \"/\"){\n\ndocument.getElementById('result').value = n1/n2;\n\n}\n\nreturn;\n}", "function equalTest(){//if =sign was clicked, all screen will clean before you start a new calculation\n\tif (equaled == 1){\n\t\tconstantCe();//screen cleaning function\n\t\tequaled = 0;\n\t\tdot = 0;\n\t}\n}", "function sqrt(num) {\n if (num < 2) return 0\n return sqrtRecur(num, 0, num)\n}", "function squareRoot(number) {\n let squareRoot = number * number;\n console.log(squareRoot);\n}", "function equalClicked(){\n\tsecondMemory = Number($display.val());\n\tif(operator === \"+\"){\n\t\tfirstMemory = add(firstMemory, secondMemory);\n\t} else if(operator === \"-\"){\n\t\tfirstMemory = substract(firstMemory, secondMemory);\n\t} else if(operator === \"×\"){\n\t\tfirstMemory = multiply(firstMemory, secondMemory);\n\t} else if(operator === \"÷\"){\n\t\tfirstMemory = divide(firstMemory, secondMemory);\t\n\t}\n\tshowOnDisplay(firstMemory);\n\tsecondMemory = 0;\n\tneedNewNum = true;\n\tisThereDot = false;\n\tchain = false;\n\tnumEntered = false;\n}", "function trigOp(){\n\tif (!this.classList.contains(\"disabled\")){\n\t\tevaluate();\n\t\tvar inputScreen = document.querySelector('.screen');\n\t\tvar value = inputScreen.innerHTML;\n\t\tif(this.innerHTML.contains(\"sin\")){\n\t\t\tinputScreen.innerHTML = Math.sin(value);\n\t\t}\n\t\telse if(this.innerHTML.contains(\"cos\")){\n\t\t\tinputScreen.innerHTML = Math.cos(value);\n\t\t}\n\t\telse if(this.innerHTML.contains(\"tan\")){\n\t\t\tinputScreen.innerHTML = Math.tan(value);\n\t\t}\n\t\tstartNew = true;\n\t\tif (inputScreen.innerHTML.contains(\".\")){\n\t\t\tdecimalBool = false;\n\t\t\tfactorialBool = false;\n\t\t\tdocument.getElementById(\"deci\").classList.add(\"disabled\");\n\t\t\tdocument.getElementById(\"factorial\").classList.add(\"disabled\");\n\t\t}\n\t}\t\n}", "roots(a, b, c) \n{\n var delta = (b * b) - (4 * a * c);\n console.log(delta);\n if (delta == 0) \n {\n var root = -b/(2*a);\n console.log(root);\n } \n else if (delta > 0) \n {\n var root1 = (-b + (Math.sqrt(delta))) / 2 * a;\n var root2 = (-b - (Math.sqrt(delta))) / 2 * a;\n console.log(\"First root \" + root1);\n console.log(\"Second root \" + root2);\n } \n else if (delta < 0) \n {\n var root1 = -b / 2 * a;\n var root2 = (Math.sqrt(-delta)) / 2 * a;\n console.log(\"First root : \" + root1, \"i :\", root2);\n console.log(\"Second root : \" + root1, \"-i :\", root2);\n } \n else \n {\n console.log(\"Invalid number\");\n }\n }", "function squareRoot( number){\n return Math.sqrt(number);\n }", "function clickEqualButton (){\n entries.push(temporaryValue)\n number = Number(entries[0])\n for (let j=1; j<entries.length-1; j += 2){\n let nextNumber = Number(entries[j+1])\n let symbol = entries[j]\n if (symbol === '+'){number += nextNumber}\n if (symbol === '-'){number -= nextNumber}\n if (symbol === 'x'){number *= nextNumber}\n if (symbol === '÷'){number /= nextNumber}\n if (symbol === '%'){number = number/100 * nextNumber}\n }\n\n //Display result in a way that fits the screen\n let result;\n const MAX_SCREEN_VALUE = 9999999999;\n const MIN_ABS_SCREEN_VALUE = 0.000000001;\n\n if ((number > MAX_SCREEN_VALUE || Math.abs(number) < MIN_ABS_SCREEN_VALUE)\n && number !==0){\n result = number.toExponential(2)\n }\n else if (JSON.stringify(number).length>10){\n result = JSON.stringify(number).substring(0,10)\n }\n else if (number < 0) {\n result = '-' + Math.abs(number)\n }\n else {\n result = number\n }\n document.getElementById('inputField').value = result\n entries = []\n temporaryValue = JSON.stringify(number)\n isResult = true\n}", "function clickEquals() {\n let result\n\n if (operator === '+') {\n result = Number(firstOperand) + Number(secondOperand)\n }\n\n if (operator === '-') {\n result = Number(firstOperand) - Number(secondOperand)\n }\n\n if (operator === '*') {\n result = Number(firstOperand) * Number(secondOperand)\n }\n\n if (operator === '/') {\n result = Number(firstOperand) / Number(secondOperand)\n }\n\n setDisplay(parseFloat(result.toFixed(8)).toString())\n }", "function equalClick(){\n equalTo = true;\n num1 = parseFloat(num1);\n num2 = parseFloat(num2);\n var result = \"\";\n var roundedResult = \"\";\n if(operator === 1){\n result = num1 + num2;\n }\n else if(operator === 2){\n result = num1 - num2;\n }\n else if(operator === 3){\n result = num1 * num2;\n }\n else{\n result = num1 / num2;\n }\n\n roundedResult = result.toFixed(4);\n display.innerHTML = roundedResult;\n if(roundedResult === \"Infinity\"){\n display.innerHTML = \"*dividing by 0 on a calculator?\"\n }\n else if(roundedResult === \"NaN\"){\n display.innerHTML = \"*welp, something went wrong.\";\n }\n}", "function squaR(a) {\n \n var squared = Math.pow(a, 3);\n \n document.write(\"<br/>\" + \"Squares Its: \" + squared + \"<br />\");\n}", "function showAnswer(){\n equalsToIsClicked=true;\n numberIsClicked=true;\n numberOfOperand=1;\n if(numberIsClicked && operatorIsClicked && numberOfOperand===1 && equalsToIsClicked===true){\n switch(myoperator){\n case \"*\":\n num1*=(Number($values.innerText));\n $values.innerText=num1;\n if($values.innerText.length>8){\n $values.innerText=num1.toPrecision(3);\n throw \"the number of digits exceeded\";\n \n }\n break;\n case \"+\":\n num1+=(Number($values.innerText));\n $values.innerText=num1;\n if($values.innerText.length>8){\n $values.innerText=num1.toPrecision(3);\n throw \"the number of digits exceeded\";\n }\n break;\n case \"-\":\n num1-=(Number($values.innerText));\n $values.innerText=num1;\n if($values.innerText.length>8){\n $values.innerText=num1.toPrecision(2);\n throw \"the number of digits exceeded\";\n }\n break;\n case \"/\":\n num1/=(Number($values.innerText));\n $values.innerText=num1;\n if($values.innerText.length>8){\n $values.innerText=num1.toPrecision(3);\n throw \"the number of digits exceeded\";\n }\n break;\n\n }\n }\n numberIsClicked=false;\n operatorIsClicked=false;\n equalsToIsClicked=false;\n numberOfOperand=0;\n numberChecker=0;\n\n}", "BigInt_sqrt(b) {\n if (b < 0n) throw \"square root of negative numbers is not supported\";\n if (b < 2n) return b;\n function newtonIteration(n, x0) {\n const x1 = (n / x0 + x0) >> 1n;\n if (x0 === x1 || x0 === x1 - 1n) {\n return x0;\n }\n return newtonIteration(n, x1);\n }\n return newtonIteration(b, 1n);\n }", "function sRoot(number){\n return Math.sqrt(number);\n }", "function circumference () {\n d = document.getElementById('input').value\n d = parseInt(d)\n r = d / 2\n answer = 2 * Math.PI * r\n document.getElementById('answers').innerHTML = Math.round(answer * 10) / 10\n}", "function equalClick(){\n equalTo = true;\n num1 = parseFloat(num1); //Turns num1 from a string to a number\n num2 = parseFloat(num2); //Turns num2 from a string to a number\n var result = \"\";\n var roundedResult = \"\";\n\n if(operator === 1){\n result = num1 + num2;\n }else if(operator === 2){\n result = num1 - num2;\n }else if(operator === 3){\n result = num1 * num2;\n }else{\n result = num1 / num2;\n }\n\n roundedResult = result.toFixed(4);\n display.innerHTML = roundedResult;\n\n if(roundedResult === \"Infinity\"){\n display.innerHTML = \"You can't divide by zero\"\n alert(\"Don't do that\")\n }\n if(roundedResult === \"NaN\"){\n display.innerHTML = \"Invalid calculation\"\n alert(\"What did you do\")\n }\n}", "function equalPressed() {\n if(equalFire == true){\n num1 = doMath(num1 , storeNum2 , operator);\n $(\"#displayScreen p\").text(parseFloat(num1).toFixed(3));\n }else {\n if(inputs.length <= 2){\n num2 = num1;\n }\n num1 = doMath(num1, num2, operator);\n $(\"#displayScreen p\").text(num1);\n inputs = [];\n num2 = null;\n totalInt2 = null;\n inputs[0] = num1;\n i = 1;\n equalFire = true;\n }\n}", "function gen_vfp_sqrt(/* int */ dp) { if (dp) gen_op_vfp_sqrtd(); else gen_op_vfp_sqrts(); }", "function symPress(inputSym) {\n // If the sym is not =, then reset the equal values\n if (inputSym !== '=') {\n equalTemp = undefined;\n eqPress = false;\n }\n // Switch cases for various symbols\n switch (inputSym) {\n case '+':\n // Only allows you to input operands if num1 has already been defined\n // Otherwise, you can press an operand, and then a num, which can cause weird results\n if (num1 !== '') {\n // If num2 isn't defined yet, set the operand and do nothing else\n if (num2 === '') {\n displayWindow.innerHTML = '+';\n operand = '+';\n break;\n // If it has been defined, calculate the last 2 numbers, display that result,\n // place the result in num1, and clear num2\n } else {\n multiCalc(operand);\n displayWindow.innerHTML = num1;\n operand = '+';\n break;\n }\n }\n break;\n case '-':\n if (num1 !== '') {\n if (num2 === '') {\n displayWindow.innerHTML = '-';\n operand = '-';\n break;\n } else {\n multiCalc(operand);\n displayWindow.innerHTML = num1;\n operand = '-';\n break;\n }\n }\n break;\n case '/':\n if (num1 !== '') {\n if (num2 === '') {\n displayWindow.innerHTML = '/';\n operand = '/';\n break;\n } else {\n multiCalc(operand);\n displayWindow.innerHTML = num1;\n operand = '/';\n break;\n }\n }\n break;\n case 'X':\n if (num1 !== '') {\n if (num2 === '') {\n displayWindow.innerHTML = 'X';\n operand = '*';\n break;\n } else {\n multiCalc(operand);\n displayWindow.innerHTML = num1;\n operand = '*';\n break;\n }\n }\n break;\n case '=':\n // If either input is '.' --> display \"Illegal use of decimal\"\n if (num1 === '.' || num2 === '.') {\n clear();\n displayWindow.innerHTML = '-Invalid Use of Decimal-';\n }\n // Records a boolean for if = was the last sym pressed\n eqPress = true;\n // If neither num1 nor num2 have been defined yet, do nothing\n if (num1 === '' && num2 === '') {\n break;\n // If num2 is undefined, calculate using num1 [operand] num1\n } else if (num2 === '') {\n displayWindow.innerHTML = equalCalc(operand);\n break;\n // If num2 has been defined, record num2 in the equal sign's temp num holder, then calculate\n } else {\n equalTemp = num2;\n displayWindow.innerHTML = mathCalc(operand);\n break;\n }\n case '.':\n // If operand is undefined, then apply decimal to num1\n if (operand === '') {\n // Check to make sure num1 doesn't already have a decimal\n if (!num1.includes('.')) {\n num1 += '.';\n displayWindow.innerHTML = num1;\n }\n } else {\n if (!num2.includes('.')) {\n num2 += '.';\n displayWindow.innerHTML = num2;\n }\n }\n break;\n // Clears the calc and all its variables if btn C is pressed\n case 'C':\n clear();\n }\n}", "function sqrt(n) {\n return 1 / inverseSqrt(n);\n}", "function ctfclick(){\r\n //define the number\r\n let C = Number(document.getElementById('tic').value);\r\n\r\n //create the formula\r\n let answerC = 'Temperature in Farhrenheit' + [32 + (C * 9/5)]\r\n\r\n //output\r\n document.getElementById('result').innerHTML = answerC;\r\n}", "function operClicked(){\n\tif((chain === false)){\n\t\tfirstMemory = Number($display.val());\n\t} else if(numEntered){\n\t\tif(operator === \"+\"){\n\t\t\tfirstMemory = add(firstMemory, Number($display.val()));\n\t\t} else if(operator === \"-\"){\n\t\t\tfirstMemory = substract(firstMemory, Number($display.val()));\n\t\t} else if(operator === \"×\"){\n\t\t\tfirstMemory = multiply(firstMemory, Number($display.val()));\n\t\t} else if(operator === \"÷\"){\n\t\t\tfirstMemory = divide(firstMemory, Number($display.val()));\t\n\t\t}\n\t} \n\n\toperator = $(this).text();\n\tconsole.log(operator);\n\tchain = true;\n\tneedNewNum = true;\n\tisThereDot = false;\n\tnumEntered = false;\n}", "function eqClicked() {\r\n calculateResult();\r\n printText();\r\n deleteText();\r\n}", "function squareNumber(num){\n console.log(`The square root of the number is${num ** 2}`)\n return num ** 2\n}", "function APosition_TimeCalculation(InitialPosition, FinalPosition, Acceleration)\n{\n //t = 2*sqrt((xf - xi)/a) || t = 2 * squareRoot( (xf - xi) / a )\n var square = (FinalPosition - InitialPosition) / Acceleration;\n var Time = 2 * Math.sqrt(square);\n document.getElementById(\"result\").value = Time;\n //return Time;\n}", "function buttonClickHandler(el) {\n removeLeadingZero(el)\n lastValue = el.value\n\n let basicOperator = evalBasicOperator(el)\n if (calculatePower(el)) {\n\n }\n else if (basicOperator != null) {\n display += basicOperator\n evaluationString += basicOperator\n if(basicOperator == \"-\" || basicOperator ==\"+\"){\n lastDigitClicked += basicOperator\n }\n } else if (!evalComplexOperator(el)) {\n if(!isNaN(el.value)){\n if(!isNaN(lastValue)){\n lastDigitClicked += el.value\n }else{\n lastDigitClicked = el.value\n }\n }\n display += el.value\n evaluationString += el.value\n }\n document.getElementById(\"output\").value = display\n}", "function quadratic(a,b,c) {\n let equation = -b +- Math.sqrt(b**2 -4*(a*c))/2*(a);\n console.log(equation);\n}", "function checkMath2() {\n var answer, text;\n\n // Get the value of the input field with id=\"numb-2\"\n answer = document.getElementById(\"numb-2\").value;\n\n // Will return true if answer is 5 psi above or below the answer\n if (answer == totalFriction2() ||\n answer == totalFriction2() - 5 ||\n answer == totalFriction2() + 5 ||\n answer == totalFriction2() - 4 ||\n answer == totalFriction2() + 4 ||\n answer == totalFriction2() - 3 ||\n answer == totalFriction2() + 3 ||\n answer == totalFriction2() - 2 ||\n answer == totalFriction2() + 2 ||\n answer == totalFriction2() - 1 ||\n answer == totalFriction2() + 1) {\n text = \"This is the correct PSI\";\n } else {\n text = \"Nope, remember your training my young padawan!\";\n };\n document.getElementById(\"demo-2\").innerHTML = text;\n}", "function showTheSign() {\n //Variables\n var input1 = parseFloat(document.getElementById('input21').value);\n var input2 = parseFloat(document.getElementById('input22').value);\n var input3 = parseFloat(document.getElementById('input23').value);\n var value1 = document.getElementById('val21');\n var value2 = document.getElementById('val22');\n var value3 = document.getElementById('val23');\n var result = document.getElementById('result2');\n\n //The sign of each one number\n sign(input1, value1, 1);\n sign(input2, value2, 2);\n sign(input3, value3, 3);\n\n //Define the sign of the product of the three numbers\n if (input1 == 0 || input2 == 0 || input3 == 0) {\n result.innerHTML = \"The result of the product is 0!\";\n }\n else if (!isNaN(input1) && !isNaN(input2) && !isNaN(input3)) {\n result.innerHTML = \"The sign of the product is \" +\n ((input1 > 0 ^ input2 > 0 ^ input3 > 0) ? \"+\" : \"-\");\n }\n else result.innerHTML = null;\n}", "function power2(){\n\tcurrent = Math.pow(eval(current), 2);\n\tdocument.getElementById('screen').value = current;\n}", "function raisedValue(){\r\n var a =prompt(\"enter first value\");\r\n var b = prompt(\"enter second value\");\r\n console.log(Math.pow(a, b))\r\n }", "function button1(button) {\n\tflag = \"0\";\n\tif (document.calc.view.value == \"0\") {\n\t\tdocument.calc.view.value = button;\n\t\tif (document.calc.view.value == \".\") {\n\t\t\tdocument.calc.view.value = document.calc.view.value.replace(\".\",\"0.\");\n\t\t\tflag = \"1\";\n\t\t}\n\t} else {\n\t\tif (flag == \"1\") {\n\t\t\tif (button == \".\") {\n\t\t\t\tbutton = \"\";\n\t\t\t}\n\t\t}\n\t\tif (document.calc.view.value.indexOf(\"√(\") != \"-1\") {\n\t\t\tif (document.calc.view.value[document.calc.view.value.indexOf(\"√(\")-1] != \")\") {\n\t\t\t\tdocument.calc.view.value = document.calc.view.value.replace(/\\s/g,\"\");\n\t\t\t\tdocument.calc.view.value = document.calc.view.value.slice(0,document.calc.view.value.indexOf(\"√(\"));\n\t\t\t\tdocument.calc.view.value += button + \"√(\";\n\t\t\t} else {\n\t\t\t\tbutton2(button);\n\t\t\t}\n\t\t} else {\n\t\t\tbutton2(button);\n\t\t}\n\t}\n\tif (button == \".\") {\n\t\tflag = \"1\";\n\t}\n\telse if (isNaN(button)) {\n\t\tflag = \"0\";\n\t}\n}", "function doMathClicked () {\n // this function does basic math\n\n document.getElementById('area').innerHTML = 'The area is 5 x 3 = ' + (3 * 5) + (' cm²')\n document.getElementById('perimeter').innerHTML = 'The perimeter is 2(5 + 3) = ' + ((5 + 3) * 2) + (' cm')\n}", "quadraticEquation(a, b, c) {\n var delta = b * b - (4 * a * c);\n var root1 = (-b + (Math.sqrt(delta))) / (2 * a);\n var root2 = (-b - (Math.sqrt(delta))) / (2 * a);\n console.log(\" First root is : \" + root1);\n console.log(\" Second root is : \" + root2);\n\n }", "function operatorClick() {\n lowerDisplayString = lowerDisplayString + \" \" + $(this).text() + \" \";\n $('#lower-display').text(lowerDisplayString);\n if (displayString !== \"\") {\n if (firstOperator === true) {\n mathObject.firstNumber = Number(displayString);\n mathObject.operator = $(this).attr('id');\n displayString = \"\";\n firstOperator = false;\n $(this).addClass('keyFrame');\n keyFrame = $(this);\n window.setTimeout(removeKeyframe, 250);\n positive = true;\n }\n else {\n //ajax request to get result of previous calculation\n mathObject.secondNumber = Number(displayString);\n mathObject.nextOperator = $(this).attr('id');\n console.log(mathObject);\n displayString = \"\";\n $(this).addClass('keyFrame');\n keyFrame = $(this);\n window.setTimeout(removeKeyframe, 250);\n doFirstCalculation();\n positive = true;\n }\n }\n}", "function atvd17(){\n \n let a = parseFloat(document.querySelector(\"#atvd17-1\").value);\n let b = parseFloat(document.querySelector(\"#atvd17-2\").value);\n let c = parseFloat(document.querySelector(\"#atvd17-3\").value);\n\n let de,x1=0,x2=0;\n \n\n de = (Math.pow(b, 2)) - (4*a*c);\n \n \n x1= (-b - Math.sqrt(de))/(2*a);\n \n x2= (-b + Math.sqrt(de))/(2*a);\n \n\n if(de<0){\n document.getElementById(\"raiz\").innerHTML = \"Não existe raiz real\";\n\n }else{\n document.getElementById(\"raiz\").innerHTML = \"VALOR DA PRIMEIRA RAIZ:\" + x1+ \" | \" + \"VALOR DA SEGUNDA RAIZ:\" + x2;\n \n }\n \n }", "function pressEqual(){\n getNum();\n switch(calc[1]){\n case ('+'):\n result = add(calc[0],calc[2]);\n break;\n case('-'):\n result = subtract(calc[0],calc[2]);\n break;\n case('x'):\n result = multiply(calc[0],calc[2]);\n break;\n case('÷'):\n result = divide(calc[0],calc[2]);\n break;\n default:\n result = calc[2];\n break;\n }\n calc = [];\n numbers.push(result);\n console.log(result);\n console.log(calc);\n var display = $('.display');\n display.text(result);\n}", "function calculateSide(sideA, sideB)\n{\n // returns sqrt\nreturn Math.sqrt(sideA * sideA + SideB * SideB)\n}", "function buttonPress(value) {\n if (value === \"0\" && displayValue.endsWith(\"/\")) {\n alert(\"You can't divide by 0, sorry.\");\n } else {\n\n displayValue += value;\n equationValue += value;\n display.innerText = displayValue;\n equation.innerText = equationValue;\n }\n}", "function math() {\r\n var num1 = document.getElementById(\"inputNum1\").value;\r\n var num2 = document.getElementById(\"inputNum2\").value;\r\n var product = num1 * num2;\r\n document.getElementById(\"mul\").innerHTML = product;\r\n console.log(product);\r\n}", "function equals() {\r\n // If value 1 is not set display error\r\n if (value_1 === null) {\r\n errorDisplay(3);\r\n return;\r\n }\r\n\r\n // When equals pressed when answer displayed, display answer\r\n if (answer !== null) {\r\n displayValue(answer);\r\n return;\r\n }\r\n\r\n // Set second value\r\n value_2 = toNum(current_value);\r\n console.log(value_1);\r\n console.log(value_2);\r\n\r\n // Check if there are float numbers\r\n if (isFloatNum(value_1) || isFloatNum(value_2)) {\r\n // Using big.js library to avoid problems with decimal math in JS \r\n // BIG.JS library by Michael Mclaughlin\r\n // https://github.com/MikeMcl/big.js/LICENCE.md\r\n var x = Big(value_1);\r\n }\r\n\r\n\r\n // Calculate\r\n switch (operation_type) {\r\n case \"+\":\r\n if (isFloatNum(value_1) || isFloatNum(value_2)) answer = Number(x.plus(value_2).valueOf());\r\n else answer = value_1 + value_2;\r\n\r\n displayValue(answer);\r\n break;\r\n case \"-\":\r\n if (isFloatNum(value_1) || isFloatNum(value_2)) answer = Number(x.minus(value_2).valueOf());\r\n else answer = value_1 - value_2;\r\n\r\n displayValue(answer);\r\n break;\r\n case \"/\":\r\n if (value_2 === 0) {\r\n errorDisplay(2);\r\n return;\r\n }\r\n if (isFloatNum(value_1) || isFloatNum(value_2)) answer = Number(x.div(value_2).valueOf());\r\n else answer = value_1 / value_2;\r\n\r\n displayValue(answer);\r\n break;\r\n case \"x\":\r\n if (isFloatNum(value_1) || isFloatNum(value_2)) answer = Number(x.times(value_2).valueOf());\r\n else answer = value_1 * value_2;\r\n\r\n displayValue(answer);\r\n break;\r\n default:\r\n errorDisplay(3);\r\n }\r\n // Update current value\r\n current_value = \"\";\r\n}", "function calculatePower(event) {\n let dString = display.toString();\n \n if(!isPowerPressed && lastValue == '^'){\n isPowerPressed = true\n }else if(isPowerPressed){\n display += (dString.charAt(dString.length - 1) == \"^\") ? event.value : \"^\"\n display = eval(\"Math.pow(\" + lastDigitClicked + \",\" + event.value + \")\")\n evaluationString = eval(\"Math.pow(\" + lastDigitClicked + \",\" + event.value + \")\")\n lastDigitClicked = display\n isPowerPressed = false\n return true\n }\n return false\n}", "function renderCalculator() {\n var firstNumber = '';\n var secondNumber = '';\n var operator = '';\n var result = '';\n var isOperatorChosen = false;\n\n $('.number').on('click', function () {\n\n // check about opperator being picked yet.\n if (result !== '') {\n alert('You have already done an equation, please clear the Calculator');\n }\n else if (isOperatorChosen) {\n secondNumber += $(this).val();\n $('#second-number').text(secondNumber);\n\n }\n else {\n firstNumber += $(this).val();\n $('#first-number').text(firstNumber);\n }\n\n });\n\n $('.operator').on('click', function () {\n\n if (operator !== '') {\n\n }\n else if (firstNumber > 0) {\n\n operator = $(this).val();\n if (operator == 'plus') {\n $('#operator').text('+');\n }\n else if (operator == 'minus') {\n $('#operator').text('-');\n }\n else if (operator == 'times') {\n $('#operator').text('*');\n }\n else if (operator == 'divide') {\n $('#operator').text('\\xF7');\n }\n else if (operator == 'power') {\n $('#operator').text('^');\n }\n isOperatorChosen = true;\n }\n else {\n alert('Please insert a number before choosing operator');\n }\n });\n\n $('.equal').on('click', function () {\n\n if (secondNumber === '') {\n alert('equation can not be run without 2 numbers & an operator');\n }\n else {\n firstNumber = parseFloat(firstNumber);\n secondNumber = parseFloat(secondNumber);\n\n if (operator === 'plus') {\n\n result = firstNumber + secondNumber;\n }\n\n else if (operator === 'minus') {\n result = firstNumber - secondNumber;\n }\n\n else if (operator === 'times') {\n result = firstNumber * secondNumber;\n }\n\n else if (operator === 'divide') {\n result = firstNumber / secondNumber;\n }\n\n else if (operator === 'power') {\n result = Math.pow(firstNumber, secondNumber);\n }\n\n $('#result').text(result);\n }\n\n\n });\n\n $('.clear').on('click', function () {\n\n $('#first-number').empty();\n $('#operator').empty();\n $('#second-number').empty();\n $('#result').empty();\n firstNumber = '';\n secondNumber = '';\n operator = '';\n result = '';\n isOperatorChosen = false;\n })\n }", "doMath(){\n // console.log(\"pressed: \" + this.icon);\n this.mathTime(this.icon)\n }", "Dis(x2, y2) {\n var x1 = 0;\n var y1 = 0;\n\n console.log(\"X1 is \" + x1);\n console.log(\"Y is \" + y1);\n\n var xs = (x2 - x1);\n var ys = (y2 - y1);\n xs *= xs;\n ys *= ys;\n\n var distance = Math.sqrt(xs + ys);\n console.log(\"Result is =>\" + distance);\n\n }", "function multiply() {\n let num1 = document.getElementById('num1').value;\n let num2 = document.getElementById('num2').value;\n let result = document.getElementById('calResult');\n res = num1 * num2;\n console.log(num1);\n // console.log('multiply' + res);\n result.innerHTML = `<p>The ruslt is ${res}</p>`;\n}", "function evalComplexOperator(el) {\n switch (el.value) {\n case \"LOG\":\n display = eval(\"Math.log(\" + lastDigitClicked + \")\")\n if(!isNaN(display)){\n evaluationString = eval(\"Math.log(\" + lastDigitClicked + \")\")\n }else{\n display = evaluationString =0;\n }\n lastDigitClicked = display\n break\n case \"SQRT\":\n display = eval(\"Math.sqrt(\" + lastDigitClicked + \")\")\n if(!isNaN(display)){\n evaluationString = eval(\"Math.sqrt(\" + lastDigitClicked + \")\")\n }else{\n display = evaluationString =0;\n }\n lastDigitClicked = display\n break\n case \"CUBRT\":\n display = eval(\"Math.cbrt(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.cbrt(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"TAN\":\n display = eval(\"Math.tan(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.tan(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"COS\":\n display = eval(\"Math.cos(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.cos(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n case \"SIN\":\n display = eval(\"Math.sin(\" + lastDigitClicked + \")\")\n evaluationString = eval(\"Math.sin(\" + lastDigitClicked + \")\")\n lastDigitClicked = display\n break\n default:\n return false\n }\n console.log(evaluationString)\n return true\n\n}", "mul() {\n document.getElementById(\"read\").style.display = \"none\";\n document.getElementById(\"add\").style.display = \"none\";\n document.getElementById(\"mul\").style.display = \"block\";\n\n calculator.multiplied = calculator.first * calculator.second;\n document.getElementById(\"mul\").innerHTML = calculator.multiplied;\n\n }", "function init() {\n\n // Create display\n formulaInput = $(\"<input type='text' class='form-control form-inline' placeholder='Enter formula' aria-describedby='calculator-hint'>\");\n formulaInput.on(\"keyup change\", calculate);\n hintText = $(\"<span id='calculator-hint' class='help-block'>&nbsp;</span>\");\n var resultBox = $(\"<h2>\");\n resultDisplay = $(\"<span>0</span>\");\n var useResultButton = $(\"<a href='#' class='btn btn-default btn-xs'>&uarr;</a>\").click(useResult);\n resultBox.append(resultDisplay).append(\"&nbsp;\").append(useResultButton);\n container.append($(\"<div class='col-md-12'>\").append(formulaInput).append(hintText).append(resultBox));\n\n // Create function buttons\n var row = $(\"<div class='btn-group btn-group-justified'>\");\n row.append($(\"<a href='#' class='btn btn-default'>C</a>\").click(reset));\n row.append($(\"<a href='#' class='btn btn-default'>CE</a>\").click(clear));\n row.append($(\"<a href='#' class='btn btn-default'>&larrhk;</a>\").click(undo));\n container.append(row);\n\n // Create all non-function buttons\n var buttons = [\"(\", \")\", \"7\", \"8\", \"9\", \"%\", \"^\", \"4\", \"5\", \"6\", \"/\", \"*\", \"1\", \"2\", \"3\", \"+\", \"-\", \"0\", \".\"];\n $.each(buttons, function(i, v) {\n if((i+3) % 5 == 0) {\n container.append(row);\n row = $(\"<div class='btn-group btn-group-justified'>\");\n }\n row.append($(\"<a href='#' class='btn btn-default'>\"+v+\"</a>\").click(symbolClick));\n });\n\n // Add more function buttons\n row.append($(\"<a href='#' class='btn btn-default'>&plusmn;</a>\").click(togglePositivity));\n row.append($(\"<a href='#' class='btn btn-default'>&larr;</a>\").click({amount: -1}, moveCursor));\n row.append($(\"<a href='#' class='btn btn-default'>&rarr;</a>\").click({amount: 1}, moveCursor));\n container.append(row);\n\n // Stop default event behaviour to prevent input losing focus\n container.on(\"mousedown\", \"a\", function(e) {\n if(!formulaInput.is(\":focus\")) {\n formulaInput.focus();\n }\n e.preventDefault();\n });\n\n\n }", "function square_root(x) {\n return x * x;\n}", "function sqare(m,n) {\n let tot = (m+n);\n let tot1 = Math.pow(tot,2);\n // console.log(tot1);\n if (tot1 % 2 == 0){\n return `the sum of squares of ${m} and ${n} is even`;\n }\n return \"odd\";\n}", "function triArea() {\n let side1 = document.getElementById('side1').value;\n let side2 = document.getElementById('side2').value;\n let side3 = document.getElementById('side3').value;\n side1 = parseInt(side1);\n side2 = parseInt(side2);\n side3 = parseInt(side3);\n\n const resultArea = document.getElementById('resultArea');\n\n let s = (side1 + side2 + side3) / 2;\n let area = Math.sqrt(s * ((s - side1) * (s - side2) * (s - side3)));\n console.log(area);\n resultArea.innerHTML = `<p>The area of Triangle is ${area}</p>`;\n}", "function volumeSphere(){\n event.preventDefault();\n let volume=0;\n let inputRadius = document.getElementById('radius');\n let radiusValue = inputRadius.value;\n radiusValue = Math.abs(radiusValue);\n volume = (4/3)*Math.PI*Math.pow(radiusValue, 3);\n volume = volume.toFixed(2);\n let inputVolume = document.getElementById('volume');\n inputVolume.value = volume;\n return false;\n}", "function wurzel(num1) {\n if(!isEmpty(num1)) {\n if (num1 === 0) {\n return null;\n } else {\n return Math.sqrt(num1);\n }\n }\n return null;\n }", "function pitagoroTeorema (x,y) {\n\nvar atsakymas = Math.sqrt( (x*x) + (y*y) );\nconsole.log(atsakymas);\n\n}", "function myFunction() {\n a = 4;\n b = 3;\n document.getElementById(\"result\").innerHTML = Math.pow(a, b); \n}", "function sqrNum(num){\n z=num**2\n return z;\n}", "function scalMtx2(row, col, operation) {\r\n var scal = document.getElementById(\"scalNum2\").value;\r\n var string = \"<section class='matrixCont' id='displayMatrix2'>\";\r\n if (operation == 2) {\r\n string += \"<div>X</div>\";\r\n }\r\n if (operation == 1) {\r\n string += \"<div>-</div>\";\r\n }\r\n if (operation == 0) {\r\n string += \"<div>+</div>\";\r\n }\r\n string += \"\\n<button type='submit' onclick='nextScalar2(\" + row + \",\" + col + \",\" + operation + \")'>Scalar Multiplication</button><table class='matrix' id='matrix2'>\";\r\n var product;\r\n var curr2;\r\n var curString2 = \"\";\r\n\r\n //Checks if it is a Square Matrix\r\n if (row == col) {\r\n for (var i = 0; i < row; i++) {\r\n string += \"\\n<tr>\";\r\n for (var j = 0; j < col; j++) {\r\n curString2 = \"mtrx2-\" + i + \"-\" + j;\r\n curr2 = Number(document.getElementById(curString2).innerText);\r\n product = curr2 * scal;\r\n console.log(product);\r\n string += \"\\n<td id='mtrx2-\" + i + \"-\" + j + \"'>\\n\" + product + \"</td>\";\r\n }\r\n string += \"\\n</tr>\";\r\n }\r\n string += \"\\n</table>\\n<section id='scalar2'></section><section id='detMatrix2'></section>\";\r\n } else {\r\n for (var i = 0; i < row; i++) {\r\n string += \"\\n<tr>\";\r\n for (var j = 0; j < col; j++) {\r\n curString2 = \"mtrx2-\" + i + \"-\" + j;\r\n curr2 = Number(document.getElementById(curString2).innerText);\r\n product = curr2 * scal;\r\n console.log(product);\r\n string += \"\\n<td id='mtrx2-\" + i + \"-\" + j + \"'>\\n\" + product + \"</td>\";\r\n }\r\n string += \"\\n</tr>\";\r\n }\r\n string += \"\\n</table>\\n<section id='scalar2'></section><section id= 'detMatrix2'></section>\";\r\n }\r\n if (operation == 2) {\r\n string += \"<button type='submit' onclick='multiEqual(\" + row + \",\" + col + \")'>=</button></section>\";\r\n }\r\n if (operation == 1) {\r\n string += \"<button type='submit' onclick='subEqual()'>=</button></section>\";\r\n }\r\n if (operation == 0) {\r\n string += \"<button type='submit' onclick='addEqual()'>=</button></section>\";\r\n }\r\n $(\"#displayMatrix2\").replaceWith(string);\r\n}", "function solve()\n {\n let x = document.querySelector(\"#result\").value\n let y = eval(x)\n document.querySelector(\"#result\").value = y\n document.addEventListener(\"click\");\n }", "function square_root(x) {\n return Math.sqrt(x);\n}", "static equation(start) {\n const oddFunc = odd => 3 * odd + 1;\n const evenFunc = even => even / 2;\n\n // Checks if number is even or odd\n const alg = startNum =>\n startNum % 2 == 0 ? evenFunc(startNum) : oddFunc(startNum);\n\n let result = alg(start);\n\n // conditional will recall equation() until result == 1\n if (result == 1) {\n steps.push(result);\n } else {\n steps.push(result);\n UI.equation(result);\n }\n }", "function main() {\n\n\n var radius = readLine();\n\n const PI = Math.PI;\n\n console.log(PI * radius * radius)\n \n\n console.log(2 * PI * radius) }" ]
[ "0.77701765", "0.7674613", "0.764238", "0.7073108", "0.67948544", "0.67832655", "0.67496145", "0.657851", "0.6577292", "0.6559996", "0.6517264", "0.6485672", "0.63884056", "0.63780576", "0.6376439", "0.63609415", "0.62917024", "0.6281794", "0.6215785", "0.61818063", "0.61530745", "0.60454965", "0.6041232", "0.60384774", "0.6013557", "0.59809756", "0.59756196", "0.5964831", "0.59515965", "0.595025", "0.59486175", "0.59331286", "0.5889906", "0.58892703", "0.5878942", "0.5876264", "0.5869741", "0.58601594", "0.58587337", "0.58488274", "0.5846282", "0.582737", "0.5809171", "0.5797566", "0.57934004", "0.57760406", "0.57581854", "0.5746912", "0.5739271", "0.5735696", "0.5733876", "0.573329", "0.5725409", "0.5724227", "0.57082903", "0.57057124", "0.5703799", "0.57023937", "0.5699303", "0.56948143", "0.56798315", "0.5671745", "0.5667067", "0.56665134", "0.5666373", "0.5642732", "0.5633864", "0.56323403", "0.5625267", "0.5620766", "0.5619874", "0.56109893", "0.55999213", "0.5592951", "0.55878663", "0.5583858", "0.55819744", "0.5579404", "0.5577392", "0.55736434", "0.55651855", "0.5546397", "0.5546215", "0.55432546", "0.55221885", "0.5514032", "0.55127585", "0.5511765", "0.5500655", "0.5500282", "0.55000144", "0.5498275", "0.54950416", "0.5492545", "0.5492318", "0.547493", "0.5474631", "0.54741865", "0.54740614", "0.5471982" ]
0.79958236
0
return HTML iframe display for the Gantt in the Database spreadsheet
function getEntireGanttSheet(width, height) { var widthScalar = 0.75; var heightScalar = 0.85; var html = `<div> <div> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#centeredFullGantt"> View Full Gantt </button> <div class="modal fade" id="centeredFullGantt" tabindex="-1" role="dialog" aria-labelledby="centeredFullGantt" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content" style="width: ` + width * widthScalar * 1.1 + `px; height: ` + height * heightScalar * 1.1 + `px"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body" style="width: ` + width * widthScalar + `px; height: ` + height * heightScalar + `px"> <iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ21BbKSgpjzx-GgFu8OymjbgaaWcp-VnTcNdeFYiMmcib_LTpYQcs4229ZvGBwUNrB8zBpOqzYvF7v/pubhtml?gid=100811517&amp;single=true&amp;widget=true&amp;headers=false" style="width: ` + width * widthScalar + `px; height: ` + height * heightScalar + `px"> </iframe> </div> </div> </div> </div> </div> <div class="big-gantt"> <iframe src="https://docs.google.com/spreadsheets/d/e/2PACX-1vQ21BbKSgpjzx-GgFu8OymjbgaaWcp-VnTcNdeFYiMmcib_LTpYQcs4229ZvGBwUNrB8zBpOqzYvF7v/pubhtml?gid=100811517&amp;single=true&amp;widget=true&amp;headers=false" style="width: 100%; height: 700px"> </iframe> </div> </div>`; return html; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Calendar() {\n return (\n <>\n <h5>Calendar</h5>\n <iframe\n title=\"Calendar Title\"\n src=\"https://calendar.google.com/calendar/embed?src=jonpchristie%40gmail.com&ctz=America%2FNew_York\"\n width= \"100%\"\n height= \"100%\"\n frameborder=\"0\"\n scrolling=\"yes\"\n ></iframe>\n </>\n );\n}", "function viewHtml() {\n var entry = ProjectManager.getSelectedItem();\n if (entry === undefined) {\n entry = DocumentManager.getCurrentDocument().file;\n }\n var path = entry.fullPath;\n var w = window.open(path);\n w.focus();\n }", "function setIframeSource() {\n var theSelect = document.getElementById('PSKILLS');\n var graphID;\n\n graphID = theSelect.options[theSelect.selectedIndex].value;\n $(\"#graph\").html('<iframe id=\"major_param\" src=\"http://public.tableausoftware.com/views/GSS/' + graphID + '_Dashboard?' + filterForGraphs + '&:toolbar=top\" width=\"100%\" height=\"600px\" frameborder=\"0\" scrolling=\"no\"></iframe>');\n}", "async displayIframe() {\n return this.display(checkIsMobile())\n }", "function selectLoopSendDisplayByGrid() {\n\tvar Url = L5.webPath + \"/jsp/workflow/help/selectloopsend.jsp?assignmentId=\"\n\t+ getProcessInfoFromContext(\"assignmentId\");\n\tUIFrame(command, method, Url,\"Next\");\n\t\n/*\tvar url=L5.webPath+\"/jsp/public/help/help.jsp?helpCode=bsp_employeelistquery\"\n\n\tvar returnValue = showModalDialog(url, window,\n\t\"scroll:no;status:no;dialogWidth:500px;dialogHeight:400px\");\n\treturn assignValueToCurrentActivity(returnValue);*/\n}", "function show(data1) { \r\nlet tab = \r\n ``; \r\n\r\n// Loop to access rows \r\nfor (let r of data1.data.notifications) { \r\n \r\n tab += `\r\n <tr>\r\n <td class=\"text-left\">${r.title} </td>\r\n <td class=\"text-left\"><a href=\"${r.link}\" target=\"_blank\" style=\"color:#4285f4\">[Link]</a></td>\r\n </tr>`; \r\n \r\n} \r\n// Setting innerHTML as tab variable \r\ndocument.getElementById(\"notf\").innerHTML = tab; \r\n\r\n}", "function drawGantt() {\r\n // first, if detail is displayed, reload class\r\n if (dojo.byId('objectClass') && !dojo.byId('objectClass').value\r\n && dojo.byId(\"objectClassName\") && dojo.byId(\"objectClassName\").value) {\r\n dojo.byId('objectClass').value = dojo.byId(\"objectClassName\").value;\r\n }\r\n if (dojo.byId(\"objectId\") && !dojo.byId(\"objectId\").value && dijit.byId(\"id\")\r\n && dijit.byId(\"id\").get(\"value\")) {\r\n dojo.byId(\"objectId\").value = dijit.byId(\"id\").get(\"value\");\r\n }\r\n var startDateView = new Date();\r\n if (dijit.byId('startDatePlanView')) {\r\n startDateView = dijit.byId('startDatePlanView').get('value');\r\n }\r\n var endDateView = null;\r\n if (dijit.byId('endDatePlanView')) {\r\n endDateView = dijit.byId('endDatePlanView').get('value');\r\n }\r\n var showWBS = null;\r\n if (dijit.byId('showWBS')) {\r\n showWBS = dijit.byId('showWBS').get('checked');\r\n }\r\n // showWBS=true;\r\n var gFormat = \"day\";\r\n if (g) {\r\n gFormat = g.getFormat();\r\n }\r\n g = new JSGantt.GanttChart('g', dojo.byId('GanttChartDIV'), gFormat);\r\n setGanttVisibility(g);\r\n g.setCaptionType('Caption'); // Set to Show Caption\r\n // (None,Caption,Resource,Duration,Complete)\r\n // g.setShowStartDate(1); // Show/Hide Start Date(0/1)\r\n // g.setShowEndDate(1); // Show/Hide End Date(0/1)\r\n g.setDateInputFormat('yyyy-mm-dd'); // Set format of input dates\r\n // ('mm/dd/yyyy', 'dd/mm/yyyy',\r\n // 'yyyy-mm-dd')\r\n g.setDateDisplayFormat('default'); // Set format to display dates\r\n // ('mm/dd/yyyy', 'dd/mm/yyyy',\r\n // 'yyyy-mm-dd')\r\n g.setFormatArr(\"day\", \"week\", \"month\", \"quarter\"); // Set format options (up\r\n if (dijit.byId('selectBaselineBottom')) {\r\n g.setBaseBottomName(dijit.byId('selectBaselineBottom').get('displayedValue'));\r\n }\r\n if (dijit.byId('selectBaselineTop')) {\r\n g.setBaseTopName(dijit.byId('selectBaselineTop').get('displayedValue'));\r\n }\r\n // to 4 :\r\n // \"minute\",\"hour\",\"day\",\"week\",\"month\",\"quarter\")\r\n if (ganttPlanningScale) {\r\n g.setFormat(ganttPlanningScale);\r\n }\r\n g.setStartDateView(startDateView);\r\n g.setEndDateView(endDateView);\r\n if (dijit.byId('criticalPathPlanning')) g.setShowCriticalPath(dijit.byId('criticalPathPlanning').get('checked'));\r\n var contentNode = dojo.byId('gridContainerDiv');\r\n if (contentNode) {\r\n g.setWidth(dojo.style(contentNode, \"width\"));\r\n }\r\n jsonData = dojo.byId('planningJsonData');\r\n if (jsonData.innerHTML.indexOf('{\"identifier\"') < 0 || jsonData.innerHTML.indexOf('{\"identifier\":\"id\", \"items\":[ ] }')>=0) {\r\n if (dijit.byId('leftGanttChartDIV')) dijit.byId('leftGanttChartDIV').set('content',null);\r\n if (dijit.byId('rightGanttChartDIV')) dijit.byId('rightGanttChartDIV').set('content',null);\r\n if (dijit.byId('topGanttChartDIV')) dijit.byId('topGanttChartDIV').set('content',null); \r\n if (jsonData.innerHTML.length > 10 && jsonData.innerHTML.indexOf('{\"identifier\":\"id\", \"items\":[ ] }')<0) {\r\n showAlert(jsonData.innerHTML);\r\n }\r\n hideWait();\r\n return;\r\n }\r\n var now = formatDate(new Date());\r\n // g.AddTaskItem(new JSGantt.TaskItem( 0, 'project', '', '', 'ff0000', '',\r\n // 0, '', '10', 1, '', 1, '' , 'test'));\r\n if (g && jsonData) {\r\n var store = eval('(' + jsonData.innerHTML + ')');\r\n var items = store.items;\r\n // var arrayKeys=new Array();\r\n var keys = \"\";\r\n for (var i = 0; i < items.length; i++) {\r\n var item = items[i];\r\n // var topId=(i==0)?'':item.topid;\r\n var topId = item.topid;\r\n // pStart : start date of task\r\n var pStart = now;\r\n var pStartFraction = 0;\r\n pStart = (trim(item.initialstartdate) != \"\") ? item.initialstartdate\r\n : pStart;\r\n pStart = (trim(item.validatedstartdate) != \"\") ? item.validatedstartdate\r\n : pStart;\r\n pStart = (trim(item.plannedstartdate) != \"\") ? item.plannedstartdate\r\n : pStart;\r\n pStart = (trim(item.realstartdate) != \"\") ? item.realstartdate : pStart;\r\n pStart = (trim(item.plannedstartdate)!=\"\" && trim(item.realstartdate) && item.plannedstartdate<item.realstartdate)?item.plannedstartdate:pStart;\r\n if (trim(item.plannedstartdate) != \"\" && trim(item.realenddate) == \"\") {\r\n pStartFraction = item.plannedstartfraction;\r\n }\r\n // If real work in the future, don't take it in account\r\n if (trim(item.plannedstartdate) && trim(item.realstartdate)\r\n && item.plannedstartdate < item.realstartdate\r\n && item.realstartdate > now) {\r\n pStart = item.plannedstartdate;\r\n }\r\n // pEnd : end date of task\r\n var pEnd = now;\r\n //var pEndFraction = 1;\r\n pEnd = (trim(item.initialenddate) != \"\") ? item.initialenddate : pEnd;\r\n pEnd = (trim(item.validatedenddate) != \"\") ? item.validatedenddate : pEnd;\r\n pEnd = (trim(item.plannedenddate) != \"\") ? item.plannedenddate : pEnd;\r\n\r\n pRealEnd = \"\";\r\n pPlannedStart = \"\";\r\n pWork = \"\";\r\n if (dojo.byId('resourcePlanning')) {\r\n pRealEnd = item.realenddate;\r\n pPlannedStart = item.plannedstartdate;\r\n pWork = item.leftworkdisplay;\r\n g.setSplitted(true);\r\n } else {\r\n pEnd = (trim(item.realenddate) != \"\") ? item.realenddate : pEnd;\r\n }\r\n if (pEnd < pStart)\r\n pEnd = pStart;\r\n //\r\n var realWork = parseFloat(item.realwork);\r\n var plannedWork = parseFloat(item.plannedwork);\r\n var validatedWork = parseFloat(item.validatedwork);\r\n var progress = 0;\r\n if (item.isglobal && item.isglobal==1 && item.progress) { \r\n progress=item.progress;\r\n } else {\r\n if (plannedWork > 0) {\r\n progress = Math.round(100 * realWork / plannedWork);\r\n } else {\r\n if (item.done == 1) {\r\n progress = 100;\r\n }\r\n }\r\n }\r\n // pGroup : is the task a group one ?\r\n var pGroup = (item.elementary == '0') ? 1 : 0;\r\n //MODIF qCazelles - GANTT\r\n if (item.reftype=='Project' || item.reftype=='Fixed' || item.reftype=='Replan' || item.reftype=='Construction' || item.reftype=='ProductVersionhasChild' || item.reftype=='ComponentVersionhasChild' ) pGroup=1;\r\n //END MODIF qCazelles - GANTT\r\n // runScript : JavaScript to run when click on task (to display the\r\n // detail of the task)\r\n var runScript = \"runScript('\" + item.reftype + \"','\" + item.refid + \"','\"+ item.id + \"');\";\r\n var contextMenu = \"runScriptContextMenu('\" + item.reftype + \"','\" + item.refid + \"','\"+ item.id + \"');\";\r\n // display Name of the task\r\n var pName = ((showWBS) ? item.wbs : '') + \" \" + item.refname; // for\r\n // testeing\r\n // purpose, add\r\n // wbs code\r\n // var pName=item.refname;\r\n // display color of the task bar\r\n var pColor = (pGroup)?'003000':'50BB50'; // Default green\r\n if (! pGroup && item.notplannedwork > 0) { // Some left work not planned : purple\r\n pColor = '9933CC';\r\n } else if (trim(item.validatedenddate) != \"\" && item.validatedenddate < pEnd) { // Not respected constraints (end date) : red\r\n if (item.reftype!='Milestone' && ( ! item.assignedwork || item.assignedwork==0 ) && ( ! item.leftwork || item.leftwork==0 ) && ( ! item.realwork || item.realwork==0 )) {\r\n pColor = (pGroup)?'650000':'BB9099';\r\n } else {\r\n pColor = (pGroup)?'650000':'BB5050';\r\n }\r\n } else if (! pGroup && item.reftype!='Milestone' && ( ! item.assignedwork || item.assignedwork==0 ) && ( ! item.leftwork || item.leftwork==0 ) && ( ! item.realwork || item.realwork==0 ) ) { // No workassigned : greyed green\r\n pColor = 'aec5ae';\r\n }\r\n \r\n if (item.redElement == '1') {\r\n pColor = 'BB5050';\r\n }\r\n else if(item.redElement == '0') {\r\n pColor = '50BB50';\r\n } \r\n \r\n // pMile : is it a milestone ? \r\n var pMile = (item.reftype == 'Milestone') ? 1 : 0;\r\n if (pMile) {\r\n pStart = pEnd;\r\n }\r\n pClass = item.reftype;\r\n pId = item.refid;\r\n pScope = \"Planning_\" + pClass + \"_\" + pId;\r\n pOpen = (item.collapsed == '1') ? '0' : '1';\r\n var pResource = item.resource;\r\n var pCaption = \"\";\r\n if (dojo.byId('listShowResource')) {\r\n if (dojo.byId('listShowResource').checked) {\r\n pCaption = pResource;\r\n }\r\n }\r\n if (dojo.byId('listShowLeftWork')\r\n && dojo.byId('listShowLeftWork').checked) {\r\n if (item.leftwork > 0) {\r\n pCaption = item.leftworkdisplay;\r\n } else {\r\n pCaption = \"\";\r\n }\r\n }\r\n var pDepend = item.depend;\r\n topKey = \"#\" + topId + \"#\";\r\n curKey = \"#\" + item.id + \"#\";\r\n if (keys.indexOf(topKey) == -1) {\r\n topId = '';\r\n }\r\n keys += \"#\" + curKey + \"#\";\r\n g.AddTaskItem(new JSGantt.TaskItem(item.id, pName, pStart, pEnd, pColor,\r\n runScript, contextMenu, pMile, pResource, progress, pGroup, \r\n topId, pOpen, pDepend,\r\n pCaption, pClass, pScope, pRealEnd, pPlannedStart,\r\n item.validatedworkdisplay, item.assignedworkdisplay, item.realworkdisplay, item.leftworkdisplay, item.plannedworkdisplay,\r\n item.priority, item.planningmode, \r\n item.status, item.type, \r\n item.validatedcostdisplay, item.assignedcostdisplay, item.realcostdisplay, item.leftcostdisplay, item.plannedcostdisplay,\r\n item.baseTopStart, item.baseTopEnd, item.baseBottomStart, item.baseBottomEnd, item.isoncriticalpath));\r\n }\r\n g.Draw();\r\n g.DrawDependencies();\r\n } else {\r\n // showAlert(\"Gantt chart not defined\");\r\n return;\r\n }\r\n highlightPlanningLine();\r\n}", "function onSchedule_() {\n FormApp.getUi().showModalDialog(\n HtmlService.createHtmlOutputFromFile(\"Main\").setWidth(600).setHeight(675), \"Schedule\");\n}", "function printSchedule() {\n var win=window.open();\n win.document.write(\"<head><title>My Class Schedule</title>\");\n win.document.write(\"<style> img { border: 2.5px solid gray; } h1 { font-family: 'Arial'; }</style></head>\");\n win.document.write(\"<body><h1 style='text-align: center; width: 1080;'>\"+_schedule+\"</h1>\");\n win.document.write(\"<img src='\"+_canvas.toDataURL()+\"'></body>\");\n win.print();\n win.close();\n }", "function showBoards(){\r\n tbl.innerHTML=\"\"\r\n GetWorkflow(2)\r\n /*\r\n var board_title=document.createElement(\"span\")\r\n board_title.className=\"board-title\"\r\n board_title.appendChild(document.createTextNode(\"TO DO\"))\r\n var board_panel=document.createElement(\"div\")\r\n board_panel.className=\"board-elements-container panel\"\r\n var board_element=document.createElement(\"div\")\r\n board_element.className=\"board-element\"\r\n var eletitle=document.createElement(\"h4\")\r\n eletitle.className=\"element-title\"\r\n board_panel.appendChild(eletitle)\r\n eletitle.appendChild(document.createTextNode(\"Statement of Changes in Equity\"))\r\n */\r\n \r\n}", "function FloatingDaily() \n{\n\n this.window = new Window(\"floatingDaily\", data.storage);\n \n // Add css style for report window\n GM_addStyle(\"#floatingDaily {border: 2px solid #000000; position: fixed; z-index: 100; \" +\n\t\t\"color: #000000; background-color: #FFFFFF; padding: 5; text-align: left; \" +\n\t\t\"overflow-y: auto; overflow-x: auto; width: 200; height: 500; \" +\n\t\t\"background: none repeat scroll 0% 0% rgb(216, 216, 216);}\");\n\n this.Draw = function()\n {\n\t// Test whether the daily window should be drawn on this page\n\tif (data.TestHidePage(location.href))\n\t{\n\t this.Hide();\n\t return;\n\t}\n\n\t// Show the window if not already\n\tthis.window.show();\n\n\t// Helper array to build the HTML\n\tvar arr = new Array();\n\t\n\tarr.push('<table width=\"200\"><tr><td align=\"left\">Daily Helper</td>',\n\t\t '<td align=\"right\"><p style=\"margin: 0pt; text-align: right;\">',\n\t\t '<a href=\"javascript:void(0)\" id=\"DailyHidePageButton\">',\n\t\t '(Hide)</a></p></td></tr></table><br>');\n\n\tarr.push(\"Sequence: <b>\" + data.sequenceName + \"</b><br><br>\");\n\t\n\tarr.push('<table width=\"200\"><tr><td align=\"left\">',\n\t\t '<a href=\"javascript:void(0)\" id=\"DailyBackTaskButton\">',\n\t\t '&lt;-----</a></td>');\n\n\tarr.push('<td align=\"center\"><b>' + data.taskNum + '</b> / ' + (data.taskList.length-1) + '</td>');\n\n\tarr.push('<td align=\"right\"><a href=\"javascript:void(0)\" id=\"DailySkipTaskButton\">',\n\t\t '-----&gt;</a></td></tr></table><br>');\n\t\n\tif (data.taskNum > 0 && data.taskNum < data.taskList.length)\n\t arr.push('Task: <b>' + data.taskList[data.taskNum].taskname + '</b>');\n\telse\n\t arr.push('Task: Undefined Task');\n\n\tarr.push('<br><br><div id=\"DailyMsgDiv\"></div><br><br>');\n\n\tarr.push('Your sequences:');\n\t\n\t// Generate list of sequence options to choose from\n\tfor (var i=0; i<data.sequenceList.length; i++)\n\t{\n\t var sequenceName = data.sequenceList[i];\n\n\t arr.push('<p style=\"margin: 0pt; text-align: right;\">',\n\t\t '<a href=\"javascript:void(0)\" val=\"' + sequenceName,\n\t\t '\" id=\"ChooseSequenceButton_' + sequenceName + '\">',\n\t\t sequenceName + ' &gt;</a></p>');\n\t}\n\n\tarr.push('<br><p style=\"margin: 0pt; text-align: left;\">',\n\t\t '<a href=\"javascript:void(0)\" id=\"DailySequenceEditorButton\">',\n\t\t '&lt; Open Sequence Editor</a></p>');\n\n\tarr.push('<br><p style=\"margin: 0pt; text-align: left;\">',\n\t\t '<a href=\"https://docs.google.com/leaf?id=0B10D12_4U2KiNzYxZjY0YTEtYzU1Mi00Y2YzLTg5NGYtYWZlNGQzMDQyNDE0&hl=en\" id=\"MoreSequencesButton\" target=\"_blank\">',\n\t\t '&lt; Get More Sequences</a></p>');\n\n//\tarr.push(\"<b>Flags</b>:\");\n//\tarr.push(data.flagStr.replace(/\\|/g, \"<br>\"));\n\t\n\t// Concatenate everything in the array to form the html\n\tthis.window.element.innerHTML = arr.join(\"\");\n\n\t// Event handlers for sequenceList items\n\tfor (var i=0; i<data.sequenceList.length; i++)\n\t{\n\t var sequenceName = data.sequenceList[i];\n\n\t var elem = document.getElementById(\"ChooseSequenceButton_\" + sequenceName);\n\t elem.addEventListener(\"click\", function() { data.LoadSequence(this.id.split(\"_\")[1]); data.SaveState(); floatingDaily.Draw(); }, false);\n\t}\n\n\tdocument.getElementById(\"DailyHidePageButton\").addEventListener(\"click\", floatingDaily.HidePage, true);\n//\tdocument.getElementById(\"DailyResetDataButton\").addEventListener(\"click\", floatingDaily.ResetData, true);\n\tdocument.getElementById(\"DailySkipTaskButton\").addEventListener(\"click\", floatingDaily.SkipTask, true);\n\tdocument.getElementById(\"DailyBackTaskButton\").addEventListener(\"click\", floatingDaily.BackTask, true);\n\tdocument.getElementById(\"DailySequenceEditorButton\").addEventListener(\"click\", floatingDaily.OpenSequenceEditor, true);\n }\n\n // Hide the window (and remove the interior)\n this.Hide = function()\n {\n\tthis.window.element.innerHTML = \"\";\n\tthis.window.hide();\n }\n\n this.showErr = function(err)\n {\n\tdocument.getElementById(\"DailyMsgDiv\").innerHTML += err.message;\n }\n\n this.HidePage = function()\n {\n\tdata.AddHidePage(location.href);\n\tfloatingDaily.Hide();\n }\n\n this.ResetData = function()\n {\n\tdata.taskNum = 1;\n\tdata.flagStr = \"|\";\n\tdata.SaveState();\n\tfloatingDaily.Draw();\n }\n\n this.SkipTask = function()\n {\n\tIncrementTask();\n }\n\n this.BackTask = function()\n {\n\t// Temporary for debugging\n\tif (data.taskNum > 1)\n\t data.taskNum--;\n\tdata.SaveState();\n\tfloatingDaily.Draw();\n }\n\n this.OpenSequenceEditor = function()\n {\n\t// Disable hotkeys\n\thotkeyLock = true;\n\n\t// Initialize the Editor window if not already\n\tfloatingEditor.Draw();\n\n\t// Load the current sequence if it exists\n\tif (data.TestSequence(data.sequenceName))\n\t floatingEditor.LoadSequence(data.sequenceName);\n\n\t// Show the editor window\n\tfloatingEditor.window.show();\n }\n}", "function schedulePlan()\r\n{\r\n\tvar url = \"scheduled\";\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\r\n\tsectionName = objAjax.getDivSectionId();\r\n\t//alert(\"sectionName \" + sectionName);\r\n\tif(objAjax && objHTMLData)\r\n\t{\r\n\t\tif(!isValidRecord(true))\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tbShowMsg = true;\r\n\t Main.loadWorkArea(\"techspecevents.do\", url);\t \r\n\t}\r\n}", "function show_traj() {\n var traj_obj = editor.getValue();\n var traj = JSON.stringify(traj_obj, null, \" \");\n var scriptwin = window.open(\"\", \"_blank\");\n scriptwin.traj_obj = traj_obj;\n scriptwin.document.title = \"Trajectory: \";\n var code = scriptwin.document.createElement('pre');\n scriptwin.document.body.appendChild(code);\n code.innerHTML = traj;\n return scriptwin\n }", "function getReferralByProfessionTimeFrameChart(){\n\t\t$('#referralByProfessionWait').show();\n\t\tgetParamsForTimeFrame();\n\t\t$.ajax({\n\t\t\turl: referralByProfessionUrl+'TimeFrame',\n\t context: document.body,\n\t method: \"POST\",\n\t data: { search_entity: searchEntity, from_time_val: fromTimeVal, to_time_val: toTimeVal },\n\t success: function(response){\n\t $('#referralByProfessionWait').hide();\n\t $('#referralByProfessionChart').html(response);\n\t }});\n\t}", "createHTMLtask() {\n const htmlstring = '<div class=\"task\" draggable=\"true\" id=\"' + this.id + '\" ondragstart=\"drag(event)\" ondrop=\"drop(event)\" ondragover=\"allowDrop(event)\">' +\n '<big><strong>' + this.name + \" \" + '</strong></big>' +\n this.date.replace('T', ' ').substring(0, 19) +\n '<button id=\"' + this.id + '\" onClick=\"viewTask(this.id)\"' + ' class=\"view\" type=\"button\">&#128065;</button>' +\n this.priorityButton() + '<br><br>' +\n \"<p>\" + this.minimizeDescription() +\n this.changePhaseButton() +\n '<p>Assignee: ' + this.assignee + '..........Priority: ' + this.priority + '</p>' +\n '</div><br><br><br><br><br>';\n\n return htmlstring;\n }", "function DisplayEraFrame(eraLink, current_document, current_window)\r\n\t{\r\n\t\tcurrent_document.write('<iframe name=\"era_relatedLinks\" width='+GetEraBlockWidth(current_window)+\" height=\"+GetEraBlockHeight(current_window)+' frameborder=0 src='+ eraLink +' marginwidth=\"0\" marginheight=\"0\" vspace=\"0\" hspace=\"0\" allowtransparency=\"true\" scrolling=\"no\">');\r\n\t\tcurrent_document.write(\"</iframe>\");\r\n\t}", "toHtml()\n\t{\n //to finish \n var answer = '<div class=\"student-project-panel\"><div class=\"personal-row\"> <h3>' \n\t\t+ this.name + '</h3><span class=\"'+ map_dot[this.status]+'\"></span></div></div>'\n\t\treturn answer;\n\t}", "function start() {\n var timelineHolder = document.getElementById(\"schedule-graph\");\n var timeline = new google.visualization.Timeline(timelineHolder);\n var dataTable = prepareDataTable();\n\n timeline.draw(dataTable);\n}", "function ksPeekHw(iHwId , sTitle){\n var iframeurl = \"http://docs.google.com/gview?url=http://\"+ window.location.host + \"/filemanager/downloadhw/id/\"+ iHwId +\"&embedded=true\";\n $(\"#peeking_iframe\").html(\"\");\n $('<iframe />', {\n name: 'myFrame',\n id: 'myFrame',\n src: iframeurl,\n width: \"100%\",\n height: \"100%\"\n }).appendTo('#peeking_iframe');\n $('#glassnoloading').fadeIn('fast');\n $(\"#peeking\").css('display' , 'block');\n $('#peeking * h2').text(sTitle);\n}", "function getReferralStatusTimeFrameChart(){\n\t\t$('#referralStatusWait').show();\n\t\tgetParamsForTimeFrame();\n\t\t$.ajax({\n\t\t\turl: referralByStatusUrl+'TimeFrame',\n\t context: document.body,\n\t method: \"POST\",\n\t data: { search_entity: searchEntity, from_time_val: fromTimeVal, to_time_val: toTimeVal },\n\t success: function(response){\n\t $('#referralStatusWait').hide();\n\t $('#referralStatusChart').html(response);\n\t }});\n\t}", "function showHistoryOfRelease(instituteID,instituteName,strProposalId,strVersionId)\n{\nvar str = \"/ICMR/app_srv/icmr/mm02/jsp/view_release_budget_history.jsp?instituteID=\"+instituteID+\"&isSingleInstitute=yes&instituteName=\"+instituteName+\"&strProposalId=\"+strProposalId+\"&strVersionId=\"+strVersionId; \n window.open(str, 'new', 'scrollbars,width=1100,height=450,top=175,left=175');\n\n}", "function refreshIFrame() {\n\tlet url = \"\";\n\tif(typeSelected === \"\") {\t// If standard, don't add a type GET Variable for simplicity\n\t\turl = genurl + \"?evt=\" + eventSelected + \"&year=\" + yearSelected;\n\t}\n\telse {\n\t\turl = genurl + \"?type=\" + typeSelected + \"&evt=\" + eventSelected + \"&year=\" + yearSelected;\n\t}\n\n\t// Fill the HTML attributes with the new URL (in various forms)\n\tdocument.getElementById(\"preview\").src = url;\n\tdocument.getElementById(\"url\").innerHTML = '<a href=\"' + url + '\">'+url+'</a>';\n\tdocument.getElementById(\"md\").innerText = \"![Jugend hackt \" + eventSelected + \" \" + yearSelected + \"](\" + url + \")\";\n}", "function generatePreview() {\n var ifrm = document.getElementById('preview');\n ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;\n ifrm.document.open();\n ifrm.document.write($scope.editHtml);\n ifrm.document.close();\n }", "function reporteeDevelopmentNeedListHTML(id, title, description, category, timeToCompleteBy, status){\n\tvar html = \" \\\n\t <div class='panel-group' id='dev-need-item-\"+id+\"'> \\\n\t <div class='panel panel-default' id='panel'> \\\n\t\t <input type='hidden' id='dev-need-status-\"+id+\"' value='\"+status+\"'> \\\n\t\t <input type='hidden' id='dev-need-category-id-\"+id+\"' value='\"+category+\"'> \\\n\t \t<div class='panel-heading'> \\\n\t \t<div class='row'> \\\n\t \t\t<div class='col-sm-6'> \\\n\t\t \t\t<div class='row'> \\\n\t\t\t \t\t<div class='col-sm-6' id='dev-need-no-\"+id+\"'><h6><b>#\"+id+\"</b></h6></div> \\\n\t\t\t \t\t<div class='col-sm-6' id='dev-need-date-\"+id+\"'><h6 class='pull-right'><b>\"+timeToCompleteBy+\"</b></h6></div> \\\n\t\t \t\t</div> \\\n\t\t \t\t<div class='row'> \\\n\t\t\t \t\t<div class='col-sm-12 wrap-text' id='dev-need-title-\"+id+\"'>\"+title+\"</div> \\\n\t\t \t\t</div> \\\n\t \t\t</div> \\\n\t \t\t<div class='col-sm-5 bs-wizard'> \\\n\t \t\t\t <div class='col-xs-4 bs-wizard-step complete' id='proposed-dev-need-dot-\"+id+\"'> \\\n\t\t\t\t\t\t <div class='text-center' id='test'><h6>Proposed</h6></div> \\\n\t\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t\t </div> \\\n\t\t\t\t\t\t <div class='col-xs-4 bs-wizard-step \"+ checkComplete(status, 1) +\"' id='started-dev-need-dot-\"+id+\"'> \\\n\t\t\t\t\t\t <div class='text-center'><h6>In-Progress</h6></div> \\\n\t\t\t\t\t\t <div class='progress'><div class='progress-bar'></div></div> \\\n\t\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t\t <div class='bs-wizard-dot-complete'></div> \\\n\t\t\t\t\t\t </div> \\\n\t\t\t\t\t\t <div class='col-xs-4 bs-wizard-step \"+ checkComplete(status, 2) +\"' id='complete-dev-need-dot-\"+id+\"'> \\\n\t\t\t\t\t\t <div class='text-center'><h6>Complete</h6></div> \\\n\t\t\t\t\t\t \t <div class='progress'><div class='progress-bar'></div></div> \\\n\t\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t\t <div class='bs-wizard-dot-complete'></div> \\\n\t\t\t\t\t\t </div> \\\n\t \t\t</div> \\\n\t \t\t<div class='col-sm-1 chev-height notUnderlined'> \\\n\t\t\t\t\t\t <a data-toggle='collapse' href='#collapse-dev-need-\"+id+\"' class='collapsed'></a> \\\n\t\t\t\t\t\t</div> \\\n\t \t</div> \\\n\t </div> \\\n\t <div id='collapse-dev-need-\"+id+\"' class='panel-collapse collapse'> \\\n\t <div class='panel-body'> \\\n\t <div class='row'> \\\n\t <div class='col-md-6'> \\\n\t <h5><b>Description</b></h5> \\\n\t </div> \\\n\t \t<div class='col-md-6' > \\\n\t \t<input type='hidden' id='dev-need-category-id-\"+id+\"' value='\" + category + \"'> \\\n\t\t <h6><b> Category: </b><span id='dev-need-category-\"+id+\"'>\" + categoryList[category] + \"</span></h6>\\\n\t\t </div> \\\n\t </div> \\\n\t <div class='row'> \\\n\t <div class='col-md-12 wrap-text'> \\\n\t <p id='dev-need-text-\"+id+\"'>\"+description+\"</p> \\\n\t </div> \\\n\t </div> \\\n\t </div> \\\n\t </div> \\\n\t \\\n\t </div> \\\n\t </div> \\\n\t \" \n return html;\n}", "function displayHTML() {\n \tvar preview_div = document.getElementById(\"preview_div\");\n \tpreview_div.style.display = \"none\";\n \tvar htmlcode_div = document.getElementById(\"htmlcode_div\");\n \thtmlcode_div.style.display = \"block\";\n }", "function DisplaySchedule()\n{\nHTMLCode = \"<table cellspacing=0 cellpadding=3 border=3 bgcolor=purple bordercolor=#000033>\";\nQueryDay = DefDateDay(QueryYear,QueryMonth,QueryDate);\nWeekRef = DefWeekNum(QueryDate);\nWeekOne = DefWeekNum(1);\nHTMLCode += \"<tr align=center><td colspan=8 class=Titre><b>\" + MonthsList[QueryMonth] + \" \" + QueryYear + \"</b></td></tr><tr align=center>\";\n\nfor (s=1; s<8; s++)\n{\nif (QueryDay == s) { HTMLCode += \"<td><b><font color=#ff0000>\" + DaysList[s] + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><b>\" + DaysList[s] + \"</b></td>\"; }\n}\n\nHTMLCode += \"<td><b><font color=#888888>Sem</font></b></td></tr>\";\na = 0;\n\nfor (i=(1-DefDateDay(QueryYear,QueryMonth,1)); i<MonthLength[QueryMonth]; i++)\n{\nHTMLCode += \"<tr align=center>\";\nfor (j=1; j<8; j++)\n{\nif ((i+j) <= 0) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse if ((i+j) == QueryDate) { HTMLCode += \"<td><b><font color=#ff0000>\" + (i+j) + \"</font></b></td>\"; }\nelse if ((i+j) > MonthLength[QueryMonth]) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse { HTMLCode += \"<td>\" + (i+j) + \"</td>\"; }\n}\n\nif ((WeekOne+a) == WeekRef) { HTMLCode += \"<td><b><font color=#00aa00>\" + WeekRef + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><font color=#888888>\" + (WeekOne+a) + \"</font></td>\"; }\nHTMLCode += \"</tr>\";\na++;\ni = i + 6;\n}\n\nCalendrier.innerHTML = HTMLCode + \"</table>\";\n}", "function showFlow() {\r\n\t\tif (issueheadPanel.selModel.hasSelection()) {\r\n\t\t\tvar record = issueheadPanel.getSelectionModel().getSelected();\r\n\t\t\tvar entryId = record.get(\"workFlowNo\");\r\n\t\t\tif (entryId == null) {\r\n\t\t\t\tExt.Msg.alert(\"提示\", \"流程未启动!\");\r\n\t\t\t} else {\r\n\t\t\t\tvar url = application_base_path + \"workflow/manager/show/show.jsp?entryId=\"\r\n\t\t\t\t\t\t+ entryId;\r\n\r\n\t\t\t\twindow.open(url);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tExt.Msg.alert(\"提示\", \"请先选择要查看的记录!\");\r\n\t\t}\r\n\t}", "function caricaFeedIframe(theUri,theHolder) {\n\t// qui faccio scaricare al browser direttamente il contenuto del feed come src dell'iframe.\n\ttheHolder.innerHTML = '<iframe src=\"' + theUri + '\" width=\"50%\" height=\"50px\">Il tuo browser non supporta gli iframe</iframe>';\n\t// non riesco tuttavia a intervenire per parsificarlo! è il browser che renderizza il src del iframe!\n}", "function reporteeObjectiveListHTML(id, title, description, timeToCompleteBy, status, isArchived){\n\tvar html = \" \\\n <div class='panel-group' id='objective-item-\"+id+\"'> \\\n <div class='panel panel-default' id='panel'> \\\n <input type='hidden' id='obj-status-\"+id+\"' value='\"+status+\"'> \\\n <input type='hidden' id='obj-is-archived-\"+id+\"' value='\"+isArchived+\"'> \\\n \t<div class='panel-heading'> \\\n \t<div class='row'> \\\n \t\t<div class='col-sm-6'> \\\n\t \t\t<div class='row'> \\\n\t\t \t\t<div class='col-sm-6' id='obj-no-\"+id+\"'><h6><b>#\"+id+\"</b></h6></div> \\\n\t\t \t\t<div class='col-sm-6' id='obj-date-\"+id+\"'><h6 class='pull-right'><b>\"+timeToCompleteBy+\"</b></h6></div> \\\n\t \t\t</div> \\\n\t \t\t<div class='row'> \\\n\t\t \t\t<div class='col-sm-12 wrap-text' id='obj-title-\"+id+\"'>\"+title+\"</div> \\\n\t \t\t</div> \\\n \t\t</div> \\\n \t\t<div class='col-sm-5 bs-wizard'> \\\n \t\t\t <div class='col-xs-4 bs-wizard-step complete' id='proposed-obj-dot-\"+id+\"'> \\\n\t\t\t\t\t <div class='text-center' id='test'><h6>Proposed</h6></div> \\\n\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t </div> \\\n\t\t\t\t\t <div class='col-xs-4 bs-wizard-step \"+ checkComplete(status, 1) +\"' id='started-obj-dot-\"+id+\"'> \\\n\t\t\t\t\t <div class='text-center'><h6>In-Progress</h6></div> \\\n\t\t\t\t\t <div class='progress'><div class='progress-bar'></div></div> \\\n\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t <div class='bs-wizard-dot-complete'></div> \\\n\t\t\t\t\t </div> \\\n\t\t\t\t\t <div class='col-xs-4 bs-wizard-step \"+ checkComplete(status, 2) +\"' id='complete-obj-dot-\"+id+\"'> \\\n\t\t\t\t\t <div class='text-center'><h6>Complete</h6></div> \\\n\t\t\t\t\t \t <div class='progress'><div class='progress-bar'></div></div> \\\n\t\t\t\t\t <div class='bs-wizard-dot-start'></div> \\\n\t\t\t\t\t <div class='bs-wizard-dot-complete'></div> \\\n\t\t\t\t\t </div> \\\n \t\t</div> \\\n \t\t<div class='col-sm-1 chev-height notUnderlined'> \\\n\t\t\t\t\t <a data-toggle='collapse' href='#collapse-obj-\"+id+\"' class='collapsed'></a> \\\n\t\t\t\t\t</div> \\\n \t</div> \\\n </div> \\\n \\\n <div id='collapse-obj-\"+id+\"' class='panel-collapse collapse'> \\\n \\\n <div class='panel-body'> \\\n <div class='row'> \\\n <div class='col-md-4'> \\\n <h5><b>Description</b></h5> \\\n </div> \\\n <div class='col-md-8'> \\\n </div> \\\n </div> \\\n <div class='row'> \\\n <div class='col-md-12 wrap-text'> \\\n <p id='obj-text-\"+id+\"'>\"+description+\"</p> \\\n </div> \\\n </div> \\\n </div> \\\n </div> \\\n \\\n </div> \\\n </div> \\\n \"; \n return html;\n}", "function showDeadline(deadline) {\n //get elems from page\n const day = document.querySelector('[data-date=\"day\"]'),\n dateOfMonth = document.querySelector('[data-date=\"date\"]'),\n month = document.querySelector('[data-date=\"month\"]'),\n year = document.querySelector('[data-date=\"year\"]'),\n hours = document.querySelector('[data-date=\"hours\"]'),\n minutes = document.querySelector('[data-date=\"minutes\"]');\n\n \n //form date from deadline\n const date = new Date(deadline);\n //get needed values from date\n const deadlineDay = date.toLocaleString(\"en-en\", { weekday: \"long\" }), // alternative old method - days[date.getDay()] from const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];\n deadlineDate = date.getDate(),\n deadlineMonth = date.toLocaleString(\"en-en\", { month: \"long\" }),\n deadlineYear = date.getFullYear(),\n deadlineHours = date.getHours(),\n deadlineMinutes = date.getMinutes();\n\n //put this values in html\n day.textContent = deadlineDay;\n dateOfMonth.textContent = deadlineDate;\n month.textContent = deadlineMonth;\n year.textContent = deadlineYear;\n hours.textContent = deadlineHours;\n minutes.textContent = deadlineMinutes;\n\n }", "function renderInIframe(content) {\n let iFrame = document.getElementById('results-window');\n iFrame = iFrame.contentWindow || iFrame.contentDocument.document || iFrame.contentDocument;\n iFrame.document.open();\n iFrame.document.write(content);\n iFrame.document.close();\n}", "function loadJavascript(jobId, container, openInNewWindow) {\n $(\"table.group\").hide();\n $(\"#systemAlertMessage\").hide();\n\n // Abort if there is no job id\n if (jobId === undefined || jobId === null || jobId === '') {\n return;\n }\n\n var openVisualizers = getURLParameter(\"openVisualizers\");\n\n // if open visualizer is false then user most likely\n // intends to open job status page\n /*if (!openVisualizers) {\n return;\n }*/\n\n $.ajax({\n type: \"GET\",\n url: \"/gp/rest/v1/jobs/\" + jobId,\n cache: false,\n success: function(data) {\n var job = data;\n if (job.launchUrl !== undefined && job.launchUrl !== null) {\n\n if (!openInNewWindow)\n {\n // Add to history so back button works\n var visualizerAppend = \"&openVisualizers=true\";\n if(openVisualizers != null)\n {\n visualizerAppend = \"&openVisualizers=\" + openVisualizers;\n }\n\n history.pushState(null, document.title, location.protocol + \"//\" + location.host + location.pathname + \"?jobid=\" + jobId + visualizerAppend);\n\n cleanUpPanels();\n\n //destroy the gpJavascript plugin if already initialized\n if(container.is( \":data('gpJavascript')\" ))\n {\n container.gpJavascript(\"destroy\");\n }\n container.gpJavascript({\n taskName: job.taskName,\n taskLsid: job.taskLsid,\n jobId: job.jobId,\n url: job.launchUrl //The URL to the main javascript html file\n });\n mainLayout.close('west');\n }\n else\n {\n window.open(\"/gp/pages/jsViewer.jsf?jobNumber=\" + job.jobId);\n }\n }\n },\n error: function(data) {\n if (typeof data === 'object') {\n data = data.responseText;\n }\n\n showErrorMessage(data);\n },\n dataType: \"json\"\n });\n}", "function networkingVideo() {\n var iframe = document.createElement('iframe');\n var h2 = document.createElement('h2');\n h2.innerHTML = \"Submission Video\";\n h2.style.marginTop = \"100px\";\n iframe.setAttribute('src', 'https://drive.google.com/file/d/130e73-bmEyUzndj14dnz84-nwSfrIZFj/preview');\n iframe.setAttribute('height', '600');\n iframe.setAttribute('width', '800');\n const div = document.getElementById(\"networkingDiv\");\n while (div.firstChild) {\n div.firstChild.remove();\n }\n document.getElementById(\"networkingDiv\").appendChild(h2);\n document.getElementById(\"networkingDiv\").appendChild(iframe);\n}", "function getContentIframe(cont_html){\n\t$(\"#fb_disclaimer\").remove();\n\tif($(\"#lcom_pop #social_connect input[name=submitComplete]\").length > 0){\n\t\t$(\"#lcom_pop \").html(cont_html);\n\t}else {\n\t\t$(\"#lcom_pop #ajax_container\").html(cont_html);\n\t}\n\tif($(\"#ajax_container #fb_disclaimer\").length > 0){\n\t\t$(\"#social_connect .box_socialn\").after($(\"#ajax_container #fb_disclaimer\"));\n\t}\n\t$(\"#lcom_pop #social_connect .clearSN img.waitBT\").remove();\n\tif($(\"#lcom_pop .container_socialn #registrazione-social-err\").length > 0){\n\t\t$(\"#lcom_pop .container_socialn\").prepend($(\"#lcom_pop .container_socialn #registrazione-social-err\"));\n\t}\n\tsetFBoption();\n}", "function add_html() {\n\t\tdocument.getElementById(\"whole_month\").innerHTML=table_html;\n\t}", "function hvc_showList(url) {\r\n\tvar iframe = parent.document.getElementById(\"nyroModalIframe\");\r\n\tiframe.src = url;\r\n}", "function createIframe(authToken) {\n // //////////////////// IFRAME CREATION ////////////////////////////////////\n const formIframe = document.createElement('iframe');\n // append to body\n const parent = document.getElementById(parentId);\n parent.appendChild(formIframe);\n\n // add attr to the iframe\n // formIframe.frameBorder = '0'; this is obsolet\n // formIframe.scrolling = 'no'; this has been deprecated\n // formIframe.style = 'border:0; overflow:hidden;';\n formIframe.frameBorder = '0';\n formIframe.scrolling = 'no';\n formIframe.title = 'Consolidated Credit Callback Scheduler';\n formIframe.id = 'callbackScheduler';\n formIframe.sandbox = 'allow-forms allow-scripts allow-same-origin allow-popups';\n\n // Dcom URL: https://ewc.debt.com/fef/\n // eslint-disable-next-line prettier/prettier\n formIframe.src = `https://resources.venturetechsolutions.com/iframes/callback-scheduler?pageUrl=${clientUrl}&pageDomain=${clientDomain}&ip_address=${ip_address}&twoColumn=${twoColumn}&language=${language}&token=${authToken.token}&bordered=${bordered}&formBackground=${formBackground}&fontColor=${fontColor}&calendarColorON=${calendarColorON}&calendarColorOFF=${calendarColorOFF}&calendarColorHOVER=${calendarColorHOVER}&calendarColorACTIVE=${calendarColorACTIVE}&calendarColorLines=${calendarColorLines}&btnCTANormalColor=${btnCTANormalColor}&btnCTAHoveredColor=${btnCTAHoveredColor}&btnCTAFontColor=${btnCTAFontColor}&fieldsBorderColor=${fieldsBorderColor}&timeLaps=${timeLaps}&numberOfDays=${numberOfDays}&daysOff=${JSON.stringify(daysOff)}&sun=${JSON.stringify(sun)}&mon=${JSON.stringify(mon)}&tue=${JSON.stringify(tue)}&wed=${JSON.stringify(wed)}&thu=${JSON.stringify(thu)}&fri=${JSON.stringify(fri)}&sat=${JSON.stringify(sat)}&source=${source}&name=${name}&lastname=${lastname}&phone=${phone}&email=${email}`;\n\n // Remove Loading\n removeLoading();\n }", "function actualPlan()\r\n{\r\n\tvar url = \"actual\";\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\r\n\tsectionName = objAjax.getDivSectionId();\r\n\t//alert(\"sectionName \" + sectionName);\r\n\tif(objAjax && objHTMLData)\r\n\t{\r\n\t if(!isValidRecord(true))\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tbShowMsg = true;\r\n\t Main.loadWorkArea(\"techspecevents.do\", url);\t \r\n\t}\r\n}", "function exportToExcel() {\n var fE = document.getElementById(\"iFgfrm\");\n if (fE == null) {\n fE = document.createElement(\"IFRAME\");\n fE.id = \"iFgfrm\"\n fE.scrolling = \"no\";\n fE.frameborder = \"0\";\n fE.width = \"100\";\n fE.height = \"100\";\n document.body.appendChild(fE);\n hideDiv(\"iFgfrm\");\n }\n fE.src = currentURL() + \"&ifgActivityId=\" + getQStr(\"activityid\") + \"&Export=True\";\n return;\n}", "function doExcelExport() {\n\tvar elemIF = document.createElement(\"iframe\");\n\telemIF.src = \"/hiwi/Clerk/js/doExcelExport\";\n\telemIF.style.display = \"none\";\n\tdocument.body.appendChild(elemIF);\n}", "function showFlyout()\r\n{\r\n\tif ( flyoutIndex >= projects.length )\r\n\t{\r\n\t\tSystem.Gadget.Flyout.show = false;\r\n\t\treturn true;\r\n\t}\r\n\tSystem.Gadget.Flyout.file = \"Flyout.html\";\r\n\tSystem.Gadget.Flyout.show = true;\r\n}", "function showProject(project) {\n //show main content div\n projectContent.setAttribute(\"class\", \"projectContent show\");\n\n //if arrows are hidden then show\n if (!next.getAttribute(\"class\").includes(\"showArrow\")) {\n next.setAttribute(\"class\", \"arrow showArrow\");\n last.setAttribute(\"class\", \"arrow showArrow\");\n }\n\n if (project.title == \"\") {\n //if no title provided show dummy title\n contentTitle.innerHTML = \"My Project\"\n } else {\n contentTitle.innerHTML = project.title;\n }\n //Description\n if (project.description == \"\") {\n\n contentDescription.innerHTML = \"\"\n } else {\n contentDescription.innerHTML = \"<strong>Description: </strong><div class='text'>\" + project.description + \"</p>\";\n }\n //Time\n if (project.time_needed == \"\") {\n\n contentTime.innerHTML = \"\"\n } else {\n contentTime.innerHTML = \"<strong>Time needed: </strong><div class='text'>\" + project.time_needed + \"</p>\";\n }\n //Tech\n if (project.tech == \"\") {\n\n contentTech.innerHTML = \"\"\n } else {\n contentTech.innerHTML = \"<strong>Technologies used: </strong><div class='text'>\" + project.tech + \"</p>\";\n }\n //link\n if (project.link == \"\") {\n\n open.parentElement.setAttribute(\"style\",\"display:none\");\n open.setAttribute(\"href\",``);\n } else {\n open.parentElement.setAttribute(\"style\",\"\");\n open.setAttribute(\"href\",`${project.link}`);\n }\n //img\n if (project.image == \"\") {\n contentImg.setAttribute(\"style\", \"display:none\");\n } else {\n contentImg.setAttribute(\"style\", \"display:block; border-radius: 10px;\");\n contentImg.setAttribute(\"width\", project.imgWidth == \"\" ? \"320px\" : project.imgWidth);\n contentImg.setAttribute(\"height\", project.imgHeight == \"\" ? \"310px\" : project.imgHeight);\n contentImg.setAttribute(\"src\", project.image);\n }\n}", "async function getPreview() {\n var jobData = getJobData();\n\n previewData = await eel.getPreview(jobData)();\n previewData = JSON.parse(previewData);\n\n JSONtoTable(previewData, \"preview\");\n}", "function insertContentIFrame(width) {\n\t\tif (typeof(width)==\"undefined\") {\n\t\t\twidth = \"100%\";\n\t\t}\n\n\t\tvar s = \"\";\n\t\t\n\t\ts += createIframeHtml(\"main\", elemParams.CONTENTIFRAME, \"block\", width);\n\t\ts += createIframeHtml(\"mytemplate\", \"mytemplate\", \"none\", width);\n\n\t\tdocument.write(s);\n\t}", "function returnRenderContentForiFrame(html, css, javascript,\n externalString, htmlClass, htmlHead) {\n\n const template = `<html class=\"${htmlClass}\">\n <head>\n ${htmlHead}\n ${externalString}\n <style>${css}</style>\n </head>\n <body>${html}\n <script>${javascript}</script>\n </body>\n</html>`;\n\n return template;\n}", "function executeCode(e) {\n let frame = document.getElementById(\"explore-show\");\n let frameDoc =\n frame.contentWindow ||\n frame.contentDocument.document ||\n frame.contentDocument;\n let body = jar.toString();\n frameDoc.document.write(\n '<html><head><link rel=\"stylesheet\" href=\"style.css\"><style>body{padding:0.5em 9em;margin:6;}</style></head>' +\n body +\n \"</html>\"\n );\n frameDoc.document.close();\n}", "function renderHtml() {\n var template = settings.datasource.role === 'index' ? 'index' : 'datasource';\n settings.extensions = { Before: null, After: null };\n self._renderTemplate('triplepatternfragments/' + template, settings, request, response, done);\n }", "function showPreview(){\n\t$('#ce-side-event_date, #ce-side-time, #ce-side-title, #ce-side-speaker, #ce-side-bio, #ce-side-prelude, #ce-side-article, #ce-side-postlude, #ce-side-location, #ce-img-preview').show();\n}", "function onShowSchedule(){\n\tvar restriction = new Ab.view.Restriction();\n\trestriction.addClause(\"wr.wr_id\",$(\"wr.wr_id\").value,'=');\n\t\n\tView.openDialog(\"ab-helpdesk-workrequest-scheduling.axvw\",restriction);\n}", "function loadTimeline() {\n \t\t//Calls Google's API to retrieve all accessible calendars that have been prepended with Habitask's custom tag. In this case, all calendars created via Habitask are prepended with \"&c_\"\n\t \t\tgapi.client.load('calendar', 'v3', function() {\n\t \t\t\tvar calendarRequest = gapi.client.calendar.calendarList.list();\n\t\t \tcalendarRequest.execute(function(resp){\n\t\t \t\tcalendars.length=0;\n\t\t \t\tfor (var i=0;i<resp.items.length;i++) {\n\t\t \t\t\tif (resp.items[i].summary !== undefined) {\n \t\tif (resp.items[i].summary.substring(0, 3) == \"&c_\") {\n \t\t\t//Pushes each calendar to an object in the calendars array\n\t\t \t\t\t\t\tcalendars.push(new calendar(resp.items[i].summary.substring(3),resp.items[i].id));\n\t\t \t\t\t\t}\n\t\t \t\t\t}\n\t\t \t\t}\n\t\t \t\t//Displays the list of calendars in a drop down\n\t\t \t\t$('#plan-select').empty();\n\t\t \t\tfor (var i=0;i<calendars.length;i++)\n\t\t \t\t{\n\t\t \t\t\tif (i==curCalIndex)\n\t\t \t\t\t\t$('#plan-select').append('<option class=\"calselect\" selected value=\"'+i+'\" >'+calendars[i].name+'</option>');\n\t\t \t\t\telse \n\t\t \t\t\t\t$('#plan-select').append('<option class=\"calselect\" value=\"'+i+'\" >'+calendars[i].name+'</option>');\n\t\t \t\t}\n\t\t \t\t//Calls Google's API to retrieve all events from the current Calendar\n\t\t \t\tvar request = gapi.client.calendar.events.list({ 'calendarId': calendars[curCalIndex].id, 'orderBy': 'startTime', 'singleEvents': true });\n\n\t\t\t\t request.execute(function(resp) {\n\t\t\t\t \tif (resp.items)\n\t\t\t\t \t{\n\t\t\t\t \t\tevents.length=0;\n\t\t\t\t\t \tfor (var i = 0; i < resp.items.length; i++) {\n\t\t\t\t\t\t var parsedDate = new Date(resp.items[i].end.date);\n\t\t\t\t\t\t var curDate = new Date();\n\t\t\t\t\t\t if (curIndex==0 && parsedDate>=curDate)\n\t\t\t\t\t\t \tcurIndex = i;\n\t\t\t\t\t\t else\n\t\t\t\t\t\t \tcurIndex = 0;\n\t\t\t\t\t\t var fdate=(parsedDate.getMonth()+1)+'-'+(parsedDate.getDate()+1);\n\t\t\t\t\t\t if (resp.items[i].description && resp.items[i].description.search(\"&d_\"+user.email)!=-1)\n\t\t\t\t\t\t \tvar eventComplete = \"complete\";\n\t\t\t\t\t\t else \n\t\t\t\t\t\t \tvar eventComplete = \"ncomplete\";\n\t\t\t\t\t\t //Pushes each event to an object in the events array\n\t\t\t\t\t\t events[i] = new resource(resp.items[i].summary,resp.items[i].id,resp.items[i].location,resp.items[i].description,resp.items[i].start.date,fdate,eventComplete);\n\t\t\t\t\t \t}\n\t\t\t\t\t \tprintTimeline();\n\t\t\t\t \t}\n\t\t\t\t \telse\n\t\t\t\t \t\talert ('Calendar contains no Milestones');\n\t\t\t \t});\n\t\t \t});\n\n\t\t\t});\n\t\t}", "function playWallCreateIframe() {\n var iframe = document.createElement('iframe');\n iframe.id = 'playwall-frame';\n iframe.src = playwallLocationUrl;\n iframe.style.width = '300px';\n iframe.style.minHeight = '560px';\n iframe.style.border = '0';\n iframe.style.borderRadius = '10px';\n iframe.style.display = 'table';\n iframe.style.zIndex = '999';\n iframe.style.position = 'absolute';\n iframe.style.top = '50px';\n iframe.style.left = '0';\n iframe.style.right = '0';\n iframe.style.margin = '0 auto';\n document.body.appendChild(iframe);\n}", "function make_frame_content(rte) {\n\t var opt = rte.options,\n\t hd,\n\t bd = rte._input.val();\n\n\t if (opt.link) {\n\t hd = ('<link type=\"text/css\" rel=\"stylesheet\" href=\"'+ opt.link + '\" />');\n\t }\n\t else if (opt.style) {\n\t hd = ('<style type=\"text/css\">' + opt.style + '</style>');\n\t }\n\n\t bd = $.trim(bd) || '';\n\t return ('<html><head>' + hd + '</head><body class=\"frame\">' + bd + '</body></html>');\n }", "function displayPreview() {\n \tvar preview_div = document.getElementById(\"preview_div\");\n \tpreview_div.style.display = \"block\";\n \tvar htmlcode_div = document.getElementById(\"htmlcode_div\");\n \thtmlcode_div.style.display = \"none\";\n }", "function dateDisplay()\n{\nduration= opener.repDuration;\nrep_Period= opener.currRepEnd;\nweek=7;\ndate= new Date(curr_date);\nsel_day=date.getDate();\nend_date= getEndDate(date);\ndate.setDate(end_date);\nend_day=date.getDay();\ndate.setDate(1);\nstart_day=date.getDay();\nrow=0;\nend_week=week-end_day;\ndocument.writeln(\"<tr>\"); \nfor (var odday=0;odday<start_day;odday++,row++)\n{\ndocument.writeln(\"<td class='\"+css[3]+\"'>&nbsp;</td>\");\n}\n\nfor (var day=1;day<=end_date;day++,row++)\n{\nif(row == week)\n{\ndocument.writeln(\"</tr> <tr align='right'> \");\nrow=0;\n}\ndocument.writeln(\"<td class='\"+getCssClass(day,duration,date,rep_Period)+\"'>\");\n\nif(isWeekend(day,date))\n{\ndocument.writeln(day+\"</td>\");\n}\nelse{\ndocument.writeln(\"<a href='javascript:clickDatePeriod(\"+day+\",\"+date.getMonth()+\",\"+date.getFullYear()+\");' >\"+day+\"</a></td>\");\n}\n\n}\n\nfor (var end=0;end<(end_week-1);end++)\n{\ndocument.writeln(\"<td class='\"+css[3]+\"'>&nbsp;</td>\");\n}\ndocument.writeln(\"</tr>\"); \n}", "function refreshHtml(finishFunc) {\n getEventsAndDialogSettings(\n function getEventsAndDialogSettings_response(settings) {\n document.title = calGetString(\"calendar\", \"PrintPreviewWindowTitle\", [settings.title]);\n\n let printformatter = Components.classes[settings.layoutCId]\n .createInstance(Components.interfaces.calIPrintFormatter);\n let html = \"\";\n try {\n let pipe = Components.classes[\"@mozilla.org/pipe;1\"]\n .createInstance(Components.interfaces.nsIPipe);\n const PR_UINT32_MAX = 4294967295; // signals \"infinite-length\"\n pipe.init(true, true, 0, PR_UINT32_MAX, null);\n printformatter.formatToHtml(pipe.outputStream,\n settings.start,\n settings.end,\n settings.eventList.length,\n settings.eventList,\n settings.title);\n pipe.outputStream.close();\n // convert byte-array to UTF-8 string:\n let convStream = Components.classes[\"@mozilla.org/intl/converter-input-stream;1\"]\n .createInstance(Components.interfaces.nsIConverterInputStream);\n convStream.init(pipe.inputStream, \"UTF-8\", 0,\n Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);\n try {\n let portion = {};\n while (convStream.readString(-1, portion)) {\n html += portion.value;\n }\n } finally {\n convStream.close();\n }\n } catch (e) {\n Components.utils.reportError(\"Calendar print dialog:refreshHtml: \" + e);\n }\n\n let iframeDoc = document.getElementById(\"content\").contentDocument;\n iframeDoc.documentElement.innerHTML = html;\n iframeDoc.title = settings.title;\n\n if (finishFunc) {\n finishFunc();\n }\n }\n );\n}", "function viewReport( idCedulaNit, codigoCuenta, actualElement )\n{\n var childsT = actualElement.parentNode.parentNode.childNodes;\n \n var monthTD = childsT[ 1 ];\n \n var selectMonthSelect = monthTD.childNodes;\n \n var fechaExtracto = selectMonthSelect[ 0 ].options[ selectMonthSelect[ 0 ].selectedIndex ].value;\n \n //xhr = createXhr;\n \n document.getElementById('reportPlaceHolder').src = \"Extracto_Generar.jsp?codigoCuenta=\" + codigoCuenta + \"&idCedulaNit=\" + idCedulaNit + \"&fechaExtracto=\" + fechaExtracto;\n\n return false;\n} // end function viewReport", "function projectHtmlFromWorkshop(key, workshop){\n return'<div class=\"timeline-item\">'\n + '<p class=\"item-description\">'\n +workshop.wentry + '</p>'\n +'</div>';\n}", "function makeGeneralPage(sprSheet,recentReleases,oldORPDetails) {\n var milestones=releaseList()\n var pendingInfo=oldORPDetails['pending'] //these are the items left to add to the new meeting agenda\n \n var genSheet=sprSheet.getSheetByName(\"General\") //get the right sheet\n genSheet.clear() //remove any content already there\n\n // generic header information\n var nRow=1\n nRow=addRows(genSheet,[{'cols' : ['Welcome to the CMSSW release meeting'], 'isBold':true, 'fontSize':18 }],nRow);\n nRow=addBlankRows(genSheet,{'nRows':2},nRow)\n nRow=addRows(genSheet,[{'cols' : ['General information'], 'isBold':true, 'fontSize':16 }],nRow);\n nRow=addRows(genSheet,[{'cols' : ['Viydo'], \n 'forms' : ['=HYPERLINK(\"http://vidyoportal.cern.ch/flex.html?roomdirect.html&key=uFVZiCsN6DIb\",\"(Vidyo: Weekly_Offline_Meetings room, Extension: 9226777)\")'],\n 'fontSize':14 }],nRow);\n nRow=addBlankRows(genSheet,{'nRows':2},nRow)\n\n nRow=addRows(genSheet,[{'cols' : ['General topics'], 'fontSize':14 }],nRow); \n\n //add in releases created since the last CMSSW release meeting - one per line\n //in case this is recreation of a meeting page, any descriptions are retained\n //via the existingReleases information from the old ORP (which is not old in this case) \n nRow=addRows(genSheet,[{'cols' : ['Recent releases'], 'fontSize':14 }],nRow);\n nRow=addRows(genSheet,[{'cols' : ['Release name','Date created','Primary purpose'], 'fontSize': 12}],nRow); \n var nRowReleaseStart=nRow //cache for where and how many releases there are - needed to create the existingReleases info next time\n var savedReleaseInfo=oldORPDetails['existingReleases']\n\n //See if there is some notes about the releases to save\n for ( var rel in recentReleases) {\n releaseComment=\"To fill in\"\n for ( var i in savedReleaseInfo) {\n if ( i == recentReleases[rel][0] ) {\n releaseComment=savedReleaseInfo[recentReleases[rel][0]]\n }\n }\n //add a link to the release notes\n nRow=addRows(genSheet,[{'cols' : ['',readableDate(extractDate(recentReleases[rel][1])),releaseComment],\n 'forms':['=HYPERLINK(\"https://github.com/cms-sw/cmssw/releases/'+recentReleases[rel][0]+'\",\"'+recentReleases[rel][0]+'\")' ]}],nRow);\n }\n nRow=addBlankRows(genSheet,{'nRows':1},nRow)\n\n //list of general items for discussion (or items that don't fit elsewhere\n nRow=addRows(genSheet,[{'cols' : ['General items for discussion'], 'fontSize':14 }],nRow);\n var genRowTop=nRow\n if ( (pendingInfo['general'] != null) && (pendingInfo['general'].length > 0 )){\n for ( var i in pendingInfo['general']) {\n if ( pendingInfo['general'][i][1].substr(0,1) == \"=\" ) { //watch for hyperlinks that need to be treated separately\n nRow=addRows(genSheet,[{'cols': [pendingInfo['general'][i][0],''],\n 'forms': ['',pendingInfo['general'][i][1]],\n 'isBold':false, 'fontSize':10}],nRow)\n }\n else{ //handle hyperlinks\n nRow=addRows(genSheet,[{'cols': pendingInfo['general'][i], 'isBold':false, 'fontSize':10}],nRow)\n }\n genSheet.getRange(nRow-1,2).setFontSize(8)\n }\n }\n \n \n var genRow=nRow //cache for later\n nRow=nRow+1 //not sure why I did this - it seems to be the same as adding a blank line\n \n nRow=addBlankRows(genSheet,{'nRows':1},nRow)\n \n var saveRows=[]\n // now loop over the active releases and add a stanza in the agenda for each one\n for ( var r in milestones) {\n var m=milestones[r]\n var savedRow=[m]\n nRow=addBlankRows(genSheet,{'nRows':1,'color':'blue'},nRow)\n nRow=addRows(genSheet,[{'cols' : [m], 'isBold':true, 'fontSize':16 }],nRow); //title row\n savedRow.push(nRow)\n nRow=addRows(genSheet,[{'cols' : ['Pending issues'], 'isBold':true, 'fontSize':12 }],nRow); //Pending issues\n \n //now add the pending issues - watch for hyperlinks and handle them separately\n if ( (pendingInfo[m] != null) && (pendingInfo[m].length > 0 )){\n for ( var i in pendingInfo[m]) {\n if ( pendingInfo[m][i][1].substr(0,1) == \"=\" ) {\n nRow=addRows(genSheet,[{'cols': [pendingInfo[m][i][0],''],\n 'forms': ['',pendingInfo[m][i][1]],\n 'isBold':false, 'fontSize':10}],nRow)\n }\n else{\n nRow=addRows(genSheet,[{'cols': pendingInfo[m][i], 'isBold':false, 'fontSize':10}],nRow)\n }\n genSheet.getRange(nRow-1,2).setFontSize(8)\n }\n }\n savedRow.push(nRow)\n\n // Stanza for new external package requests for discussion\n nRow=addRows(genSheet,[{'cols' : ['External package requests'], 'isBold':true, 'fontSize':12 }],nRow);\n savedRow.push(nRow)\n\n // Stanza for new CMSSW requests for discussion\n nRow=addRows(genSheet,[{'cols' : ['CMSSW requests'], 'isBold':true, 'fontSize':12 }],nRow);\n savedRow.push(nRow)\n nRow=nRow+1\n \n saveRows.push(savedRow)\n }\n nRow=addBlankRows(genSheet,{'nRows':1,'color':'blue'},nRow)\n\n //done with release-by-release section. Finish with AOB section\n nRow=addRows(genSheet,[{'cols' : ['AOB'], 'fontSize':14 }],nRow);\n var aobRow=nRow\n saveRows.push(['Misc info',aobRow,genRow,genRowTop,recentReleases.length+\" from \"+nRowReleaseStart])\n nRow=nRow+1//buildAOBMenu(genSheet,nRow)\n nRow=addBlankRows(genSheet,{'nRows':1},nRow)\n\n //Done - now format sheet\n var range=genSheet.getRange(nRow,1,saveRows.length,5)\n range.setValues(saveRows)\n genSheet.getRange(1,1,genSheet.getLastRow(),5).setWrap(true)\n \n genSheet.hideRows(nRow,saveRows.length)\n nRow=nRow+saveRows.length\n Logger.log('Total general rows'+nRow)\n\n //hardwired column widths \n var pixNums=[40,170,150,250,250]\n for ( var i=0; i<pixNums.length; i++) {\n genSheet.setColumnWidth(i+1,pixNums[i])\n }\n\n //trim off the extra rows and columns\n if ( genSheet.getMaxRows() > nRow) {\n genSheet.deleteRows(nRow,genSheet.getMaxRows()-(nRow-1))\n }\n if ( genSheet.getMaxColumns() > 5 ) {\n genSheet.deleteColumns(6,genSheet.getMaxColumns()-5)\n }\n \n //only \"I\" can edit this page\n var me = Session.getEffectiveUser();\n var protection = genSheet.protect().setDescription('Sample protected range');\n protection.addEditor(me);\n protection.removeEditors(protection.getEditors());\n if (protection.canDomainEdit()) {\n protection.setDomainEdit(false);\n }\n \n\n return genSheet \n}", "function showCalenderManage(){\n loadData();\n var page = HtmlService.createHtmlOutputFromFile('TopCalenderManage'); \n var detailDiv = ''; //Variable to store html for right detail div\n var isAtLeastOneAdded = false;\n \n // Add dynamic HTML\n for(var i = 0; i < data.length; i++){\n if (!hasCalender(data[i][3])) {\n isAtLeastOneAdded = true; //Records that at least one club was added\n page.append(\n '<li><button class=\"tablinks\" onmouseover=\"openClub(event, \\'c'+data[i][0]+\n '\\')\"><input type = \"checkbox\" name = \"cal\" value=\"'+data[i][3]+'\">'+data[i][1]+'</button></li>');\n \n detailDiv = detailDiv + '<div id=\"c'+data[i][0]+'\" class=\"tabcontent\"><h3>'+data[i][1]+'</h3><p>'+data[i][2]+'</p></div>';\n }\n }\n if (!isAtLeastOneAdded) { page.append('<li>You are subscribed to all the calenders</li>') }\n page.append('</ul></div>');\n page.append(detailDiv);\n \n var bottom = HtmlService.createHtmlOutputFromFile('BottomCalenderManage'); //Load bottom of page\n page = page.append(bottom.getContent()); //Append bottom of page\n Logger.log(page.getContent());\n return page;\n}", "display(){\n this.htmlBuilder.build();\n this.displayCityName();\n this.displayTodayWeather();\n this.displayWeekWeather();\n this.displayTimeSlots();\n }", "function printTasks(projectsOfInterest) {\n\tconsole.log(\"PROJECTS OF INTEREST ==== \", projectsOfInterest);\n\tdocument.body.innerHTML=\"\";\n document.body.style.backgroundColor = \"white\";\n\tvar div = document.createElement(\"div\");\n\tdiv.id = \"insertTable\";\n\tvar title = document.createElement(\"h1\");\n\ttitle.innerHTML = \"Task Report\";\n\ttitle.align = 'center';\n\tvar table = document.createElement(\"Table\");\n\ttable.id = \"table\"\n table.class = \"table\";\n\ttable.border =\"1px solid black\";\n\t\n\t\n\tvar indexCol = document.createElement(\"col\");\n\tindexCol.style = \"width: 5%\";\n\tvar projCol = document.createElement(\"col\");\n\tprojCol.style =\"width: 15%\";\n\tvar taskCol = document.createElement(\"col\");\n\ttaskCol.style =\"width: 11%\";\n\tvar assigneeCol = document.createElement(\"col\");\n\tassigneeCol.style =\"width: 10%\";\n\tvar descriptionCol = document.createElement(\"col\");\n\tdescriptionCol.style =\"width: 25%\";\n\tvar createdCol = document.createElement(\"col\");\n\tcreatedCol.style =\"width: 11%\";\n\tvar dueCol = document.createElement(\"col\");\n\tdueCol.style =\"width: 11%\";\n\tvar priorityCol = document.createElement(\"col\");\n\tpriorityCol.style =\"width: 7%\";\n\tvar notesCol = document.createElement(\"col\");\n\tnotesCol.style =\"width: 25%\";\n\ttable.appendChild(indexCol);\n table.appendChild(projCol);\n table.appendChild(taskCol);\n table.appendChild(assigneeCol);\n table.appendChild(descriptionCol);\n table.appendChild(createdCol);\n table.appendChild(dueCol);\n table.appendChild(priorityCol);\n table.appendChild(notesCol);\n\t\n\tvar head = table.createTHead();\n\thead.id = \"tableHeader\";\n\tvar headRow = table.insertRow();\n\theadRow.id = \"head\";\n\tvar indexHead = document.createElement(\"th\");\n\tindexHead.innerHTML = \"Index\";\n\tindexHead.align = 'center';\n\tvar projectHead = document.createElement(\"th\");\n\tprojectHead.innerHTML = \"Project\";\n\tprojectHead.align = 'center';\n\tvar taskHead = document.createElement(\"th\");\n\ttaskHead.innerHTML = \"Task\";\n\ttaskHead.align = 'center';\n\tvar assigneeHead = document.createElement(\"th\");\n\tassigneeHead.innerHTML = \"Assignee\";\n\tassigneeHead.align = 'center';\n\tvar descriptionHead = document.createElement(\"th\");\n\tdescriptionHead.innerHTML = \"Description\";\n\tdescriptionHead.align = 'center';\n\tvar createdHead = document.createElement(\"th\");\n\tcreatedHead.innerHTML = \"Created\";\n\tcreatedHead.align = 'center';\n\tvar dueHead = document.createElement(\"th\");\n\tdueHead.innerHTML = \"Due\";\n\tdueHead.align = 'center';\n\tvar priorityHead = document.createElement(\"th\");\n\tpriorityHead.innerHTML = \"Priority\";\n\tpriorityHead.align = 'center';\n\tvar notesHead = document.createElement(\"th\");\n\tnotesHead.innerHTML = \"Notes\";\n\tnotesHead.align = 'center';\n\tdocument.body.appendChild(div);\n\n\tdocument.getElementById(\"insertTable\").appendChild(title);\n\tdocument.getElementById(\"insertTable\").appendChild(table);\n\tdocument.getElementById(\"table\").setAttribute(\"border-spacing\", \"8px\");\n\tdocument.getElementById(\"table\").setAttribute(\"border-collapse\", \"separate\");\n\tdocument.getElementById(\"table\").appendChild(head);\n\tdocument.getElementById(\"tableHeader\").appendChild(headRow);\n\tdocument.getElementById(\"head\").appendChild(indexHead);\n\tdocument.getElementById(\"head\").appendChild(projectHead);\n\tdocument.getElementById(\"head\").appendChild(taskHead);\n\tdocument.getElementById(\"head\").appendChild(assigneeHead);\n\tdocument.getElementById(\"head\").appendChild(descriptionHead);\n\tdocument.getElementById(\"head\").appendChild(createdHead);\n\tdocument.getElementById(\"head\").appendChild(dueHead);\n\tdocument.getElementById(\"head\").appendChild(priorityHead);\n\tdocument.getElementById(\"head\").appendChild(notesHead);\n\tvar count = 0;\n\tfor(var i = 0;i<projectsOfInterest.length; i++){\n\t\tcount++;\n\t\tvar row = table.insertRow();\n\t\tvar index = row.insertCell();\n\t\tindex.align = \"center\";\n\t\tvar project = row.insertCell();\n\t\tproject.align = \"center\";\n\t\tvar task = row.insertCell();\n\t\ttask.align = 'center';\n\t\tvar assignee = row.insertCell();\n\t\tassignee.align = 'center';\n\t\tvar description = row.insertCell();\n\t\tdescription.align = 'center';\n\t\tvar created = row.insertCell();\n\t\tcreated.align = 'center';\n\t\tvar due = row.insertCell();\n\t\tdue.align = 'center';\n\t\tvar priority = row.insertCell();\n\t\tpriority.align = 'center';\n\t\tvar notes = row.insertCell();\n\n\t\tindex.innerHTML = (count);\n\t\tproject.innerHTML = projectsOfInterest[i].project.warehouse.city.name + \n\t\t' #' + projectsOfInterest[i].project.warehouse.warehouseID +\n\t\t' - ' + projectsOfInterest[i].project.projectItem.name;\n\t\ttask.innerHTML = projectsOfInterest[i].title;\n\t\tassignee.innerHTML = projectsOfInterest[i].assignee.firstName;\n\t\tdescription.innerHTML = projectsOfInterest[i].description;\n\t\tcreated.innerHTML = projectsOfInterest[i].assignedDate;\n\t\tdue.innerHTML = projectsOfInterest[i].dueDate;\n\t\tpriority.innerHTML = projectsOfInterest[i].severity;\n\t\tpriority.align = 'center';\n\t\tnotes.innerHTML = projectsOfInterest[i].notes;\n\t\t\n\t\trow.appendChild(index);\n\t\trow.appendChild(project);\n\t\trow.appendChild(task);\n\t\trow.appendChild(assignee);\n\t\trow.appendChild(description);\n\t\trow.appendChild(created);\n\t\trow.appendChild(due);\n\t\trow.appendChild(priority);\n\t\trow.appendChild(notes);\n\t\ttable.appendChild(row);\n\t}\n\t\n\t\n\twindow.print();\n\t\n}", "function doGet () { \n return HtmlService.createHtmlOutputFromFile('Index')\n .setSandboxMode(HtmlService.SandboxMode.IFRAME);\n}", "function setHTML_offerUpcoming_upcoming(){\n return (\n '<div class=\"offerUpcoming_upcoming\"> upcoming deal </div>'\n );\n }", "function showTasks(taskList) {\n\tbodyListElem.innerHTML = \"\";\n\ttaskList.forEach((task) => {\n\t\tconst rowTask = createHtmlElement(\"tr\", null, [\"task-row\"], null);\n\t\trowTask.dataset.id = task.getId();\n\t\tconst circleColumnTask = createHtmlElement(\"td\", null, [\"task-cell\"], null);\n\t\tconst circleTask = createHtmlElement(\"div\", null, [\"circle-task\"], null);\n\t\tcircleTask.innerHTML = `<i class=\"bi bi-check done-icon\" data-id=\"${task.getId()}\"></i>`;\n\t\tcircleTask.dataset.id = task.getId();\n\t\tcircleColumnTask.appendChild(circleTask);\n\t\tconst titleColumnTask = createHtmlElement(\"td\", null, [\"task-title\"], task.getTitle());\n\t\tconst editColumnTask = createHtmlElement(\"td\", null, [\"task-cell\"], null);\n\t\teditColumnTask.innerHTML = `<i class=\"bi bi-pen task-icon\" data-id=\"${task.getId()}\"></i>`;\n\t\t//const dateColumnTask = createHtmlElement(\"td\", null, [\"task-cell\"], null);\n\t\t//dateColumnTask.innerHTML = '<i class=\"bi bi-calendar-plus task-icon\"></i>';\n\t\tconst deleteColumnTask = createHtmlElement(\"td\", null, [\"task-cell\"], null);\n\t\tdeleteColumnTask.innerHTML = `<i class=\"bi bi-trash task-icon\" data-id=\"${task.getId()}\"></i>`;\n\n\t\tif (task.isCompleted()){\n\t\t\tcircleTask.innerHTML = `<i class=\"bi bi-check done-icon done-icon-active\" data-id=\"${task.getId()}\"></i>`;\n\t\t} \n\n\t\trowTask.appendChild(circleColumnTask);\n\t\trowTask.appendChild(titleColumnTask);\n\t\trowTask.appendChild(editColumnTask);\n\t\t//rowTask.appendChild(dateColumnTask);\n\t\trowTask.appendChild(deleteColumnTask);\n\n\t\t//Event listeners from each button task\n\t\t//Complete a task\n\t\tcircleTask.onclick = (e) => {\n\t\t\tcompleteTask(e.target.dataset.id);\n\t\t\tdocument.querySelector(`[data-id=\"${e.target.dataset.id}\"]`).remove();\n\t\t};\n\t\tcircleTask.onmouseover = () => document.querySelector(\".done-icon\").classList.toggle(\"done-icon-active\");\n\t\tcircleTask.onmouseout = () => document.querySelector(\".done-icon\").classList.toggle(\"done-icon-active\");\n\t\teditColumnTask.onclick = (e) => {\n\t\t\tfillForm(e);\n\t\t\tdocument.querySelector(\"#create-task-modal\").querySelector(\".modal-title\").innerText =\n\t\t\t\t\"Edit Task\";\n\t\t\tdocument.querySelector(\"#add-task-btn\").innerText = \"Save\";\n\t\t\tdocument.querySelector(\"#add-task-btn\").setAttribute(\"data-id\", e.target.dataset.id);\n\t\t\tnew bootstrap.Modal(document.getElementById(\"create-task-modal\")).show();\n\t\t};\n\n\t\t//Remove a task\n\t\tdeleteColumnTask.onclick = (e) => {\n\t\t\tremoveTask(e.target.dataset.id);\n\t\t\te.target.parentNode.parentNode.remove();\n\t\t};\n\n\t\tbodyListElem.appendChild(rowTask);\n\t});\n}", "function projectToPanel(task) {\n\n // variable that fetches project panel\n const panel = document.querySelector('.projectPanel');\n\n panel.textContent = `${task}`;\n\n }", "function preview(url) {\n window.frames['previewing'].document.location.href = url;\n // document.getElementById(\"previewing\")\n}", "showIFrameInParent(data, element) {\n bsw.showIFrame(data.response.sets, element);\n }", "function getHaploview()\n{\n\tExt.Ajax.request({\t\t\t\t\t\t\n\t\turl: pageInfo.basePath+\"/asyncJob/createnewjob\",\n\t\tmethod: 'POST',\n\t\tsuccess: function(result, request)\n\t\t{\n\t\t\tRunHaploViewer(result, GLOBAL.DefaultCohortInfo.SampleIdList, GLOBAL.CurrentGenes);\n\t\t},\n\t\tfailure: function(result, request)\n\t\t{\n\t\t\tExt.Msg.alert('状态', '无法创建heatmap工作.');//<SIAT_zh_CN original=\"Status\">状态</SIAT_zh_CN><SIAT_zh_CN original=\"Unable to create the heatmap job\">无法创建heatmap工作</SIAT_zh_CN>\n\t\t},\n\t\ttimeout: '1800000',\n\t\tparams: {jobType: \"Haplo\"}\n\t});\t\n}", "function display(dimension) {\n toolbarStyle = $iframe.width(dimension.width).height(dimension.height).css('opacity', 1).attr('style');\n bodyStyle = $('body').attr('style') || '';\n htmlStyle = $('html').attr('style') || '';\n }", "render() {\n return this.renderPart_popup();\n }", "function visualiserFb(){\n // service pour visualiser facebook\n var url = \"https://www.facebook.com/conservatoireculinaireduquebec/\";\n window.open(url,\"_blank\");\n} // end visualiser pdffeed", "get html() {\n let html = '<div style=\"background: #fff; border: solid 1px #000; border-radius: 5px; font-weight: bold; margin-bottom: 1em; overflow: hidden;\">';\n html += '<div style=\"background: #000; color: #fff; text-align: center;\">' + this._header + '</div>';\n html += '<div style=\"padding: 5px;\">' + this._content + '</div>';\n html += '</div>';\n return html;\n }", "function show(data) {\r\n let tab =\r\n `<tr> \r\n\t\t\r\n\t\t</tr>`;\r\n\r\n // Loop to access all rows \r\n for (let r of data.articles) {\r\n tab += `<tr> <br><br>\r\n <tr><img src=\"${r.image_url}\" width=50% height=60% class=\"mx-auto w-50\"><br></tr> \r\n\t <tr>${r.title} <br></tr> \r\n\t <tr><a href=\"${r.article_url}\" target=\"_blank\">Read More</a><br></tr> \r\n\t <tr><strong>Source: </strong> ${r.source_name}<br></tr>\t\r\n \t<hr>\r\n </tr>`;\r\n }\r\n // Setting innerHTML as tab variable \r\n document.getElementById(\"employees\").innerHTML = tab;\r\n}", "function getUserDashHtml() {\n return new Promise(function(resolve) { \n firebase.database().ref('users/'+ firebase.auth().currentUser.uid)\n .once('value', function(userSnapshot){\n const name = userSnapshot.val().name;\n document.getElementById(TOP_ID).innerHTML = `Hi, ${name}! ${TOP_INFO_STR}`; \n \n resolve(`<img onclick=\"showModal(${INFO_HTML_PATH})\" class=\"btn btn-icon\" src=\"icons/help.svg\">\n Display Saved:\n <label class=\"switch btn\">\n <input type=\"checkbox\">\n <span class=\"slider round\"></span>\n </label>\n <a class=\"btn btn-outline-primary btn-color\" style=\"color: #049688;\" id=\"logout\">Logout</a>`);\n });\n });\n}", "function template(url, width, height) {\n return (\n '<div style=\"width:0;height:0\"> </div><div class=\"videoContainer bandcamp\" style=\"padding-bottom: ' +\n height +\n 'px\"><iframe width=\"' +\n width +\n '\" height=\"' +\n height +\n '\" src=\"' +\n encodeURI(url) + // encodeURI should prevent a passed URI from escaping / causing an XSS\n '\" frameborder=\"0\" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe></div>'\n );\n}", "render() {\n return (\n // Encompasing Div\n <div className=\"flexColumn\" id=\"wepaPage\">\n {/* Start TImeout Timer */}\n {this.runTimer()}\n\n {/* Iframe */}\n <div style={rightDiv}>{this.passIframe()}</div>\n\n <p style={{ marginLeft: 5 }}>\n * The link to IMT Support Desk does not function, please click\n <Link to=\"/APUSupport\"> HERE </Link>\n for assistance *\n </p>\n\n {/* Calls method to display modal */}\n {this.displayModal()}\n </div>\n );\n }", "function runSiteBuilder() {\n //Projektnamn\n document.getElementById(\"projectNameSpan\").innerHTML = settings[\"ProjectName\"];\n\n document.getElementById(\"rows\").children[0].value = settings[\"Rows\"];\n\n //Dutylist\n s = \"\";\n Duties.forEach(element => {//Loopa genom alla data och printa till s\n s += \"<tr id=\\\"task\" + element[\"ID\"] + \"\\\"><td>\" +\n \"<div class=\\\"removeDutyButton\\\" onclick=removeDuty(\" + element.ID + \")></div>\" +//Ta bort knapp\n /*byt namn knapp->*/\"<div class=\\\"renameButton\\\" onclick=renameDuty(\" + element.ID + \")></div></td><td><div id=\\\"taskName\" + element.ID + \"\\\">\" + element.Name + \"</td></tr>\";\n });\n //TBody\n document.getElementById(\"dutyList\").children[0].innerHTML += s; //Lägg in s i tabelen\n}", "function viewEmpTask(projectId,projectResourceId,content_id)\n{\n\t$.ajax({\n\t\turl: base_url + \"/timemanagement/projectresources/viewemptasks/format/html\",\n\t\tdata: 'projectId=' + projectId + '&projectResourceId=' + projectResourceId,\n\t\tdataType: 'html',\n\t\tsuccess: function(response) {\n\t\t\t $('#'+content_id).html(response);\n\t\t}\n\t});\n}", "function showPDSeason()\r\n{\r\n \t\r\n _startAssignPDPopup(); \r\n var reqData = formData2QueryString(document.forms[0]); \r\n \tvar ajaxReq = new AJAXRequest(\"merchandisecalendar.do?\" ,_showAssignPDSeasonPopup, \"method=showpdseason&\"+reqData, true);\r\n \tajaxReq.send();\r\n}", "function iframe(pageid) {\n var iw;\n if (inbrowser) {\n // represent the iframe as an iframe (of course)\n var iframe = document.createElement(\"iframe\");\n iframe.style.display = \"none\";\n document.body.appendChild(iframe);\n iw = iframe.contentWindow;\n iw.document.write(\"<script type=\\\"text/javascript\\\">Function.prototype.bind = null; var JSBNG_Replay_geval = eval;</script>\");\n iw.document.close();\n } else {\n // no general way, just lie and do horrible things\n var topwin = window;\n (function() {\n var window = {};\n window.window = window;\n window.top = topwin;\n window.JSBNG_Replay_geval = function(str) {\n eval(str);\n }\n iw = window;\n })();\n }\n return iw;\n }", "function createChartControl(htmlDiv, hasTreePanel) {\r\n try{\r\n var ganttChartControl;\r\n\r\n // Create Gantt control\r\n ganttChartControl = new GanttChart();\r\n // Setup paths and behavior\r\n ganttChartControl.setImagePath(\"/images/gantt/\");\r\n ganttChartControl.setEditable(false);\r\n ganttChartControl.showContextMenu(false);\r\n ganttChartControl.showTreePanel(hasTreePanel);\r\n\r\n ganttChartControl.getMonthScaleLabel = function(date) {\r\n return \"\";\r\n }\r\n\r\n\r\n // Build control on the page\r\n ganttChartControl.create(htmlDiv);\r\n ganttChartControl.showDescTask(true, 'n,e,d');\r\n ganttChartControl.showDescProject(true, 'n');\r\n\r\n // Load data structure\r\n ganttChartControl.loadData(\"../scripts/data.xml\", true, true);\r\n } catch (e) {}\r\n}", "function update_activity_section() {\n // Activity section displays changes within iframes, so we can't target it directly like with the history section.\n var iframe_container = document.getElementById('gadget-0').contentDocument;\n var container_array = iframe_container.getElementsByClassName('activity-item-info');\n var time_stamp_array = [];\n\n for (let i = 0; i < container_array.length; i++) {\n container_array[i].children[1].style = 'display: none;';\n time_stamp_array.push(container_array[i].children[1]);\n }\n\n for (let i = 0; i < time_stamp_array.length; i++) {\n var inserted_element = document.createElement('div');\n inserted_element.className = 'nates-awesome-date-element';\n inserted_element.style = 'display: inline-block; position: relative; width: 225px;' // iframes don't receive the styling from our css unfortunately. :(\n inserted_element.innerText = time_stamp_array[i].title;\n\n container_array[i].appendChild(inserted_element);\n }\n}", "function viewActivitySite(row, attribute) {\n window.open(location.origin + \"/gb.html#!/\"+row.id);\n }", "function displayGmailContent() {\n show('gmail-content');\n hide('gmail-settings');\n}", "function printPlaylistIframe(obj){\n var playlist = obj.playlistID;\n var user = obj.ownerID;\n var iframe = $('<iframe>')\n iframe.attr({\n src: 'https://embed.spotify.com/?uri=spotify:user:'+user+':playlist:'+playlist,\n width: '250',\n height: '380',\n frameborder: '0',\n allowtransparency: 'true'\n });\n $('#pane').find($('iframe')).remove();\n $('#pane').prepend(iframe);\n}", "function showHours() {\n var start = 0;\n var idstr = '';\n var hour = 0;\n var meridian = '';\n var calcDay = null;\n var cd = currDate;\n var currDay = new Date(cd.getFullYear(), cd.getMonth(), cd.getDate());\n var viewDiv = null;\n var timeLineWidth = 0;\n var workingHoursBarWidth = 3;\n\n // Subtract one px for border per asinine CSS spec\n var halfHourHeight = (HOUR_UNIT_HEIGHT/2) - 1;\n\n viewDiv = timelineNode;\n timeLineWidth = parseInt(viewDiv.offsetWidth);\n // Subtract 1 for 1px border\n timeLineWidth = timeLineWidth - workingHoursBarWidth - 1;\n\n var str = '';\n var row = '';\n // Timeline of hours on left\n for (var j = 0; j < 24; j++) {\n hour = j == 12 ? _('App.Noon') : cosmo.datetime.util.hrMil2Std(j);\n meridian = j > 11 ? ' PM' : ' AM';\n meridian = j == 12 ? '' : '<span>' + meridian + '</span>';\n row = '';\n\n // Upper half hour\n // ==================\n row += '<div class=\"hourDivTop';\n row += '\" style=\"height:' +\n halfHourHeight + 'px; width:' +\n timeLineWidth + 'px; float:left;\">';\n // Hour plus AM/PM\n row += '<div class=\"hourDivSubLeft\">' + hour +\n meridian + '</div>';\n row += '</div>\\n';\n row += '<br class=\"clearAll\"/>'\n\n idstr = i + '-' + j + '30';\n\n // Lower half hour\n // ==================\n row += '<div class=\"hourDivBottom\"';\n // Make the noon border thicker\n if (j == 11) {\n row += ' style=\"height:' + (halfHourHeight-1) +\n 'px; border-width:2px;';\n }\n else {\n row += ' style=\"height:' + halfHourHeight + 'px;';\n }\n row += ' width:' + timeLineWidth +\n 'px; float:left;\">&nbsp;</div>\\n';\n row += '<br class=\"clearAll\"/>'\n\n str += row;\n }\n viewDiv.innerHTML = str;\n\n str = '';\n viewDiv = hoursNode;\n\n // Do a week's worth of day cols with hours\n for (var i = 0; i < 7; i++) {\n calcDay = cosmo.datetime.Date.add(viewStart, cosmo.datetime.util.dateParts.DAY, i);\n str += '<div class=\"dayDiv\" id=\"dayDiv' + i +\n '\" style=\"left:' + start + 'px; width:' +\n (cosmo.view.cal.canvas.dayUnitWidth-1) +\n 'px;\"';\n str += '>';\n for (var j = 0; j < 24; j++) {\n idstr = i + '-' + j + '00';\n row = '';\n row += '<div id=\"hourDiv' + idstr + '\" class=\"hourDivTop\" style=\"height:' + halfHourHeight + 'px;\">';\n row += '</div>\\n';\n idstr = i + '-' + j + '30';\n row += '<div id=\"hourDiv' + idstr + '\" class=\"hourDivBottom\" style=\"';\n if (j == 11) {\n row += 'height:' + (halfHourHeight-1) +\n 'px; border-width:2px;';\n }\n else {\n row += 'height:' + halfHourHeight + 'px;';\n }\n row += '\">&nbsp;</div>';\n str += row;\n }\n str += '</div>\\n';\n start += cosmo.view.cal.canvas.dayUnitWidth;\n }\n\n viewDiv.innerHTML = str;\n return true;\n }", "function main() {\n logging(\"enter main\")\n var mainframe = document.getElementById(\"mainframe\")\n if(mainframe != undefined) {\n logging(\"mainfram found\")\n var tables = document.getElementById(\"mainframe\").contentWindow.document.getElementsByTagName(\"table\")\n var table_count = tables.length\n logging(\"table count: \"+table_count)\n // 1.1 course list\n if(table_count == 1){\n // a. find first un-complete course\n var course_list = get_childNode(tables[0], 0)\n if (course_list.length >= COURSE_TABLE_MIN_SIZE) {\n for (var i = 1; i < course_list.length; i++) {\n var progress = get_course_progress(course_list[0] ,course_list[i])\n if((progress != \"\") && (progress != \"100%\")) {\n // hit target, open the course and break\n // TBD\n }\n }\n }\n // b. else prmpt( other ways inform TBD) all courses are completed\n }\n // 1.2 check lecture list and play the un-completed list in the queue\n if(table_count >=2) {\n\n //////////////////////////////////////////////////////////////////////////////////////////////////// Stop interval task\n // window.clearInterval(task)\n // get entire lecture list and check if any lecture uncomplete\n var lecture_table_outer = document.getElementById(\"mainframe\").contentWindow.document.getElementsByTagName(\"table\")[1]\n if (get_childNode(lecture_table_outer,0) != null) {\n var lecture_table = lecture_table_outer.childNodes[0]\n // header, control_element, lecture(start from index 7 - total more than 8)\n if (lecture_table.childNodes.length >= LECTURE_TABLE_MIN_SIZE + 1) {\n // loop lecture list, and check lecture progress\n for (var i = LECTURE_TABLE_MIN_SIZE; i < lecture_table.childNodes.length; i++) {\n var lecture = lecture_table.childNodes[i]\n if(validate_lecture(lecture)) {\n var lecture_progress = get_lecture_progress(lecture)\n logging(lecture.childNodes[1].innerHTML + \" \" + lecture_progress)\n\n if ((lecture_progress == \"100%\") && window.ongoing_lecture == i) {\n// window.ongoing_lecture = 0;\n }\n ////////////////////////////////////////////////////////// Manual updated progress\n if((lecture_progress != \"1000%\") && (lecture_progress != \"\")) { \n logging(\"hit lecture check ongoing status before play it and current index is: \" + window.ongoing_lecture )\n if (window.ongoing_lecture == 0) {\n window.ongoing_lecture = i;\n lecture.childNodes[3].childNodes[0].dispatchEvent(click_evt)\n } \n break\n } \n } \n }\n }\n } \n // referh to get the latest progress\n var control_table = document.getElementById(\"mainframe\").contentWindow.document.getElementsByTagName(\"table\")[0]\n control_table.childNodes[1].childNodes[4].childNodes[1].childNodes[3].dispatchEvent(click_evt)\n }\n }\n else {\n logging(\"checking...\")\n }\n }", "function calculus()\n{\n document.getElementById('ZoneJeu').innerHTML = '<iframe id=\"Calculus\" width=\"850px\" height=\"500px\"></iframe>';\n document.getElementById('Calculus').src = \"Calculus.html?Prenom=\" + EnfantConnecte.Prenom;\n}", "function showOverview() {\n var links = [];\n $.each(noteSelf.paragraphs, function(index, paragraph) {\n if (paragraph.paragraphClient.getDependencies != undefined) {\n var dependencies = paragraph.paragraphClient.getDependencies();\n $.each(dependencies.inputTables, function(index, inputTable) {\n links.push({ source: inputTable, target: dependencies.name });\n });\n $.each(dependencies.outputTables, function(index, outputTable) {\n links.push({ source: dependencies.name, target: outputTable });\n });\n }\n });\n\n utils.showModalPopup('Overview', utils.generateDirectedGraph(links), $());\n }", "function print_corte_operador_day(id_operador){\n\n\t\tlet print_pdf_dia = document.getElementById('modal_content_dia');\n\t\tlet ifram_pdf_dia = document.createElement(\"iframe\");\n\n\t\tifram_pdf_dia.setAttribute(\"src\", baseURL + \"web/Operador_ctrl/pdf_operador_corte_dia?id=\" + id_operador);\n\t\tifram_pdf_dia.setAttribute(\"id\", \"load_pdf_dia\");\n\t\tifram_pdf_dia.style.width = \"100%\";\n\t\tifram_pdf_dia.style.height = \"510px\";\n\t\tprint_pdf_dia.appendChild(ifram_pdf_dia);\n\t}", "function expandTable1()\r\n{\r\n\t\r\n\talert(\"hey\");\r\n\tdocument.getElementById(\"col1\").innerHTML = myPanel(\"User Expence:Daily\",\r\n\t\t\tuserExpenceDailyList,0,1);\t\r\n\t\r\n}", "function showSidebar() {\n var ui = HtmlService.createHtmlOutputFromFile('Sidebar')\n .setSandboxMode(HtmlService.SandboxMode.IFRAME)\n .setTitle('Post to Airtable');\n FormApp.getUi().showSidebar(ui);\n}", "function showCalendar(date) {\n var calendar = document.createElement('IFRAME');\n var src = cal.src + cal.id + '&ctz=' + cal.timeZone;\n\n if (date != null) {\n // create a month long range for calendar view based off event date\n date = date.split('-');\n var dateRange = '' + date[0] + date[1];\n dateRange = dateRange +'01%2F'+ dateRange + '28';\n src += '&dates=' + dateRange;\n }\n\n calendar.setAttribute('id', 'calendar-view');\n calendar.setAttribute('src', src);\n calendar.setAttribute('scrolling', 'no');\n calendar.setAttribute('frameborder', '0');\n\n if (cal.inEvent) {\n calendar.setAttribute('class', 'smallCalendar');\n } else {\n calendar.setAttribute('class', 'bigCalendar');\n }\n\n $('#calendar-div').append(calendar);\n}", "function doGet(){\r\n\r\n // This called function handles scratch pad file creation . . .\r\n\r\n var scratchpadSpreadsheetId = returnScratchpadFileCollection();\r\n\r\n PropertiesService.getScriptProperties().setProperty('scratchpadSpreadsheetId', scratchpadSpreadsheetId);\r\n\r\n // Through the createHtmlOutputFromFile() function,\r\n // multiple users can use the application . . .\r\n\r\n return HtmlService.createHtmlOutputFromFile(\"BigQueryDemoApp.html\").setSandboxMode(HtmlService.SandboxMode.IFRAME);\r\n}", "function _drawVisualization() {\n // Create and populate a data table.\n var data = new google.visualization.DataTable();\n data.addColumn('datetime', 'start');\n data.addColumn('datetime', 'end');\n data.addColumn('string', 'content');\n data.addColumn('string', 'group');\n\n var date = new Date(2014, 04, 25, 8, 0, 0);\n\n var loader_text = '<img src=\"/res/qsl/img/loader33x16.png\" width=\"33px\" height=\"16px\"> L-105';\n var inspe_text =\n '<div title=\"Inspection\" class=\"order\">' +\n '<i class=\"fa fa-lg fa-wrench\"></i> ' +\n 'Inspection' +\n '</div>';\n var inspe_start = new Date(date);\n var inspe_end = new Date(date.setHours(date.getHours() + 6));\n\n data.addRow([inspe_start, inspe_end, inspe_text, loader_text]);\n\n var vessl_text =\n '<div title=\"Snoekgracht\" class=\"order\">' +\n '<i class=\"fa fa-lg fa-anchor\"></i> ' +\n 'Snoekgracht' +\n '</div>';\n var inspe_start = new Date(date.setHours(date.getHours() + 6));\n var inspe_end = new Date(date.setHours(date.getHours() + 48));\n\n data.addRow([inspe_start, inspe_end, vessl_text, loader_text]);\n\n // specify options\n var options = {\n width: \"100%\",\n //height: \"300px\",\n height: \"auto\",\n layout: \"box\",\n editable: true,\n eventMargin: 5, // minimal margin between events\n eventMarginAxis: 0, // minimal margin beteen events and the axis\n showMajorLabels: false,\n axisOnTop: true,\n // groupsWidth : \"200px\",\n groupsChangeable: true,\n groupsOnRight: false,\n stackEvents: false\n };\n\n // Instantiate our timeline object.\n that.timeline = new links.Timeline(document.getElementById(that.optio.vva_id_regn));\n\n // Draw our timeline with the created data and options\n that.timeline.draw(data, options);\n }", "function createHTML (courseSet) {\n\tvar frame = '';\n\tfor (var j=0; j < courseSet.length;\t j ++) {\n\t\tif (courseSet[j].filename != \"na\") {\n\t\t\tframe += \"<li class='list-group-item body-text'><b>\" + courseSet[j].courseCode + \" \" + courseSet[j].courseNum + \"</b> - \" + courseSet[j].title + \" (\" + courseSet[j].quarter + \" \" + courseSet[j].year + \") \" + \"<a href='documents/syllabi/\" + courseSet[j].filename + \"''>\" + \"[syllabus]\" + \"</a></li>\";\n\t\t}\n\t\telse {\n\t\tframe += \"<li class='list-group-item body-text'><b>\" + courseSet[j].courseCode + \" \" + courseSet[j].courseNum + \"</b> - \" + courseSet[j].title + \" (\" + courseSet[j].quarter + \" \" + courseSet[j].year + \") \" + \"</li>\";\n\t\t}\n\t}\n\treturn frame;\n}", "function show(requiredData) { \r\n \r\n let tab=\"\";\r\n console.log(typeof(requiredData));\r\n console.log(requiredData);\r\n \r\n // Loop to access all rows \r\n for(let r of requiredData) { \r\n tab += `<div style=\"margin-top:25px;\"class=\"col-lg-4 col-md-6 col-sm-12\"><div class=\"card h-100 bg-danger\"> <div class=\"card-header\">\r\n <h4 class=\"card-title\" >${r.loc}</h4> </div><div class=\"card-body bg-warning\">\r\n <div> Confirmed cases Indian: ${r.confirmedCasesIndian}</div>\r\n <div> Confirmed cases Foreign: ${r.confirmedCasesForeign}</div>\r\n <div> Discharged: ${r.discharged}</div>\r\n <div> Deaths : ${r.deaths}</div>\r\n <div> Total Confirmed : ${r.totalConfirmed}</div></div></div></div>`; \r\n } \r\n // Setting innerHTML as tab variable \r\n document.getElementById(\"covidData\").innerHTML = tab; \r\n}", "function showMyPage(gameweekPlan){\n var box = document.getElementById('fpl-suggestion-box');\n if(box){\n box.remove();\n }\n\n box = document.createElement('div');\n box.id = 'fpl-suggestion-box'\n box.style = 'display: block; margin-bottom: 16px; color: #333333';\n\n var content = document.createElement('div');\n content.style =\n 'background-color: #EFEFEF;' +\n 'font-family: PremierSans-Bold, Arial, \"Helvetica Neue\", Helvetica, sans-seriff;';\n\n var contentHeader = document.createElement('div');\n contentHeader.style =\n 'margin-bottom: 16px; border-bottom: 1px solid rgb(55, 0, 60); padding: 16px;';\n contentHeader.innerHTML = `\n <h2 style=\"color: #333333;\">Fantasy Pundit</h2>\n <h3 style=\"color: #333333; margin-bottom: 10px\">Suggested Changes to Starting 11</h3>\n `;\n\n var contentBody = document.createElement('div');\n contentBody.style = 'padding: 16px';\n contentBody.innerHTML = '';\n\n content.appendChild(contentHeader);\n content.appendChild(contentBody);\n\n var tableHTML = `\n <table width='100%'>\n <thead style=\"text-align: left; color: #FF2828; margin-bottom: 16px\">\n <tr>\n <th>Bench</th>\n <th>Captian</th>\n <th>Vice Captian</th>`;\n\n if(gameweekPlan.activateTripleCaptian){\n tableHTML += '<th>Triple Captian</th>';\n }\n\n if(gameweekPlan.activateBenchBoost){\n tableHTML += '<th>Bench Boost</th>';\n }\n\n tableHTML += `</tr>\n </thead> \n \n <tbody style='font-family: PremierSans-Regular, Arial, \"Helvetica Neue\", Helvetica, sans-serif; font-weight: 400; font-size: 13px';>\n <tr>\n <td style=\"padding-top: 9px;\">\n GK: ${gameweekPlan.bench.goalkeeper.name.charAt(0).toUpperCase() + gameweekPlan.bench.goalkeeper.name.slice(1)}\n (${Math.round(gameweekPlan.bench.goalkeeper.next_gw_expected_points)})\n </td>\n <td style=\"padding-top: 9px;\" rowspan=\"4\" valign=\"top\">\n ${gameweekPlan.captian.name.charAt(0).toUpperCase() + gameweekPlan.captian.name.slice(1)}\n (${Math.round(gameweekPlan.captian.next_gw_expected_points)})\n </td>\n <td style=\"padding-top: 9px;\" rowspan=\"4\" valign=\"top\">\n ${gameweekPlan.viceCaptian.name.charAt(0).toUpperCase() + gameweekPlan.viceCaptian.name.slice(1)}\n (${Math.round(gameweekPlan.viceCaptian.next_gw_expected_points)})\n </td>\n `;\n\n if(gameweekPlan.activateTripleCaptian){\n tableHTML += `<td style=\"padding-top: 9px;\" rowspan=\"4\" valign=\"top\">${gameweekPlan.activateTripleCaptian}</td>`;\n }\n\n if(gameweekPlan.activateBenchBoost){\n tableHTML += `<td style=\"padding-top: 9px;\" rowspan=\"4\" valign=\"top\">${gameweekPlan.activateBenchBoost}</td>`;\n }\n\n tableHTML += `</tr>\n <tr><td style=\"padding-top: 9px;\" colspan=\"5\">\n ${gameweekPlan.bench.outfield[0].name.charAt(0).toUpperCase() + gameweekPlan.bench.outfield[0].name.slice(1)}\n (${Math.round(gameweekPlan.bench.outfield[0].next_gw_expected_points)})\n </td></tr>\n \n <tr><td style=\"padding-top: 9px;\" colspan=\"5\">\n ${gameweekPlan.bench.outfield[1].name.charAt(0).toUpperCase() + gameweekPlan.bench.outfield[1].name.slice(1)}\n (${Math.round(gameweekPlan.bench.outfield[1].next_gw_expected_points)})\n </td></tr>\n \n <tr><td style=\"padding-top: 9px;\" colspan=\"5\">\n ${gameweekPlan.bench.outfield[2].name.charAt(0).toUpperCase() + gameweekPlan.bench.outfield[2].name.slice(1)}\n (${Math.round(gameweekPlan.bench.outfield[2].next_gw_expected_points)})\n </td></tr>\n </tbody>\n </table>\n `;\n\n contentBody.innerHTML = tableHTML;\n\n var highlight = document.createElement('div');\n highlight.style = 'height: 6px; margin: 0px 1rem; background: linear-gradient(to right, rgb(235, 255, 0), rgb(0, 255, 135));';\n\n box.appendChild(content);\n box.appendChild(highlight);\n\n var playerBox = document.getElementsByClassName('sc-AykKC YEZTh')[0];\n playerBox.parentNode.insertBefore(box,playerBox);\n}", "function metadataStaticView() {\n html= HtmlService\n .createTemplateFromFile('staticMetadata')\n .evaluate()\n .setSandboxMode(HtmlService.SandboxMode.IFRAME);\n DocumentApp.getUi().showSidebar(html);\n }", "function showDisplayFrame() {\n\treturn utils.messageWindow(parent, {action: 'showMainDisplay'}, context.url);\n}" ]
[ "0.5806583", "0.57869035", "0.56300116", "0.5610308", "0.55983096", "0.5590144", "0.5587809", "0.5543368", "0.5543", "0.54806256", "0.5463755", "0.54394054", "0.5430979", "0.5423943", "0.54152936", "0.5410391", "0.5397799", "0.53975356", "0.5396913", "0.5387686", "0.5382666", "0.5342795", "0.5332395", "0.53280675", "0.5319405", "0.5318139", "0.52935916", "0.52916557", "0.5276857", "0.5266849", "0.52585745", "0.5258032", "0.5256424", "0.52485955", "0.5246961", "0.5243583", "0.523597", "0.52350396", "0.5227123", "0.52201456", "0.5194269", "0.5189801", "0.51897025", "0.51801145", "0.51691103", "0.5152766", "0.51360285", "0.5128698", "0.5122034", "0.5114", "0.5112439", "0.5109317", "0.509294", "0.5084626", "0.5082894", "0.50819755", "0.5081281", "0.5076226", "0.5068682", "0.506384", "0.5044325", "0.50247693", "0.50162756", "0.5010775", "0.5010692", "0.5010202", "0.5007543", "0.5005948", "0.50054836", "0.5004975", "0.5000206", "0.49931103", "0.49846584", "0.49786416", "0.49742404", "0.49714822", "0.49662384", "0.495942", "0.4958017", "0.49499354", "0.4948313", "0.49428162", "0.49416798", "0.49400517", "0.49392638", "0.4938595", "0.49384087", "0.49372503", "0.49357226", "0.49308315", "0.49238798", "0.49231824", "0.49231648", "0.49217293", "0.49209806", "0.49169895", "0.4916723", "0.49119604", "0.49110574", "0.49059162" ]
0.6852637
0
these are the definitions for the serial events:
function openPort() { serialPort.on('open', openPort); // called when the serial port opens var brightness = 'H'; // the brightness to send for the LED console.log('port open'); //console.log('baud rate: ' + SerialPort.options.baudRate); // since you only send data when the port is open, this function // is local to the openPort() function: function sendData() { // convert the value to an ASCII string before sending it: serialPort.write(brightness.toString()); console.log('Sending ' + brightness + ' out the serial port'); } // set an interval to update the brightness 2 times per second: //setInterval(sendData, 1500); var x = 0; var intervalID = setInterval(function () { // Your logic here sendData(); if (++x === 2) { clearInterval(intervalID); } }, 1000); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function serialEvent(){\n\n}", "function serialEvent() {\n inData = Number(serial.read());\n}", "function serialEvent() {\n inData = serial.readLine();\n let splitData = split(inData, '|');\n if (splitData.length === 7) {\n b1 = int(trim(splitData[0]));\n b2 = int(trim(splitData[1]));\n slider = int(trim(splitData[2]));\n shaked = int(trim(splitData[3]));\n light = int(trim(splitData[4]));\n sound = int(trim(splitData[5]));\n temp = int(trim(splitData[6]));\n newValue = true;\n } else {\n newValue = false;\n }\n}", "function FsEventsHandler() {}", "function constroiEventos(){}", "function Event(a, b, type, idx) {\n\t this.a = a\n\t this.b = b\n\t this.type = type\n\t this.idx = idx\n\t}", "function Event(a, b, type, idx) {\n\t this.a = a\n\t this.b = b\n\t this.type = type\n\t this.idx = idx\n\t}", "function EventReader() {}", "function Event(a, b, type, idx) {\n this.a = a\n this.b = b\n this.type = type\n this.idx = idx\n}", "function Event(a, b, type, idx) {\n this.a = a\n this.b = b\n this.type = type\n this.idx = idx\n}", "function Event(a, b, type, idx) {\n this.a = a\n this.b = b\n this.type = type\n this.idx = idx\n}", "_parseEventForParameterNumber(event) {\n // To make it more legible\n const controller = event.message.dataBytes[0];\n const value = event.message.dataBytes[1]; // A. Check if the message is the start of an RPN (101) or NRPN (99) parameter declaration.\n\n if (controller === 99 || controller === 101) {\n this._nrpnBuffer = [];\n this._rpnBuffer = [];\n\n if (controller === 99) {\n // 99\n this._nrpnBuffer = [event.message];\n } else {\n // 101\n // 127 is a reset so we ignore it\n if (value !== 127) this._rpnBuffer = [event.message];\n } // B. Check if the message is the end of an RPN (100) or NRPN (98) parameter declaration.\n\n } else if (controller === 98 || controller === 100) {\n if (controller === 98) {\n // 98\n // Flush the other buffer (they are mutually exclusive)\n this._rpnBuffer = []; // Check if we are in sequence\n\n if (this._nrpnBuffer.length === 1) {\n this._nrpnBuffer.push(event.message);\n } else {\n this._nrpnBuffer = []; // out of sequence\n }\n } else {\n // 100\n // Flush the other buffer (they are mutually exclusive)\n this._nrpnBuffer = []; // 127 is a reset so we ignore it\n\n if (this._rpnBuffer.length === 1 && value !== 127) {\n this._rpnBuffer.push(event.message);\n } else {\n this._rpnBuffer = []; // out of sequence or reset\n }\n } // C. Check if the message is for data entry (6, 38, 96 or 97). Those messages trigger events.\n\n } else if (controller === 6 || controller === 38 || controller === 96 || controller === 97) {\n if (this._rpnBuffer.length === 2) {\n this._dispatchParameterNumberEvent(\"rpn\", this._rpnBuffer[0].dataBytes[1], this._rpnBuffer[1].dataBytes[1], event);\n } else if (this._nrpnBuffer.length === 2) {\n this._dispatchParameterNumberEvent(\"nrpn\", this._nrpnBuffer[0].dataBytes[1], this._nrpnBuffer[1].dataBytes[1], event);\n } else {\n this._nrpnBuffer = [];\n this._rpnBuffer = [];\n }\n }\n }", "init() {\n //DW:P0:0;\n var self = this;\n var generalListener = function (line) {\n //decoupage\n var dataType = \"\";\n var name = \"\";\n var value = \"\";\n var re = /([A-Z]{2,3}):(.*):(.*);/i;\n var found = line.match(re);\n if (found != null && found.length == 4) {\n dataType = found[1];\n name = found[2];\n value = found[3];\n }\n //console.log_(found);\n var arrayLength = self.onReceivedListeners.length;\n var eventProcessed = false;\n for (var i = 0; i < arrayLength; i++) {\n var listener = self.onReceivedListeners[i];\n if (!eventProcessed && (listener.dataType === dataType || listener.dataType === \"*\")\n && (listener.name === name || listener.name === \"*\")) {\n listener.callback(this, value, line, dataType, name);\n eventProcessed = true;\n if (listener.removeAfter) {\n delete self.onReceivedListeners[i];\n }\n return;\n }\n }\n if (!eventProcessed) {\n self.onDefaultReceivedListener(line);\n }\n };\n //console.log_(this.onReadLine);\n //console.log(generalListener);\n this.onReadLine.addListener(generalListener);\n }", "function EventEmitter(){}// Shortcuts to improve speed and size", "constructor() {\n super();\n\n this._Add_event(\"offer\");\n this._Add_event(\"data_in\");\n this._Add_event(\"file_end\");\n }", "function InternalEvent() { }", "function InternalEvent() { }", "function InternalEvent() { }", "function InternalEvent() { }", "function InternalEvent() { }", "function InternalEvent() {}", "function serialEvent(){\n //THIS READS BINARY - serial.read reads from the serial port, Number() sets the data type to a number\n\t// inData = Number(serial.read()); //reads data as a number not a string\n\n //THIS READS ASCII\n inData = serial.readLine(); //read until a carriage return\n\n //best practice is to make sure you're not reading null data\n if(inData.length > 0){\n //split the values apart at the comma\n var numbers = split(inData, ',');\n\n //set variables as numbers\n sensor1 = Number(numbers[0]);\n sensor2 = Number(numbers[1]);\n }\n\n console.log(sensor1 + \", \" + sensor2);\n}", "function capture_events_onCbusMessage(gcMessage) {\n\tif (gcMessage.direction == \"rx\") {\n\t\tvar cantype = gcMessage.message.substr(1,1);\n\t\tif (cantype != \"S\") return;\n\t\t\n\t\t// extract OPC\n\t\tvar opcstr = gcMessage.message.substr(7, 2);\n\t\tvar opc = hex2number(opcstr);\n\t\tconsole.log(\"Event handler got opc \"+opc);\n\t\tif (isEvent(opc)) {\n\t\t\tvar e = {};\n\t\t\tvar nnstr = gcMessage.message.substr(9,4);\n \t\te.nn = hex2number(nnstr);\n \t\tvar enstr = gcMessage.message.substr(13,4);\n\t\t\te.en = hex2number(enstr);\n\t\t\tif (isShort(opc)) e.nn = 0;\n\n\t\t\te.name = \"\";\n\t\t\taddEvent(e);\n\t\t} \n\t}\n}", "_onStateChange(e) {\n let event = {\n timestamp: wm.time,\n target: this,\n port: this // for consistency\n\n };\n\n if (e.port.connection === \"open\") {\n /**\n * Event emitted when the `Input` has been opened by calling the [`open()`]{@link #open}\n * method.\n *\n * @event Input#opened\n * @type {object}\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n * @property {string} type `opened`\n * @property {Input} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n */\n event.type = \"opened\";\n this.emit(\"opened\", event);\n } else if (e.port.connection === \"closed\" && e.port.state === \"connected\") {\n /**\n * Event emitted when the `Input` has been closed by calling the\n * [`close()`]{@link #close} method.\n *\n * @event Input#closed\n * @type {object}\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n * @property {string} type `closed`\n * @property {Input} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n */\n event.type = \"closed\";\n this.emit(\"closed\", event);\n } else if (e.port.connection === \"closed\" && e.port.state === \"disconnected\") {\n /**\n * Event emitted when the `Input` becomes unavailable. This event is typically fired\n * when the MIDI device is unplugged.\n *\n * @event Input#disconnected\n * @type {object}\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n * @property {string} type `disconnected`\n * @property {Input} port Object with properties describing the {@link Input} that was\n * disconnected. This is not the actual `Input` as it is no longer available.\n * @property {Input} target The object that dispatched the event.\n */\n event.type = \"disconnected\";\n event.port = {\n connection: e.port.connection,\n id: e.port.id,\n manufacturer: e.port.manufacturer,\n name: e.port.name,\n state: e.port.state,\n type: e.port.type\n };\n this.emit(\"disconnected\", event);\n } else if (e.port.connection === \"pending\" && e.port.state === \"disconnected\") ; else {\n console.warn(\"This statechange event was not caught: \", e.port.connection, e.port.state);\n }\n }", "function SerialJS(SerialJS_serialPort__var, SerialJS_lib__var, SerialJS_serialP__var, SerialJS_buffer__var, SerialJS_index__var) {\n\nvar _this;\nthis.setThis = function(__this) {\n_this = __this;\n};\n\nthis.ready = false;\n//Attributes\nthis.SerialJS_serialPort__var = SerialJS_serialPort__var;\nthis.SerialJS_lib__var = SerialJS_lib__var;\nthis.SerialJS_serialP__var = SerialJS_serialP__var;\nthis.SerialJS_buffer__var = SerialJS_buffer__var;\nthis.SerialJS_index__var = SerialJS_index__var;\n//message queue\nconst queue = [];\nthis.getQueue = function() {\nreturn queue;\n};\n\n//callbacks for third-party listeners\nconst receive_bytesOnreadListeners = [];\nthis.getReceive_bytesonreadListeners = function() {\nreturn receive_bytesOnreadListeners;\n};\n//ThingML-defined functions\nfunction receive(SerialJS_receive_byte__var) {\nif(_this.SerialJS_buffer__var[0]\n === 0x13 && SerialJS_receive_byte__var === 0x12 || _this.SerialJS_buffer__var[0]\n === 0x12) {\nif( !((SerialJS_receive_byte__var === 0x13)) || _this.SerialJS_buffer__var[_this.SerialJS_index__var - 1]\n === 0x7D) {\nSerialJS_buffer__var[_this.SerialJS_index__var] = SerialJS_receive_byte__var;\n_this.SerialJS_index__var = _this.SerialJS_index__var + 1;\n\n}\nif(SerialJS_receive_byte__var === 0x13 && !((_this.SerialJS_buffer__var[_this.SerialJS_index__var - 1]\n === 0x7D))) {\nprocess.nextTick(sendReceive_bytesOnRead.bind(_this, _this.SerialJS_buffer__var.slice()));\n_this.SerialJS_index__var = 0;\nvar i__var = 0;\n\nwhile(i__var < 18) {\nSerialJS_buffer__var[i__var] = 0x13;\ni__var = i__var + 1;\n\n}\n\n}\n\n}\n}\n\nthis.receive = function(SerialJS_receive_byte__var) {\nreceive(SerialJS_receive_byte__var);};\n\nfunction initSerial() {\nvar i__var = 0;\n\nwhile(i__var < 18) {\nSerialJS_buffer__var[i__var] = 0x13;\ni__var = i__var + 1;\n\n}\n_this.SerialJS_serialP__var = new _this.SerialJS_lib__var.SerialPort(_this.SerialJS_serialPort__var, {baudrate: 9600, parser: _this.SerialJS_lib__var.parsers.byteLength(1)}, false);;\n_this.SerialJS_serialP__var.open(function (error) {\nif (error){\nconsole.log(\"ERROR: \" + (\"Problem opening the serial port... It might work, though most likely not :-)\"));\nconsole.log(error);\nconsole.log(\"ERROR: \" + (\"Available serial ports:\"));\n_this.SerialJS_lib__var.list(function (err, ports) {\n ports.forEach(function(port) {\n console.log(port.comName); \n });\n });\n}else{\n_this.SerialJS_serialP__var.on('data', function(data) {\nreceive(data[0]);\n});\nconsole.log((\"Serial port opened sucessfully!\"));\n}})\n}\n\nthis.initSerial = function() {\ninitSerial();};\n\nfunction killSerial() {\n_this.SerialJS_serialP__var.close(function (error) {\nif (error){\nconsole.log(\"ERROR: \" + (\"Problem closing the serial port...\"));\nconsole.log(error);\n}else\nconsole.log((\"serial port closed!\"));\n});\n}\n\nthis.killSerial = function() {\nkillSerial();};\n\n//Internal functions\nfunction sendReceive_bytesOnRead(b) {\n//notify listeners\nconst arrayLength = receive_bytesOnreadListeners.length;\nfor (var _i = 0; _i < arrayLength; _i++) {\nreceive_bytesOnreadListeners[_i](b);\n}\n}\n\n//State machine (states and regions)\nthis.build = function() {\nthis.SerialJS_behavior = new StateJS.StateMachine(\"behavior\").entry(function () {\ninitSerial();\nconsole.log((\"Serial port ready!\"));\n})\n\n.exit(function () {\nkillSerial();\nconsole.log((\"Serial port killed, RIP!\"));\n})\n\n;\nthis._initial_SerialJS_behavior = new StateJS.PseudoState(\"_initial\", this.SerialJS_behavior, StateJS.PseudoStateKind.Initial);\nvar SerialJS_behavior_default = new StateJS.State(\"default\", this.SerialJS_behavior);\nthis._initial_SerialJS_behavior.to(SerialJS_behavior_default);\nSerialJS_behavior_default.to(null).when(function (message) { v_b = message[2];return message[0] === \"write\" && message[1] === \"write_bytes\";}).effect(function (message) {\n v_b = message[2];_this.SerialJS_serialP__var.write(v_b, function(err, results) {\n});\n});\n}\n}", "_parseEventForStandardMessages(e) {\n const event = Object.assign({}, e);\n event.type = event.message.type || \"unknownmessage\";\n const data1 = e.message.dataBytes[0];\n const data2 = e.message.dataBytes[1];\n\n if (event.type === \"noteoff\" || event.type === \"noteon\" && data2 === 0) {\n this.notesState[data1] = false;\n event.type = \"noteoff\"; // necessary for note on with 0 velocity\n\n /**\n * Event emitted when a **note off** MIDI message has been received on the channel.\n *\n * @event InputChannel#noteoff\n *\n * @type {object}\n * @property {string} type `noteoff`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the incoming\n * MIDI message.\n * @property {number} timestamp The moment\n * ([`DOMHighResTimeStamp`](https://developer.mozilla.org/en-US/docs/Web/API/DOMHighResTimeStamp))\n * when the event occurred (in milliseconds since the navigation start of the document).\n *\n * @property {object} note A [`Note`](Note) object containing information such as note name,\n * octave and release velocity.\n * @property {number} value The release velocity amount expressed as a float between 0 and 1.\n * @property {number} rawValue The release velocity amount expressed as an integer (between 0\n * and 127).\n */\n // The object created when a noteoff event arrives is a Note with an attack velocity of 0.\n\n event.note = new Note(Utilities.offsetNumber(data1, this.octaveOffset + this.input.octaveOffset + wm.octaveOffset), {\n rawAttack: 0,\n rawRelease: data2\n });\n event.value = Utilities.from7bitToFloat(data2);\n event.rawValue = data2; // Those are kept for backwards-compatibility but are gone from the documentation. They will\n // be removed in future versions (@deprecated).\n\n event.velocity = event.note.release;\n event.rawVelocity = event.note.rawRelease;\n } else if (event.type === \"noteon\") {\n this.notesState[data1] = true;\n /**\n * Event emitted when a **note on** MIDI message has been received.\n *\n * @event InputChannel#noteon\n *\n * @type {object}\n * @property {string} type `noteon`\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} note A [`Note`](Note) object containing information such as note name,\n * octave and release velocity.\n * @property {number} value The attack velocity amount expressed as a float between 0 and 1.\n * @property {number} rawValue The attack velocity amount expressed as an integer (between 0\n * and 127).\n */\n\n event.note = new Note(Utilities.offsetNumber(data1, this.octaveOffset + this.input.octaveOffset + wm.octaveOffset), {\n rawAttack: data2\n });\n event.value = Utilities.from7bitToFloat(data2);\n event.rawValue = data2; // Those are kept for backwards-compatibility but are gone from the documentation. They will\n // be removed in future versions (@deprecated).\n\n event.velocity = event.note.attack;\n event.rawVelocity = event.note.rawAttack;\n } else if (event.type === \"keyaftertouch\") {\n /**\n * Event emitted when a **key-specific aftertouch** MIDI message has been received.\n *\n * @event InputChannel#keyaftertouch\n *\n * @type {object}\n * @property {string} type `\"keyaftertouch\"`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} note A [`Note`](Note) object containing information such as note name\n * and number.\n * @property {number} value The aftertouch amount expressed as a float between 0 and 1.\n * @property {number} rawValue The aftertouch amount expressed as an integer (between 0 and\n * 127).\n */\n event.note = new Note(Utilities.offsetNumber(data1, this.octaveOffset + this.input.octaveOffset + wm.octaveOffset)); // Aftertouch value\n\n event.value = Utilities.from7bitToFloat(data2);\n event.rawValue = data2; // @deprecated\n\n event.identifier = event.note.identifier;\n event.key = event.note.number;\n event.rawKey = data1;\n } else if (event.type === \"controlchange\") {\n /**\n * Event emitted when a **control change** MIDI message has been received.\n *\n * @event InputChannel#controlchange\n *\n * @type {object}\n * @property {string} type `controlchange`\n * @property {string} subtype The type of control change message that was received.\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n event.controller = {\n number: data1,\n name: Enumerations.CONTROL_CHANGE_MESSAGES[data1].name,\n description: Enumerations.CONTROL_CHANGE_MESSAGES[data1].description,\n position: Enumerations.CONTROL_CHANGE_MESSAGES[data1].position\n };\n event.subtype = event.controller.name || \"controller\" + data1;\n event.value = Utilities.from7bitToFloat(data2);\n event.rawValue = data2;\n /**\n * Event emitted when a **control change** MIDI message has been received and that message is\n * targeting the controller numbered \"xxx\". Of course, \"xxx\" should be replaced by a valid\n * controller number (0-127).\n *\n * @event InputChannel#controlchange-controllerxxx\n *\n * @type {object}\n * @property {string} type `controlchange-controllerxxx`\n * @property {string} subtype The type of control change message that was received.\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n const numberedEvent = Object.assign({}, event);\n numberedEvent.type = `${event.type}-controller${data1}`;\n delete numberedEvent.subtype;\n this.emit(numberedEvent.type, numberedEvent);\n /**\n * Event emitted when a **controlchange-bankselectcoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-bankselectcoarse\n *\n * @type {object}\n * @property {string} type `controlchange-bankselectcoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-modulationwheelcoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-modulationwheelcoarse\n *\n * @type {object}\n * @property {string} type `controlchange-modulationwheelcoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-breathcontrollercoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-breathcontrollercoarse\n *\n * @type {object}\n * @property {string} type `controlchange-breathcontrollercoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-footcontrollercoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-footcontrollercoarse\n *\n * @type {object}\n * @property {string} type `controlchange-footcontrollercoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-portamentotimecoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-portamentotimecoarse\n *\n * @type {object}\n * @property {string} type `controlchange-portamentotimecoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-dataentrycoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-dataentrycoarse\n *\n * @type {object}\n * @property {string} type `controlchange-dataentrycoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-volumecoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-volumecoarse\n *\n * @type {object}\n * @property {string} type `controlchange-volumecoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-balancecoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-balancecoarse\n *\n * @type {object}\n * @property {string} type `controlchange-balancecoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-pancoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-pancoarse\n *\n * @type {object}\n * @property {string} type `controlchange-pancoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-expressioncoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-expressioncoarse\n *\n * @type {object}\n * @property {string} type `controlchange-expressioncoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effectcontrol1coarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effectcontrol1coarse\n *\n * @type {object}\n * @property {string} type `controlchange-effectcontrol1coarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effectcontrol2coarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effectcontrol2coarse\n *\n * @type {object}\n * @property {string} type `controlchange-effectcontrol2coarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller1** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller1\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller1`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller2** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller2\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller2`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller3** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller3\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller3`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller4** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller4\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller4`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-bankselectfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-bankselectfine\n *\n * @type {object}\n * @property {string} type `controlchange-bankselectfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-modulationwheelfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-modulationwheelfine\n *\n * @type {object}\n * @property {string} type `controlchange-modulationwheelfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-breathcontrollerfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-breathcontrollerfine\n *\n * @type {object}\n * @property {string} type `controlchange-breathcontrollerfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-footcontrollerfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-footcontrollerfine\n *\n * @type {object}\n * @property {string} type `controlchange-footcontrollerfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-portamentotimefine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-portamentotimefine\n *\n * @type {object}\n * @property {string} type `controlchange-portamentotimefine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-dataentryfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-dataentryfine\n *\n * @type {object}\n * @property {string} type `controlchange-dataentryfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-channelvolumefine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-channelvolumefine\n *\n * @type {object}\n * @property {string} type `controlchange-channelvolumefine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-balancefine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-balancefine\n *\n * @type {object}\n * @property {string} type `controlchange-balancefine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-panfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-panfine\n *\n * @type {object}\n * @property {string} type `controlchange-panfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-expressionfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-expressionfine\n *\n * @type {object}\n * @property {string} type `controlchange-expressionfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effectcontrol1fine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effectcontrol1fine\n *\n * @type {object}\n * @property {string} type `controlchange-effectcontrol1fine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effectcontrol2fine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effectcontrol2fine\n *\n * @type {object}\n * @property {string} type `controlchange-effectcontrol2fine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-damperpedal** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-damperpedal\n *\n * @type {object}\n * @property {string} type `controlchange-damperpedal`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-portamento** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-portamento\n *\n * @type {object}\n * @property {string} type `controlchange-portamento`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-sostenuto** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-sostenuto\n *\n * @type {object}\n * @property {string} type `controlchange-sostenuto`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-softpedal** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-softpedal\n *\n * @type {object}\n * @property {string} type `controlchange-softpedal`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-legatopedal** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-legatopedal\n *\n * @type {object}\n * @property {string} type `controlchange-legatopedal`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-hold2** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-hold2\n *\n * @type {object}\n * @property {string} type `controlchange-hold2`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-soundvariation** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-soundvariation\n *\n * @type {object}\n * @property {string} type `controlchange-soundvariation`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-resonance** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-resonance\n *\n * @type {object}\n * @property {string} type `controlchange-resonance`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-releasetime** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-releasetime\n *\n * @type {object}\n * @property {string} type `controlchange-releasetime`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-attacktime** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-attacktime\n *\n * @type {object}\n * @property {string} type `controlchange-attacktime`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-brightness** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-brightness\n *\n * @type {object}\n * @property {string} type `controlchange-brightness`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-decaytime** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-decaytime\n *\n * @type {object}\n * @property {string} type `controlchange-decaytime`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-vibratorate** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-vibratorate\n *\n * @type {object}\n * @property {string} type `controlchange-vibratorate`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-vibratodepth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-vibratodepth\n *\n * @type {object}\n * @property {string} type `controlchange-vibratodepth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-vibratodelay** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-vibratodelay\n *\n * @type {object}\n * @property {string} type `controlchange-vibratodelay`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller5** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller5\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller5`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller6** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller6\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller6`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller7** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller7\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller7`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-generalpurposecontroller8** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-generalpurposecontroller8\n *\n * @type {object}\n * @property {string} type `controlchange-generalpurposecontroller8`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-portamentocontrol** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-portamentocontrol\n *\n * @type {object}\n * @property {string} type `controlchange-portamentocontrol`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-highresolutionvelocityprefix** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-highresolutionvelocityprefix\n *\n * @type {object}\n * @property {string} type `controlchange-highresolutionvelocityprefix`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effect1depth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effect1depth\n *\n * @type {object}\n * @property {string} type `controlchange-effect1depth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effect2depth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effect2depth\n *\n * @type {object}\n * @property {string} type `controlchange-effect2depth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effect3depth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effect3depth\n *\n * @type {object}\n * @property {string} type `controlchange-effect3depth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effect4depth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effect4depth\n *\n * @type {object}\n * @property {string} type `controlchange-effect4depth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-effect5depth** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-effect5depth\n *\n * @type {object}\n * @property {string} type `controlchange-effect5depth`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-dataincrement** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-dataincrement\n *\n * @type {object}\n * @property {string} type `controlchange-dataincrement`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-datadecrement** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-datadecrement\n *\n * @type {object}\n * @property {string} type `controlchange-datadecrement`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-nonregisteredparameterfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-nonregisteredparameterfine\n *\n * @type {object}\n * @property {string} type `controlchange-nonregisteredparameterfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-nonregisteredparametercoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-nonregisteredparametercoarse\n *\n * @type {object}\n * @property {string} type `controlchange-nonregisteredparametercoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-registeredparameterfine** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-registeredparameterfine\n *\n * @type {object}\n * @property {string} type `controlchange-registeredparameterfine`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-registeredparametercoarse** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-registeredparametercoarse\n *\n * @type {object}\n * @property {string} type `controlchange-registeredparametercoarse`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-allsoundoff** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-allsoundoff\n *\n * @type {object}\n * @property {string} type `controlchange-allsoundoff`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-resetallcontrollers** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-resetallcontrollers\n *\n * @type {object}\n * @property {string} type `controlchange-resetallcontrollers`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-localcontrol** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-localcontrol\n *\n * @type {object}\n * @property {string} type `controlchange-localcontrol`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-allnotesoff** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-allnotesoff\n *\n * @type {object}\n * @property {string} type `controlchange-allnotesoff`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-omnimodeoff** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-omnimodeoff\n *\n * @type {object}\n * @property {string} type `controlchange-omnimodeoff`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-omnimodeon** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-omnimodeon\n *\n * @type {object}\n * @property {string} type `controlchange-omnimodeon`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-monomodeon** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-monomodeon\n *\n * @type {object}\n * @property {string} type `controlchange-monomodeon`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n /**\n * Event emitted when a **controlchange-polymodeon** MIDI message has been\n * received.\n *\n * @event InputChannel#controlchange-polymodeon\n *\n * @type {object}\n * @property {string} type `controlchange-polymodeon`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {object} controller\n * @property {object} controller.number The number of the controller.\n * @property {object} controller.name The usual name or function of the controller.\n * @property {object} controller.description A user-friendly representation of the\n * controller's default function\n * @property {string} controller.position Whether the controller is meant to be an `msb` or `lsb`\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The value expressed as an integer (between 0 and 127).\n */\n\n const namedEvent = Object.assign({}, event);\n namedEvent.type = `${event.type}-` + Enumerations.CONTROL_CHANGE_MESSAGES[data1].name;\n delete namedEvent.subtype; // Dispatch controlchange-\"function\" events only if the \"function\" is defined (not the generic\n // controllerXXX nomenclature)\n\n if (namedEvent.type.indexOf(\"controller\") !== 0) {\n this.emit(namedEvent.type, namedEvent);\n } // Trigger channel mode message events (if appropriate)\n\n\n if (event.message.dataBytes[0] >= 120) this._parseChannelModeMessage(event); // Parse the inbound event to see if its part of an RPN/NRPN sequence\n\n if (this.parameterNumberEventsEnabled && this._isRpnOrNrpnController(event.message.dataBytes[0])) {\n this._parseEventForParameterNumber(event);\n }\n } else if (event.type === \"programchange\") {\n /**\n * Event emitted when a **program change** MIDI message has been received.\n *\n * @event InputChannel#programchange\n *\n * @type {object}\n * @property {string} type `programchange`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {number} value The value expressed as an integer between 0 and 127.\n * @property {number} rawValue The raw MIDI value expressed as an integer between 0 and 127.\n */\n event.value = data1;\n event.rawValue = event.value;\n } else if (event.type === \"channelaftertouch\") {\n /**\n * Event emitted when a control change MIDI message has been received.\n *\n * @event InputChannel#channelaftertouch\n *\n * @type {object}\n * @property {string} type `channelaftertouch`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The raw MIDI value expressed as an integer between 0 and 127.\n */\n event.value = Utilities.from7bitToFloat(data1);\n event.rawValue = data1;\n } else if (event.type === \"pitchbend\") {\n /**\n * Event emitted when a pitch bend MIDI message has been received.\n *\n * @event InputChannel#pitchbend\n *\n * @type {object}\n * @property {string} type `pitchbend`\n *\n * @property {InputChannel} target The object that dispatched the event.\n * @property {Input} port The `Input` that triggered the event.\n * @property {Message} message A [`Message`](Message) object containing information about the\n * incoming MIDI message.\n * @property {number} timestamp The moment (DOMHighResTimeStamp) when the event occurred (in\n * milliseconds since the navigation start of the document).\n *\n * @property {number} value The value expressed as a float between 0 and 1.\n * @property {number} rawValue The raw MIDI value expressed as an integer (between 0 and\n * 16383).\n */\n event.value = ((data2 << 7) + data1 - 8192) / 8192;\n event.rawValue = (data2 << 7) + data1;\n } else {\n event.type = \"unknownmessage\";\n }\n\n this.emit(event.type, event);\n }", "function serialListener(debug)\n{\n var receivedData = \"\";\n serialPort = new SerialPort(portName, {\n baudrate: 9600,\n // defaults for Arduino serial communication\n dataBits: 8,\n parity: 'none',\n stopBits: 1,\n flowControl: false\n });\n \n serialPort.on(\"open\", function () {\n// console.log('open serial communication');\n // Listens to incoming data\n serialPort.on('data', function(data) {\n receivedData += data.toString();\n if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('B') >= 0) {\n sendData = receivedData .substring(receivedData .indexOf('B') + 1, receivedData .indexOf('E'));\n receivedData = '';\n }\n // send the incoming data to browser with websockets.\n \n \n if(sendData.length != 0){\n if(codeTemp != sendData){\n codeTemp=sendData;\n trys = trys - 1;// -1 vie\n if (essai(sendData,code)==true){\n\n trys=99;\n }\n if (trys <= 0 ){\n socketServer.emit('updateData', '0:BOOOOM');\n\n }else{\n socketServer.emit('updateData', trys+':'+sendData);\n }\n }\n }\n //SocketIO_serialemit(sendData);\n //EE.on('update');\n \n }); \n }); \n}", "function openHandler (self) {\n\tvar parser = new xml2js.Parser();\n\tvar buffer = \"\";\t// read buffer.\n\n if (TRACE) {\t\n \tconsole.log('serial device open');\n }\n \n self.emit(\"open\");\n\n\t// add serial port data handler\t\n\tself.serialPort.on('data', function(data) {\n\t\tbuffer += data.toString() + \"\\r\\n\";\t\t// append to the read buffer\n\t\tif ( data.toString().indexOf('</') == 0 ) {\t\t// check if last part of XML element.\n\t\t\t\n\t\t\t// try to parse buffer\n\t\t\tparser.parseString(buffer, function (err, result) {\n\t\t\t\tif (err) {\n\t\t\t\t\tconsole.log(\"err: \" + err);\n\t\t\t\t\tconsole.log('data received: ' + buffer);\n\t\t\t\t}\n\t\t\t\telse if (result.InstantaneousDemand) {\n\t\t\t\t\tvar timestamp = parseInt( result.InstantaneousDemand.TimeStamp );\n\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\tvar demand = parseInt( result.InstantaneousDemand.Demand, 16 );\n\t\t\t\t\tdemand = demand < 0x80000000 ? demand : - ~demand - 1;\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.log(\"demand: \" + timestamp.toLocaleString() + \" : \" + demand);\n\t\t\t\t\t}\n\t\t\t\t \t\n\t\t\t\t\t// emit power event\n\t\t\t\t\tvar power = { value: demand, unit: \"W\", timestamp: timestamp.toISOString() };\n\t\t\t\t\tself.emit(\"power\", power);\n\t\t\t\t}\n\t\t\t\telse if (result.CurrentSummationDelivered) {\n\t\t\t\t\tvar timestamp = parseInt( result.CurrentSummationDelivered.TimeStamp );\n\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\tvar used = parseInt( result.CurrentSummationDelivered.SummationDelivered, 16 );\n\t\t\t\t\tvar fedin = parseInt( result.CurrentSummationDelivered.SummationReceived, 16 );\n\t\t\t\t\tconsole.log(\"sum: \" + timestamp.toLocaleString() + \" : \" + used + \" - \" + fedin);\n\n\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\tvar energyIn = { value: used, unit: \"Wh\" , timestamp: timestamp.toISOString() };\n\t\t\t\t\tvar energyOut = { value: fedin, unit: \"Wh\", timestamp: timestamp.toISOString() };\n\n\t\t\t\t\tself.emit(\"energy-in\", energyIn);\n\t\t\t\t\tself.emit(\"energy-out\", energyOut);\n\t\t\t\t}\n\t\t\t\telse if (result.ConnectionStatus) {\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.log(\"connection status: \" + result.ConnectionStatus.Status);\n\t\t\t\t\t}\n\t\t\t\t\tself.emit(\"connection\", result.ConnectionStatus.Status);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.dir(result);\t// display data read in\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tbuffer = \"\";\t// reset the read buffer\n\t\t}\n\t});\n\n\t// Possible commands: get_time, get_current_summation_delivered; get_connection_status; get_instantaneous_demand; get_current_price; get_message; get_device_info.\n\tvar queryCommand = \"<Command><Name>get_connection_status</Name></Command>\\r\\n\";\n\tself.serialPort.write(queryCommand, function(err, results) {\n\t\tself.serialPort.write(\"<Command><Name>get_message</Name></Command>\\r\\n\", function(err, results) {\n\t\t\tself.serialPort.write(\"<Command><Name>get_current_price</Name></Command>\\r\\n\", function(err, results) {\n\t\t\t}); \n\t\t}); \n\t}); \n}", "function EventInfo() { }", "function EventInfo() { }", "function openHandler (self) {\n\tvar parser = new xml2js.Parser();\n\tvar linenumber = 0;\n\tvar buffer = \"\";\t// read buffer.\n\tvar parseBuffer=\"\"; // for xml parsing\n\tvar tmpBuffer = \"\";\n\tvar line = \"\"; // line read;\n\t//var lines;\n \n winston.info('serial device opened at ...' + new Date());\n \n if (state.FIRST_RUN) {\n\t\tstate.FIRST_RUN = false;\n\t\tself.emit(\"open\");\n\t}\t\n\t\n\t// add serial port data handler\t\n\tself.serialPort.on('data', function(evtdata) {\n\t\tstate.PORT_INITIALIZED = true;\n\t\twinston.silly(\"Receiving data....\");\n\t\tif (newDay()) rolloverDay();\n\t\tline = evtdata.toString();\t\n\t\tbuffer += line;\t\t// append to the read buffer\n\t\ttmpBuffer=\"\";\n\t\tparseBuffer=\"\";\n\t\tvar lines = S(buffer).lines();\n\t\tfor (var i=0; i< lines.length; i++){\n\t\t\ttmpBuffer += lines[i];\n\t\t\tif (lines[i].endsWith('>')){\n\t\t\t\ttmpBuffer += '\\r\\n';\n\t\t\t}\n\t\t\tif ((lines[i].indexOf('</') == 0) && (lines[i].endsWith('>'))){\n\t\t\t\tparseBuffer=tmpBuffer;\n\t\t\t\tlinenumber =0;\n\t\t\t\ttmpBuffer=\"\";\n\t\t\t}\n\t\t}\n\t\tbuffer = tmpBuffer;\n\t\n\t\tif ( parseBuffer != \"\") {\t\t// check if last part of XML element.\n\t\t\twinston.silly('Raw Data:\\n' + parseBuffer);\n\t\t\t\n\t\t\t// try to parse buffer\n\t\t\ttry {\n\t\t\t\tparser.parseString(parseBuffer, function (err, result) {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\twinston.error(\"parser error: \" + Object.keys(err)[0] +\":\" + Object.values(err)[0]);\n\t\t\t\t\t\twinston.debug(\"details: \" + err + \"\\nRaw Buffer\\n\" + parseBuffer);\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.InstantaneousDemand) {\n\t\t\t\t\t\tvar timestamp = parseInt( result.InstantaneousDemand.TimeStamp );\n\t\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\t\tvar demand = parseInt( result.InstantaneousDemand.Demand, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.InstantaneousDemand.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.InstantaneousDemand.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tdemand = demand < 0x80000000 ? demand : - ~demand - 1;\n\t\t\t\t\t\tdemand = 1000*demand*multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"demand: \" + timestamp.toLocaleString() + \" : \" + demand);\n\t\t\t\t\t\t// emit power event\n\t\t\t\t\t\tvar power = { value: demand, unit: \"W\", timestamp: timestamp.toISOString() };\n\t\t\t\t\t\tstate.POLL_DEMAND = false;\n\t\t\t\t\t\tstate.failCount=0;\n\t\t\t\t\t\t//winston.debug(\"DEMAND POLL FLAG demand:\" + state.POLL_DEMAND + \" , Sum:\" + state.POLL_ENERGY + \" , Current:\"+ state.POLL_USAGE_CURRENT +\" , Last\" + state.POLL_USAGE_LAST );\n\t\t\t\t\t\tif (state.POLL_ENERGY) {\n\t\t\t\t\t\t\tdata.powerTable.add(demand,timestamp);\n\t\t\t\t\t\t\tmqttMsg.add(power,\"demand\");\n\t\t\t\t\t\t\tself.getSumEnergy();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.emit(\"demand\", power);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.CurrentSummationDelivered) {;\n\t\t\t\t\t\tvar timestamp = parseInt( result.CurrentSummationDelivered.TimeStamp );\n\t\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\t\tvar used = parseInt( result.CurrentSummationDelivered.SummationDelivered, 16 );\n\t\t\t\t\t\tvar fedin = parseInt( result.CurrentSummationDelivered.SummationReceived, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.CurrentSummationDelivered.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.CurrentSummationDelivered.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\tfedin = fedin * multiplier / divisor;\n\t\t\t\t\t\tdata.energyInToday = used;\n\t\t\t\t\t\tdata.energyIn.add(data.energyInToday,timestamp);\n\t\t\t\t\t\tif (data.energyInYday == 0 ) data.energyInYday = data.energyInToday;\n\t\t\t\t\t\tif (data.energyInThisMonth == 0 ) data.energyInThisMonth = data.energyInToday;\n\t\t\t\t\t\tdata.energyOutToday = fedin;\n\t\t\t\t\t\tdata.energyOut.add(data.energyOutToday,timestamp);\n\t\t\t\t\t\tif (data.energyOutYday == 0 ) data.energyOutYday = data.energyOutToday;\n\t\t\t\t\t\tif (data.energyOutThisMonth == 0 ) data.energyOutThisMonth = data.energyOutToday;\n\t\t\t\t\t\tused = (data.energyInToday - data.energyInYday);\n\t\t\t\t\t\tfedin = (data.energyOutToday - data.energyOutYday);\n\t\t\t\t\t\twinston.info(\"Today used: \" + used.toFixed(2) + \", togrid:\" + fedin.toFixed(2) + \", Month used:\" + (data.energyInToday - data.energyInThisMonth).toFixed(2) +\", togrid:\" + (data.energyOutToday - data.energyOutThisMonth).toFixed(2) );\t\t\t\t\t\n\t\t\t\t\t\tdata.energyOutTMDays = Math.round((timestamp.getTime() - data.energyOutTMStartDate.getTime())/(1000*60*60*24)); \n\t\t\t\t\t\t\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar energyIn = { value: used, unit: \"KWh\" , thismonth: (data.energyInToday - data.energyInThisMonth), lastmonth:data.energyInLastMonth, lifetime:data.energyInToday, timestamp: timestamp.toISOString() };\n\t\t\t\t\t\tvar energyOut = { value: fedin, unit: \"KWh\", thismonth: (data.energyOutToday - data.energyOutThisMonth), lastmonth:data.energyOutLastMonth, lifetime:data.energyOutToday , tmstartdate: data.energyOutTMStartDate.toISOString(), tmdays:data.energyOutTMDays , lmstartdate:data.energyOutLMStartDate.toISOString(), lmenddate:data.energyOutLMEndDate.toISOString(), lmdays: data.energyOutLMDays, timestamp: timestamp.toISOString() };\n\n\t\t\t\t\t\t//self.emit(\"energy-in\", energyIn);\n\t\t\t\t\t\t//self.emit(\"energy-out\", energyOut);\n\t\t\t\t\t\tstate.POLL_ENERGY = false\n\t\t\t\t\t\tmqttMsg.add(energyIn,\"energyin\");\n\t\t\t\t\t\tmqttMsg.add(energyOut,\"energyout\");\n\t\t\t\t\t\tself.getCurrentPeriodUsage();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.CurrentPeriodUsage) {\n\t\t\t\t\t\tvar timestamp = new Date();\n\t\t\t\t\t\tvar startdate = parseInt( result.CurrentPeriodUsage.StartDate );\n\t\t\t\t\t\tstartdate = new Date(dateOffset+startdate*1000);\n\t\t\t\t\t\tvar days = Math.round((timestamp.getTime() - startdate.getTime())/(1000*60*60*24));\n\t\t\t\t\t\tvar used = parseInt( result.CurrentPeriodUsage.CurrentUsage, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.CurrentPeriodUsage.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.CurrentPeriodUsage.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\t//winston.info(\"after divisor, miltiplier - \" + multiplier + \", divisor - \" + divisor);\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"Current Period Usage: \" + timestamp.toLocaleString() + \" : \" + used.toFixed(2) + \" - Days: \" + days + \" - Start Date \" + startdate.toLocaleString());\n\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar currentUsage = { value: used, unit: \"KWh\" , timestamp: timestamp.toISOString() , startdate: startdate.toISOString(), days: days };\n\t\t\t\t\t\t//self.emit(\"usage-current\", currentUsage);\n\t\t\t\t\t\tstate.POLL_USAGE_CURRENT = false;\n\t\t\t\t\t\tmqttMsg.add(currentUsage,\"currentusage\");\n\t\t\t\t\t\tself.getLastPeriodUsage();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.LastPeriodUsage) {\n\t\t\t\t\t\tvar timestamp = new Date();\n\t\t\t\t\t\tvar startdate = parseInt( result.LastPeriodUsage.StartDate );\n\t\t\t\t\t\tstartdate = new Date(dateOffset+startdate*1000);\n\t\t\t\t\t\tvar enddate = parseInt( result.LastPeriodUsage.EndDate );\n\t\t\t\t\t\tenddate = new Date(dateOffset+enddate*1000);\n\t\t\t\t\t\tvar days = Math.round((enddate.getTime() - startdate.getTime())/(1000*60*60*24));\n\t\t\t\t\t\tvar used = parseInt( result.LastPeriodUsage.LastUsage, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.LastPeriodUsage.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.LastPeriodUsage.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"Last Period Usage: \" + timestamp.toLocaleString() + \" : \" + used.toFixed(2) + \" - Days: \" + days +\" - Start Date \" + startdate.toLocaleString() + \" - End Date \" + enddate.toLocaleString());\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar lastUsage = { value: used , unit: \"KWh\" , timestamp: timestamp.toISOString() , startdate: startdate.toISOString(), enddate: enddate.toISOString(), days: days };\n\n\t\t\t\t\t\t//self.emit(\"usage-last\", lastUsage);\n\t\t\t\t\t\tstate.POLL_USAGE_LAST = false;\n\t\t\t\t\t\tmqttMsg.add(lastUsage,\"lastusage\");\n\t\t\t\t\t\tfireMqtt();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.ConnectionStatus) {\n\t\t\t\t\t\twinston.info(\"connection status: \" + result.ConnectionStatus.Status);\n\t\t\t\t\t\tself.emit(\"connection\", result.ConnectionStatus.Status);\n\t\t\t\t\t}\n\t\t\t\t\telse if ( (!result.InstantaneousDemand) && (!result.CurrentSummationDelivered) && (!result.CurrentPeriodUsage) && (!result.LastPeriodUsage)){\n\t\t\t\t\t\t\twinston.info(\"Other Command: \" + Object.keys(result)[0] +\":\" + Object.values(result)[0]);\n\t\t\t\t\t\t\twinston.debug(util.format('%o',result));\t// display data read in\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (ex){\n\t\t\t\twinston.error(\"Uncaught exception liklely in XML2js parser\\n\" + ex);\n\t\t\t\twinston.debug(\"Details\\n\" + Object.keys(ex)[0] +\":\" + Object.values(ex)[0]);\n\t\t\t}\n\t\t\tparseBuffer = \"\";\t// reset the read buffer\n\t\t}\t\n\t});\n\tsetTimeout(setPortStatus, 15000);\n}", "function MIDIEvents() {\n\t\t\t\tthrow new Error('MIDIEvents function not intended to be run.');\n\t\t\t}", "function Event_Event(object, eventTriggered, data, object2, eventTriggered2, data2)\n{\n\t//set our values\n\tthis.InterpreterObject = object ? object : null;\n\tthis.Event = eventTriggered ? eventTriggered : __NEMESIS_EVENT_NOTHANDLED;\n\tthis.Datas = data ? typeof data === \"object\" ? data : [data] : [];\n\tthis.InterpreterObjectEx = object2 ? object2 : null;\n\tthis.EventEx = eventTriggered2 ? eventTriggered2 : __NEMESIS_EVENT_NOTHANDLED;\n\tthis.DatasEx = data2 ? typeof data2 === \"object\" ? data2 : [data2] : [];\n}", "function EventDict() {}", "function getSystemEvent(code, length, data='') {\n switch(code) {\n case 'f0': //0xF0:\n return new SysExStart(length, data);\n break;\n case 'f7': //0xF7:\n return new SysExEnd(length, data);\n break;\n default:\n break;\n }\n}", "async function eventSerializer(){\n return new Promise(async (resolve, reject) =>{\n port\n .on('open', async () =>{\n process.stdout.write('\\x07\\x07\\x07\\x07');//Synchronized with 4 beep sound\n\n port.on('data', async (data) =>{\n data = data.toString('utf8').replace(/[wkg]/gi, '');\n if(isNaN(data)) return resolve();\n \n data = Number(data);\n if(signalDebug) console.log(`${prev} ${curr} Rate : ${stable} Stable : ${isStable} Sent : ${isSent}`);\n \n curr = data;\n\n if(data == 0){\n zero++\n\n if(STABLE_THRESHOLD < zero) isSent = false, zero = 0;\n }\n else zero = 0;\n\n if(data == 0 || Math.abs(data) <= THRESHOLD){\n return resolve();\n }\n\n if(stable < STABLE_THRESHOLD) isStable = false;\n else isStable = true;\n\n if(curr == prev){\n stable++;\n \n if(isStable && !isSent){\n prev = curr, stable = 0, isStable = false, isSent = true;\n let buf = `${String(curr)}`;\n \n \n process.stdout.write('\\x07');//Beep sound with \"please wait\"\n if(timeDebug) console.time('I/O');//Start KB I/O\n await robot.typeString(buf);\n if(timeDebug) console.timeLog('I/O');\n await robot.keyTap('tab')\n process.stdout.write('\\x07');//Beep sound with \"good to go\"\n if(timeDebug) console.timeLog('I/O');//End KB I/O\n if(timeDebug) console.timeEnd('I/O');\n }\n }\n else prev = curr, curr = 0, stable = 0, isStable = false, isSent = false;\n \n resolve();\n });\n })\n .on('error', async (error) =>{\n console.log(error);\n })\n })\n}", "function sendEvent() {\n\t// Look for the selected event in the event list and get the nn/en\n\tvar nn = Number($(\".eventselected.enn\").text());\n\tvar en = Number($(\".eventselected.en\").text());\n\t\n\t// now get the info about the event:\n\tvar onoff = $(\"input[name='onoffradio']:checked\").val();\n\tvar numdata = Number($(\"input[name='dataradio']:checked\").val());\n\t\n\tvar data1 = Number($(\"input[name='data1']\").val());\n\tvar data2 = Number($(\"input[name='data2']\").val());\n\tvar data3 = Number($(\"input[name='data3']\").val());\n\t\n\tconsole.log(\"construct event nn=\"+nn+\" en=\"+en+\" onoff=\"+onoff+\" numdata=\"+numdata);\n\tconsole.log(\"data1=\"+data1+\" data2=\"+data2+\" data3=\"+data3);\n\t\n\t// Calculate the OPC\n\tvar opc = 144 + numdata*32;\n\tif (onoff == \"OFF\") opc++;\n\tif (nn == 0) opc += 8;\n\t\n\t// Add any data bytes\n\tvar gc = ':S0FC0N'+number2hex2(opc)+number2hex4(nn)+number2hex4(en);\n\tif (numdata >= 1) {\n\t\tgc += number2hex2(data1);\n\t}\n\tif (numdata >= 2) {\n\t\tgc += number2hex2(data2);\n\t}\n\tif (numdata >= 3) {\n\t\tgc += number2hex2(data3);\n\t}\n\tgc += ';';\n\tconsole.log(\"gc=\"+gc);\n\tgcSend({direction:'tx', message:gc});\n}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}", "function Events() {}" ]
[ "0.71352947", "0.6472466", "0.6117559", "0.5978452", "0.58761066", "0.58573383", "0.58573383", "0.58545065", "0.58094406", "0.58094406", "0.58094406", "0.57856935", "0.5711684", "0.5696215", "0.56145036", "0.56056106", "0.56056106", "0.56056106", "0.56056106", "0.56056106", "0.55961233", "0.5579822", "0.5555256", "0.55402863", "0.55402404", "0.5515748", "0.5498575", "0.5495265", "0.5484357", "0.5484357", "0.54788274", "0.54435784", "0.5438643", "0.5411068", "0.5404112", "0.5396296", "0.5395374", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791", "0.537791" ]
0.0
-1
console.log('baud rate: ' + SerialPort.options.baudRate); since you only send data when the port is open, this function is local to the openPort() function:
function sendData() { // convert the value to an ASCII string before sending it: serialPort.write(brightness.toString()); console.log('Sending ' + brightness + ' out the serial port'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function showPortOpen() {\n console.log(\"port open. Data rate: \" + myPort.baudRate);\n}", "function openPort() {\n\tconsole.log('port open');\n\tconsole.log('baud rate: ' + myPort.options.baudRate);\n}", "function showPortOpen() {\n console.log('port open. Data rate: ' + myPort.baudRate);\n}", "function showPortOpen() {\n console.log('port open. Data rate: ' + myPort.baudRate);\n}", "function onOpen() {\n console.log('Port Open');\n console.log(`Baud Rate: ${port.options.baudRate}`);\n const outString = String.fromCharCode(output);\n console.log(`Sent:\\t\\t${outString}`);\n port.write(outString);\n}", "function showPortOpen() {\n console.log('Serial port open. Data rate: ' + serial.baudRate);\n }", "function openPort() {\n var brightness = 0; // the brightness to send for the LED\n console.log('port open');\n console.log('baud rate: ' + myPort.baudRate);\n\n // since you only send data when the port is open, this function\n // is local to the openPort() function:\n function sendData() {\n // convert the value to an ASCII string before sending it:\n myPort.write(brightness.toString());\n console.log('Sending ' + brightness + ' out the serial port');\n // increment brightness by 10 points. Rollover if > 255:\n if (brightness < 255) {\n brightness+= 10;\n } else {\n brightness = 0;\n }\n }\n // set an interval to update the brightness 2 times per second:\n setInterval(sendData, 500);\n}", "function openPort() {\r\n port.write('Success', function(err) {\r\n if (err) {\r\n return console.log('Error on write: ', err.message);\r\n }\r\n console.log('Serialport Connection Available');\r\n })\r\n }", "function showPortIsOpen() {\n console.log('The port is open. Data rate: ' + port.options.baudRate);\n}", "function sendToSerial(data) {\n console.log(\"sending to serial: \" + data);\n port.write(data);\n}", "function sendSerialData() {\n if(serial.isOpen()) {\n //format data in JSON\n data = JSON.stringify({\n editDelta: editDelta,\n unviewed: totalUnviewedChanges\n });\n serial.write(data + '\\n');\n console.log(\"Send '\" + data + \"' to serial\");\n }\n else {\n console.log(\"Serial port not open\");\n }\n}", "function sendSerialData() {\n\t\tif (isLoaded()) {\n\t\t\t// Beggining and ending patterns that signify port has responded\n\t\t\t// chr(2) and chr(13) surround data on a Mettler Toledo Scale\n\t\t\tqz.setSerialBegin(chr(2));\n\t\t\tqz.setSerialEnd(chr(13));\n\t\t\t// Baud rate, data bits, stop bits, parity, flow control\n\t\t\t// \"9600\", \"7\", \"1\", \"even\", \"none\" = Default for Mettler Toledo Scale\n\t\t\tqz.setSerialProperties(\"9600\", \"7\", \"1\", \"even\", \"none\");\n\t\t\t// Send raw commands to the specified port.\n\t\t\t// W = weight on Mettler Toledo Scale\n\t\t\tqz.send(document.getElementById(\"port_name\").value, \"\\nW\\n\");\n\t\t\t\n\t\t\t// Automatically called when \"qz.send()\" is finished waiting for \n\t\t\t// a valid message starting with the value supplied for setSerialBegin()\n\t\t\t// and ending with with the value supplied for setSerialEnd()\n\t\t\twindow['qzSerialReturned'] = function(portName, data) {\n\t\t\t\tif (qz.getException()) {\n\t\t\t\t\talert(\"Could not send data:\\n\\t\" + qz.getException().getLocalizedMessage());\n\t\t\t\t\tqz.clearException(); \n\t\t\t\t} else {\n\t\t\t\t\tif (data == null || data == \"\") { // Test for blank data\n\t\t\t\t\t\talert(\"No data was returned.\")\n\t\t\t\t\t} else if (data.indexOf(\"?\") !=-1) { // Test for bad data\n\t\t\t\t\t\talert(\"Device not ready. Please wait.\")\n\t\t\t\t\t} else { // Display good data\n\t\t\t\t\t\talert(\"Port [\" + portName + \"] returned data:\\n\\t\" + data);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t}", "function openPort() {\n serialPort.on('open', openPort); // called when the serial port opens\n\n var brightness = 'H'; // the brightness to send for the LED\n console.log('port open');\n //console.log('baud rate: ' + SerialPort.options.baudRate);\n \n // since you only send data when the port is open, this function\n // is local to the openPort() function:\n function sendData() {\n // convert the value to an ASCII string before sending it:\n serialPort.write(brightness.toString());\n console.log('Sending ' + brightness + ' out the serial port');\n }\n // set an interval to update the brightness 2 times per second:\n //setInterval(sendData, 1500);\n\n var x = 0;\n var intervalID = setInterval(function () {\n\n // Your logic here\n sendData();\n\n if (++x === 2) {\n clearInterval(intervalID);\n }\n }, 1000);\n}", "function openPort() {\n io.sockets.on('connection', function (socket) {// WebSocket Connection\n var seedValue = 0; //static variable for current status\n console.log('User connected..');\n socket.on('command', function(data) { //get command status from client\n myPort.write(data.toString());\n console.log('Command sent to the serial port' + ' ' + data);\n });\n });\n}", "function gotOpen() {\n console.log(\"Serial Port is Open\");\n}", "function gotOpen() {\n console.log(\"Serial Port is Open\");\n}", "function gotOpen() {\n print(\"Serial Port is Open\");\n}", "function gotOpen() {\n print(\"Serial Port is Open\");\n}", "function gotOpen() {\n print(\"Serial Port is open!\");\n}", "open(port) {\n\n var me = this;\n\n return new Promise(function(resolve, reject) {\n\n let serialOptions = {\n baudRate: me.options.baudRate\n };\n\n if(me.options.bindingOptions) {\n serialOptions.bindingOptions = me.options.bindingOptions;\n }\n\n // Do this last, since the caller will have their callback called\n // when the port is opened\n me.port = new SerialPort(port, serialOptions, function(err) {\n\n if(err) {\n reject(err);\n } else {\n\n me._configure()\n .then(function() {\n // success!\n me.isReady = true;\n me.emit('open');\n\n resolve();\n })\n .catch(function(err) {\n // configure failed\n reject(err);\n });\n }\n\n });\n\n // Call event handler on serial port error\n me.port.on('error', me._onSerialError.bind(me));\n\n // call the onData function when data is received\n me.port.on('data', me._onData.bind(me));\n\n // event when the port is closed or disconnected\n me.port.on('close', function(err) {\n\n me._flushRequestQueue();\n\n // pass up to our listeners. If port was disconnected\n // (eg remove usb cable), err is an Error object with\n // err.disconnected = true. We also get here if our\n // owner calls 'close'\n me.emit('close', err);\n\n me.isReady = false;\n me.port = null;\n this.push(null);\n });\n\n });\n\n }", "function gotOpen() {\n println(\"Serial Port is Open\");\n}", "function startListeningToSerialPort(conn) {\n\n SerialPort.list()\n .then((ports) => {\n console.log('PORTS AVAILABLE: ', ports);\n\n var arduinoPort = ports.filter(port => port.manufacturer === \"Arduino (www.arduino.cc)\")[0];\n console.log('arduinoPort: ' , arduinoPort);\n\n if (arduinoPort) {\n const PORT_NAME = arduinoPort.comName;\n\n // TODO: i think serialport automatically sets the baudRate for us when we\n // open a port...it uses the BaseBinding.getBaudRate() function todo this.\n // ==> DOUBLE CHECK THIS\n const port = SerialPort(PORT_NAME);\n\n port.on('open', () => {\n console.log('ARDUINO PORT is now open')\n console.log('calling delimiterSetupAndParse()');\n delimiterSetupAndParse(port,conn);\n\n // old stuff -- will remove soon\n electronSerialportDemoStuff();\n });\n\n port.on('error', (err) => {\n console.log('error: ', err.message);\n });\n }\n })\n .catch((err) => {\n throw err;\n });\n}", "function start(port){\n console.log(\"Finializing SP Connection\");\n port.on('data', gotData);\n sp = port;\n console.log(\"Setting Full Speed\");\n sp.send(fullSpeed);\n}", "async open()\n { \n // Open serial port\n await new Promise((resolve, reject) => {\n this.serialPort.open(function(err) { \n if (err)\n reject(err);\n else\n resolve();\n });\n });\n\n // Flush any data sitting in buffers\n await new Promise((resolve, reject) => {\n this.serialPort.flush(function(err) { \n if (err)\n reject(err);\n else\n resolve();\n });\n });\n\n // Receive data handler\n this.serialPort.on('data', this.onReceive.bind(this));\n }", "function sendData() {\n // convert the value to an ASCII string before sending it:\n myPort.write(brightness.toString());\n console.log('Sending ' + brightness + ' out the serial port');\n // increment brightness by 10 points. Rollover if > 255:\n if (brightness < 255) {\n brightness+= 10;\n } else {\n brightness = 0;\n }\n }", "function gotOpen() {\n infoData=\"Serial Port is Open\";\n println(\"Serial Port is Open\");\n}", "function gotOpen() {\n infoData=\"Serial Port is Open\";\n println(\"Serial Port is Open\");\n}", "openPort() {\n console.log('TabbyDRO::openPort');\n // if you get a good Bluetooth serial connection:\n app.clear();\n app.notify(\"Connected to: \" + app.macAddress);\n\n // change the button's name:\n connectButton.innerHTML = \"Disconnect\";\n connectButton.classList.remove('disabled');\n\n // set up a listener to listen for value terminators\n bluetoothSerial.subscribe(';', function (data) {\n app.update(data);\n });\n }", "function connectSerial(){\n let SerialPort = require('serialport');\n let ByteLength = SerialPort.parsers.ByteLength;\n\n let port = new SerialPort('COM6', { // PORT path depends on the device.\n baudRate: 9600, \n parity : 'none',\n stopBits: 1,\n flowControl : false\n },\n function(err){\n if(err){\n console.log('COM path is undefined. Trying to reconnect...');\n re_connectSerial();\n } else {\n console.log('Device connected.');\n socket.emit('device_connected', { \n data: { \n type: 'Connected', \n tool: toolSettings.tool_name,\n date_time: moment(new Date()).format()\n }\n });\n }\n });\n\n \n // let isLoaderCount = 0;\n // let isUnloaderCount = 0;\n \n const parser = port.pipe(new ByteLength({ length: 4 })); // Piping data from PLC, plc sends 4 byte data [STX] 2 3 [ETX].\n \n parser.on('data', function(data){ // Parse data from the port.\n //console.log(data);\n if(data){\n\n let rawData = data.toString();\n let rawDataRefined = rawData.slice(1, 3);\n \n /**\n * ===== PLC to SerialPort data param =====\n * \n * L0 -- param from Loader sensor\n * U1 -- param from Unloader sensor\n * \n */\n\n if(rawDataRefined == 'L0'){ // If data signal is from the Loader,\n\n // isLoaderCount = isLoaderCount + 1;\n // console.log('Loader: ', isLoaderCount);\n\n // if(isLoaderCount == 50){\n // console.log('Loader sending input to server...');\n let signalFromLoader = {\n data_uuid: uuidv1(),\n date_time: moment(new Date()).format(),\n tool_id: toolSettings.tool_name,\n param: rawDataRefined,\n position: 'LOADER',\n value: 50\n }\n\n socket.emit('device_data', signalFromLoader); // Send sinalFromLoader object to Shards Server.\n isLoaderCount = 0;\n // }\n \n } else if (rawDataRefined == 'U1'){ // Else if data signal is from the Unloader,\n\n // isUnloaderCount = isUnloaderCount + 1;\n\n // console.log('Unloader: ', isUnloaderCount);\n // if(isUnloaderCount == 50){\n \n // console.log('Unloader sending outs to server...');\n let signalFromUnloader = {\n data_uuid: uuidv1(),\n date_time: moment(new Date()).format(),\n tool_id: toolSettings.tool_name,\n param: rawDataRefined,\n position: 'UNLOADER',\n value: 50\n }\n\n socket.emit('device_data', signalFromUnloader); // Send sinalFromUnloader object to Shards Server.\n isUnloaderCount = 0;\n // }\n \n }\n\n }\n\n });\n\n port.on('close', function(){ // port event listener when disconnected invoke reconenct\n console.log('Device disconnected. Trying to reconnect...');\n socket.emit('device_disconnected', { \n data: { \n type: 'Disconnected', \n tool: toolSettings.tool_name,\n date_time: new Date()\n }\n });\n\n re_connectSerial();\n });\n \n port.on('error', function(err){ // port event listener when disconnected invoke reconenct\n console.log(err.message);\n console.log('Error occured. Trying to reconnect...');\n re_connectSerial();\n });\n }", "async write(data, encoding)\n {\n await new Promise((resolve, reject) => {\n //console.log(\"TX:\", data);\n this.serialPort.write(data, encoding, function(err) { \n if (err)\n reject(err);\n else\n resolve();\n });\n });\n }", "function sendToSerial(data){\n var objFromBuffer = JSON.parse(data);\n console.log(\"sending to serial: \", objFromBuffer.data);\n if(objFromBuffer.data !== undefined){\n myPort.write(objFromBuffer.data); \n }\n}", "async function star_serial_communication() {\n //lee todos los puertos del sistema\n const ports = await serial_port.list()\n var i = 0;\n //imprime los puertos con dispositivos disponibles\n ports.forEach((port, i) => {\n if (port.manufacturer != undefined) {\n console.log(i + '. ' + port.comName + \" - \" + port.manufacturer);\n }\n });\n //solisita la eleccion de uno de los puertos\n console.log(\"Marque el numero del puerto al que se desea conectar\");\n var stdin = process.openStdin();\n stdin.addListener('data', function (data) {\n const dataString = data.toString().trim();\n console.log(\"connecting to: \" + ports[parseInt(dataString)].comName);\n const portPath = ports[parseInt(dataString)].comName.toString().trim();\n console.log(portPath);\n //inicializa el puerto\n const port = new serial_port(portPath, {\n baudRate: 9600\n });\n\n const parser = port.pipe(new Readline({ delimiter: \"\\r\\n\" }));\n\n //declara los eventos de apertura entrada y error del puerto\n port.on('open', function () {\n port_state = true;\n console.log('connetion is opened');\n });\n\n parser.on('data', function (data) {\n console.log(data);\n if ((data + '').includes(\"Ready\")) {\n port_state = true;\n } else {\n data = data.toString().replace('\\r\\n', '').split(',');\n io.sockets.emit('read_from_arduino', {\n \"posicion\": data[0],\n \"iman\": data[1],\n \"tamanno_disc\": data[2],\n \"confirmacion\" : data[3]\n });\n }\n });\n\n port.on('error', function (err) {\n console.log(err);\n });\n\n port.on('close', function () {\n console.log('port closed');\n });\n\n send_to_arduino = function (data) {\n if (port == undefined) {\n throw \"port is undefined\"\n } else if (port_state != true) {\n throw \"port isn't connected\"\n } else {\n port.write(data, function (err, results) {\n console.log('Sent: ' + data);\n });\n }\n }\n\n io.on('connection', function (socket) {\n socket.on('send_to_arduino', function (data) {\n send_to_arduino(data);\n });\n });\n\n });\n}", "function serialListener(debug)\n{\n var receivedData = \"\";\n serialPort = new SerialPort(portName, {\n baudrate: 9600,\n // defaults for Arduino serial communication\n dataBits: 8,\n parity: 'none',\n stopBits: 1,\n flowControl: false\n });\n \n serialPort.on(\"open\", function () {\n// console.log('open serial communication');\n // Listens to incoming data\n serialPort.on('data', function(data) {\n receivedData += data.toString();\n if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('B') >= 0) {\n sendData = receivedData .substring(receivedData .indexOf('B') + 1, receivedData .indexOf('E'));\n receivedData = '';\n }\n // send the incoming data to browser with websockets.\n \n \n if(sendData.length != 0){\n if(codeTemp != sendData){\n codeTemp=sendData;\n trys = trys - 1;// -1 vie\n if (essai(sendData,code)==true){\n\n trys=99;\n }\n if (trys <= 0 ){\n socketServer.emit('updateData', '0:BOOOOM');\n\n }else{\n socketServer.emit('updateData', trys+':'+sendData);\n }\n }\n }\n //SocketIO_serialemit(sendData);\n //EE.on('update');\n \n }); \n }); \n}", "function electronSerialportDemoStuff() {\n SerialPort.list((err, ports) => {\n console.log('ports', ports);\n if (err) {\n document.getElementById('error').textContent = err.message\n return\n } else {\n document.getElementById('error').textContent = ''\n }\n\n if (ports.length === 0) {\n document.getElementById('error').textContent = 'No ports discovered'\n }\n\n const headers = Object.keys(ports[0])\n const table = createTable(headers)\n tableHTML = ''\n table.on('data', data => tableHTML += data)\n table.on('end', () => document.getElementById('ports').innerHTML = tableHTML)\n ports.forEach(port => table.write(port))\n table.end();\n })\n}", "function _setupSerialConnection(port) {\n debug.log('Trying to connect to Smart Meter via port: ' + port);\n\n var received = '';\n\n lineReader.eachLine(port, function(line, last) {\n received += line + '\\r\\n';\n\n var startCharPos = received.indexOf(config.startCharacter);\n var endCharPos = received.indexOf(config.stopCharacter);\n\n if (endCharPos >= 0 && endCharPos < startCharPos) {\n received = received.substr(endCharPos + 1);\n startCharPos = -1;\n endCharPos = -1;\n }\n\n // Package is complete if the start- and stop character are received\n const crcReceived = endCharPos >= 0 && received.length > endCharPos + 4;\n if (startCharPos >= 0 && endCharPos >= 0 && crcReceived) { \n var packet = received.substr(startCharPos, endCharPos - startCharPos);\n const expectedCrc = parseInt(received.substr(endCharPos + 1, 4), 16);\n received = received.substr(endCharPos + 5);\n\n var crcOk = true;\n if (crcCheckRequired) {\n crcOk = checkCrc(packet + '!', expectedCrc);\n }\n\n if (crcOk) {\n var parsedPacket = parsePacket(packet);\n\n // Verify if connected to the correct serial port at initialization\n if (!serialPortUsed) {\n if (parsedPacket.timestamp !== null) {\n debug.log('Connection with Smart Meter established');\n serialPortUsed = port;\n\n constructor.emit('connected', port);\n } else {\n _tryNextSerialPort();\n }\n }\n\n debug.writeToLogFile(packet, parsedPacket);\n\n constructor.emit('reading-raw', packet);\n\n if (parsedPacket.timestamp !== null) {\n constructor.emit('reading', parsedPacket);\n } else {\n constructor.emit('error', 'Invalid reading');\n }\n } else {\n constructor.emit('error', 'Invalid CRC');\n }\n }\n });\n}", "function SendPortSync() {\n}", "function Accelerometer(options) {\n var sp,\n self = this;\n\n options = options || {};\n events.EventEmitter.call(this);\n\n try {\n fs.statSync(devicePath);\n } catch (e) {\n throw new Error('device not found');\n }\n sp = new SerialPort(devicePath, {\n baudRate: 115200,\n });\n\n this.close = function () {\n sp.close();\n };\n\n sp.on('open', function () {\n logger.info('start ap..', startAccessPoint);\n\n sp.write(startAccessPoint);\n sp.write(accDataRequest);\n\n sp.on('data', function (data) {\n var x, y, z, on,\n timeout = 0,\n buf = new Buffer(data);\n if (data.length >= 7) {\n x = buf.readInt8(5);\n y = buf.readInt8(4);\n z = buf.readInt8(6);\n on = (buf[3] === 1);\n if (on) {\n off_times = 0;\n if (options.freeFallDetection) {\n //console.log('x:' + x + ' y:' + y + ' z:' + z);\n if (Math.abs(x) > FREE_FALL_THRESHOLD && Math.abs(y) > FREE_FALL_THRESHOLD && \n Math.abs(z) > FREE_FALL_THRESHOLD) {\n logger.info('freefall: ' + ' x:' + x + ' y:' + y + ' z:' + z);\n self.emit('freefall');\n } \n }\n } else {\n off_times++;\n }\n } else {\n off_times++;\n //logger.debug((new Date()).getTime() + ' invalid data', buf);\n }\n if (off_times > MAX_OFF_TIMES) {\n off_times = 0;\n timeout = POLL_INTERVAL;\n } \n setTimeout(function () {sp.write(accDataRequest); }, timeout);\n });\n sp.on('close', function (err) {\n logger.info('port closed');\n self.emit('close');\n });\n sp.on('error', function (err) {\n logger.error('error', err);\n self.emit('error', err);\n });\n });\n}", "connectCOM() {\n var sp = require(\"serialport\");\n\n // Disconnect currently connected ports (if any).\n /* To be implemented */\n\n var modport_text = [];\n var modport_value = [];\n\n // Read the selected COM port from the dropdown. If no COM has been selected, modport_value will be '0'.\n for (var i = 0; i < 4; i++) {\n var modport = document.getElementById(\"mod\" + i + \"select\");\n modport_text.push(modport.options[modport.selectedIndex].text);\n modport_value.push(modport.options[modport.selectedIndex].value);\n }\n\n // Make sure this works: If a port is selected, add it to this.ports (otherwise -1 for error/ignore).\n for (var i = 0; i < modport_value.length; i++) {\n // the `new` command opens a connection.\n if (modport_value[i] != \"0\") {\n this.ports[i] = new sp(modport_text[i], {\n baudRate: 9600,\n parser: new sp.parsers.Readline(\"\\r\\n\"),\n });\n this.ports[i].on(\"open\", () => {});\n } else {\n this.ports[i] = -1;\n }\n }\n }", "function Write(data) {\n Serial.Write({\n Command: data,\n Debug: 'False',\n Port: ArdPort,\n });\n}", "function start(port) {\n\tif (!port) {\n\t\tport = DEFAULT_SERIAL_PORT;\n\t}\n\n\t// Init serial port connection\n\tserialPort = new SerialPort(port, {\n\t baudRate: BAUD_RATE,\n\t parser: SP.parsers.readline(\"\\r\")\n\t});\n\n\t// Listen for \"open\" event form serial port\n\tserialPort.on('open', () => {\n\t console.log('Serial Port opened');\n\n\t // Listen for \"data\" event from serial port\n\t serialPort.on('data', handleData);\n\t});\n\n\tserialPort.on('error', (err) => {\n\t\tconsole.error('Serial Port Error: ', err);\n\t});\n\n\tserialPort.on('close', () => {\n\t\tconsole.log('Serial Port connection closed.');\n\t});\n}", "function serialListener(debug){\n var receivedData = \"\";\n serialPort = new SerialPort(portName, {\n baudrate: 9600,\n // defaults for Arduino serial communication\n dataBits: 8,\n parity: 'none',\n stopBits: 1,\n flowControl: false\n });\n \n serialPort.on(\"open\", function () {\n console.log('open serial communication');\n // Listens to incoming data\n serialPort.on('data', function(data) {\n receivedData = data.toString();\n sendData = receivedData;\n // receivedData = \"\";\n currentValue = sendData;\n socketServer.emit('update', {switchValue:currentValue});\n console.log(receivedData);\n // if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('S') >= 0) {\n // sendData = receivedData;\n // receivedData = '';\n // }\n // check current-value is different pre-value\n // if(currentValue != sendData){\n // currentValue = sendData;\n // socketServer.emit('update', {switchValue:currentValue});\n // console.log(currentValue);\n // }\n }); \n }); \n}", "function SerialPortCtrl($scope, SerialPortOptions) {\n\n\t// Set the SerialPortOptions and monitor for any changes to the options\n\t$scope.serialPortOptions = SerialPortOptions;\n\t$scope.$watch( function () { return SerialPortOptions; } , function() { $scope.serialPortOptions = SerialPortOptions; }, true);\n\n\t// Buffer to store the incoming data\n\t$scope.buffer = \"\";\n\n\n\t/**\n\t * Get all the serial ports.\n\t */\n\t$scope.getPorts = function() {\n\n\t\t//Get the serialport listings\n\t\trequire(\"serialport\").list(function (err, ports) {\n\n\t\t\t// Set the response\n\t\t\t// Need to use $scope.$apply() because this is within\n\t\t\t// another function.\n\t\t\t// http://stackoverflow.com/questions/10179488/the-view-is-not-updated-in-angularjs\n\t\t\t$scope.$apply(function() { SerialPortOptions.ports = ports; });\n\n\t\t\t// Display the port info to the console\n\t\t\tvar portInfo = \"\";\n\t\t\tports.forEach(function (port) {\n\t\t\t\tconsole.log(port.comName);\n\t\t\t\tconsole.log(port.pnpId);\n\t\t\t\tconsole.log(port.manufacturer);\n\n\t\t\t});\n\t\t});\n\t}\n\n\t/**\n\t * Read data from the serial port\n\t */\n\t$scope.readData = function() {\n\n\t\t//Initialize the serial port\n\t\tvar SerialPort = require(\"serialport\").SerialPort\n\t\tvar serialPort = new SerialPort(\"COM14\", { baudrate: 115200 });\n\n\t\t//Open the serial data\n\t\tserialPort.open(function () {\n\t\t\tconsole.log('open');\n\n\t\t\t// Read in the data\n\t\t\tserialPort.on('data', function(data) {\n\t\t\t\tconsole.log('data received: ' + data);\n\n\t\t\t\t//Display the data\n\t\t\t\t// Need to use $scope.$apply() because this is within\n\t\t\t\t// another function.\n\t\t\t\t// http://stackoverflow.com/questions/10179488/the-view-is-not-updated-in-angularjs\n\t\t\t\t//$scope.$apply(function() { $scope.ReadBuffer += data; });\n\t\t\t\t//$scope.serialData += data;\n\t\t\t\t//$scope.$apply(function() { $scope.serialData += data; });\n\t\t\t\t$scope.$apply(function() { SerialPortOptions.buffer = data });\n\t\t\t\t$scope.buffer = (data + $scope.buffer).substr(0, 5000);\n\n\t\t\t});\n\n\t\t});\n\t}\n\n}", "function writeAndDrain (data, callback) {\r\n console.log('Sending \\''+data+'\\'');\r\n serialPort.write(data, function () {\r\n serialPort.drain(callback);\r\n });\r\n}", "function sendSerialData(message) {\n try {\n port.write(message+`\\n`);\n lastSentMessage = message;\n } catch (e) {\n lastSentMessage = `ERROR: serial send error.`\n console.warn(`can't send data!`);\n }\n}", "function setBaudrate(_baudrate) {\n // TODO: Check the supplied baudrate value to ensure that it is reasonable\n // Set the global baudrate variable\n baudrate = _baudrate;\n}", "sendSendSerialPortsMessageToServer() {\n var message = {};\n this.sendMessageToServer('sendSerialPorts', message);\n }", "function pollData(){\r\n serial_counter +=1;\r\n\r\n //console.log(`\\n-------------------- NEW LOOP #${iter} --------------------\\n`);\r\n if(serial_counter===20){\r\n pollCharacter = [0x11];\r\n //console.log(\"1. Polled Serial Port\");\r\n myPort.write(pollCharacter);\r\n serial_counter=0;\r\n }\r\n //console.log(\"2. GET Procedure\");\r\n expressGETBuffer();\r\n expressGETConfig();\r\n //expressPOSTBuffer();\r\n}", "function serialEvent() {\n inData = Number(serial.read());\n}", "initSerial(comName) {\n return new Promise((resolve, reject) => {\n this._closeSerialPort()\n .then(() => { return this._createSerialPort(comName); })\n .then(() => {\n resolve();\n console.log(`movuino connected @ serial port ${comName}`);\n })\n .catch((err) => {\n console.error('error opening serial port : ' + err.message);\n });\n });\n }", "function connect(port, exitCallback) {\n if (!args.quiet) if (! args.nosend) log(\"Connecting to '\"+port+\"'\");\n var currentLine = \"\";\n var exitTimeout;\n Espruino.Core.Serial.startListening(function(data) {\n // convert ArrayBuffer to string\n data = String.fromCharCode.apply(null, new Uint8Array(data));\n // Now handle...\n currentLine += data;\n while (currentLine.indexOf(\"\\n\")>=0) {\n var i = currentLine.indexOf(\"\\n\");\n log(args.espruinoPrefix + currentLine.substr(0,i)+args.espruinoPostfix);\n currentLine = currentLine.substr(i+1);\n }\n // if we're waiting to exit, make sure we wait until nothing has been printed\n if (exitTimeout && exitCallback) {\n clearTimeout(exitTimeout);\n exitTimeout = setTimeout(exitCallback, 500);\n }\n });\n if (! args.nosend) {\n Espruino.Core.Serial.open(port, function(status) {\n if (status === undefined) {\n console.error(\"Unable to connect!\");\n return exitCallback();\n }\n if (!args.quiet) log(\"Connected\");\n // Do we need to update firmware?\n if (args.updateFirmware) {\n var bin = fs.readFileSync(args.updateFirmware, {encoding:\"binary\"});\n var flashOffset = args.firmwareFlashOffset || 0;\n Espruino.Core.Flasher.flashBinaryToDevice(bin, flashOffset, function(err) {\n log(err ? \"Error!\" : \"Success!\");\n exitTimeout = setTimeout(exitCallback, 500);\n });\n } else {\n // figure out what code we need to send (if any)\n sendCode(function() {\n exitTimeout = setTimeout(exitCallback, 500);\n });\n }\n // send code over here...\n\n // ----------------------\n }, function() {\n log(\"Disconnected.\");\n });\n } else {\n sendCode(function() {\n exitTimeout = setTimeout(exitCallback, 500);\n });\n }\n}", "function list_port() {\n SerialPort.list(function (err, ports) {\n ports.forEach(function(port) {\n console.log(port.comName);\n });\n });\n}", "scanAndConnect() {\n // When a device is found...\n btSerial.on('found', (address, name) => {\n winston.debug('Found ' + name)\n winston.debug('address: ' + address)\n\n // Check if it's the thermometer\n if (name === 'FINGGAL LINK IRSTP3') {\n winston.debug('Identified target device')\n winston.debug('Searching for channels...')\n\n // if it is, search for open serial ports\n btSerial.findSerialPortChannel(\n address,\n channel => {\n winston.debug('Found channel: ' + channel)\n winston.debug('Attempting to connect...')\n\n // Once found, connect on that channel\n btSerial.connect(\n address,\n channel,\n () => {\n this.emit('connect')\n winston.debug('Successfully connected!!')\n\n // Data will start flowing once connected. Data\n // could be a keep alive REQ signal, a disconnect signal,\n // or measurement data.\n btSerial.on('data', buffer => {\n winston.debug('Received bytes: ' + buffer.byteLength)\n winston.debug('byte: ' + buffer.toString('hex'))\n\n // Regardless of the type of data we always need to send\n // an ACK to keep the connection alive.\n const ACK = Buffer.from('AD01', 'hex')\n btSerial.write(ACK, (error, bytesWritten) => {\n winston.debug('sent ACK! ')\n if (error) winston.error(error)\n })\n\n // If the the data is a measurement, snag the temp\n if (this._bufferContainsMeasurement(buffer)) {\n const temp = this._extractTemp(buffer)\n winston.debug('Extracted temp: ' + temp)\n this.emit('data', temp)\n }\n })\n },\n // This block is called if we fail to connect\n () => {\n winston.error('Failed to connect!')\n emit('error', new Error('Failed to connect to thermometer!'))\n }\n )\n },\n // This block is called if we can't find an open channel\n () => {\n winston.error('Unable to find any channels.')\n emit('error', new Error('Failed to find any channels'))\n }\n )\n }\n })\n\n // Pass errors up\n btSerial.on('failure', error => {\n winston.error(error)\n this.emit('error', error)\n })\n\n // Pass on close events\n btSerial.on('closed', () => {\n winston.debug('Connection closed')\n this.emit('disconnect')\n })\n\n // Pass on finished events\n btSerial.on('finished', () => {\n winston.debug('Finished scanning')\n this.emit('finishedScan')\n })\n\n // Now that everything is configured, begin scanning\n btSerial.inquire()\n winston.debug('Beginning scan')\n }", "function readSerialData(data) {\n console.log(data.toString());\n sendit({method: 'data', data: data.toString()});\n}", "buildModemInterface() {\n return new Promise((resolve, reject) => {\n this.log(`starting modem interface on port ${this.uri} @ ${this.baud_rate}`);\n let serial_port = new SerialPort(this.uri, {\n baudRate: this.baud_rate\n });\n serial_port.on('open', () => {\n resolve(serial_port);\n });\n serial_port.on('error', (err) => {\n reject(err);\n });\n serial_port.on('data', (data) => {\n // buffer the received data\n this.response_buffer += data.toString();\n // check if the response code exists in our buffered data\n this.response_codes.forEach((code) => {\n if (this.response_buffer.toUpperCase().indexOf(code) > -1) {\n this.handleModemResponse({\n data: this.response_buffer.replace(code, '').trim(), \n code: code\n });\n this.response_buffer = '';\n }\n })\n });\n return serial_port;\n });\n }", "function create_serial() {\r\n serial = new p5.SerialPort(); // make a new instance of the serialport library\r\n serial.on(\"list\", printList); // set a callback function for the serialport list event\r\n serial.on(\"connected\", serverConnected); // callback for connecting to the server\r\n serial.on(\"open\", portOpen); // callback for the port opening\r\n serial.on(\"data\", serialEvent); // callback for when new data arrives\r\n serial.on(\"error\", serialError); // callback for errors\r\n serial.on(\"close\", portClose); // callback for the port closing\r\n \r\n serial.list(); // list the serial ports\r\n serial.open(portnumber_ans); // open a serial port\r\n // get the list of ports:\r\n function printList(portList) {\r\n // portList is an array of serial port names\r\n for (var i = 0; i < portList.length; i++) {\r\n // Display the list the console:\r\n console.log(i + \" \" + portList[i]);\r\n }\r\n }\r\n \r\n function serverConnected() {\r\n console.log(\"connected to server.\");\r\n }\r\n \r\n function portOpen() {\r\n console.log(\"the serial port opened.\");\r\n }\r\n \r\n function serialEvent() {\r\n // read a string from the serial port:\r\n var inString = serial.readLine();\r\n // check to see that there's actually a string there:\r\n \r\n if (inString.length > 0) {\r\n // convert it to a number:\r\n //split the values at each comma\r\n // inData = Number(inString);\r\n var inDataArray = split(inString, \",\");\r\n \r\n //set variables to the appropriate index of this array\r\n //turn these values from a string to a number\r\n sensor1 = Number(inDataArray[0]);\r\n sensor2 = Number(inDataArray[1]);\r\n sensor3 = Number(inDataArray[2]);\r\n }\r\n }\r\n \r\n function serialError(err) {\r\n console.log(\"Something went wrong with the serial port. \" + err);\r\n }\r\n \r\n function portClose() {\r\n console.log(\"The serial port closed.\");\r\n }\r\n }", "function openHandler (self) {\n\tvar parser = new xml2js.Parser();\n\tvar buffer = \"\";\t// read buffer.\n\n if (TRACE) {\t\n \tconsole.log('serial device open');\n }\n \n self.emit(\"open\");\n\n\t// add serial port data handler\t\n\tself.serialPort.on('data', function(data) {\n\t\tbuffer += data.toString() + \"\\r\\n\";\t\t// append to the read buffer\n\t\tif ( data.toString().indexOf('</') == 0 ) {\t\t// check if last part of XML element.\n\t\t\t\n\t\t\t// try to parse buffer\n\t\t\tparser.parseString(buffer, function (err, result) {\n\t\t\t\tif (err) {\n\t\t\t\t\tconsole.log(\"err: \" + err);\n\t\t\t\t\tconsole.log('data received: ' + buffer);\n\t\t\t\t}\n\t\t\t\telse if (result.InstantaneousDemand) {\n\t\t\t\t\tvar timestamp = parseInt( result.InstantaneousDemand.TimeStamp );\n\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\tvar demand = parseInt( result.InstantaneousDemand.Demand, 16 );\n\t\t\t\t\tdemand = demand < 0x80000000 ? demand : - ~demand - 1;\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.log(\"demand: \" + timestamp.toLocaleString() + \" : \" + demand);\n\t\t\t\t\t}\n\t\t\t\t \t\n\t\t\t\t\t// emit power event\n\t\t\t\t\tvar power = { value: demand, unit: \"W\", timestamp: timestamp.toISOString() };\n\t\t\t\t\tself.emit(\"power\", power);\n\t\t\t\t}\n\t\t\t\telse if (result.CurrentSummationDelivered) {\n\t\t\t\t\tvar timestamp = parseInt( result.CurrentSummationDelivered.TimeStamp );\n\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\tvar used = parseInt( result.CurrentSummationDelivered.SummationDelivered, 16 );\n\t\t\t\t\tvar fedin = parseInt( result.CurrentSummationDelivered.SummationReceived, 16 );\n\t\t\t\t\tconsole.log(\"sum: \" + timestamp.toLocaleString() + \" : \" + used + \" - \" + fedin);\n\n\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\tvar energyIn = { value: used, unit: \"Wh\" , timestamp: timestamp.toISOString() };\n\t\t\t\t\tvar energyOut = { value: fedin, unit: \"Wh\", timestamp: timestamp.toISOString() };\n\n\t\t\t\t\tself.emit(\"energy-in\", energyIn);\n\t\t\t\t\tself.emit(\"energy-out\", energyOut);\n\t\t\t\t}\n\t\t\t\telse if (result.ConnectionStatus) {\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.log(\"connection status: \" + result.ConnectionStatus.Status);\n\t\t\t\t\t}\n\t\t\t\t\tself.emit(\"connection\", result.ConnectionStatus.Status);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (TRACE) {\n\t\t\t\t\t\tconsole.dir(result);\t// display data read in\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t\tbuffer = \"\";\t// reset the read buffer\n\t\t}\n\t});\n\n\t// Possible commands: get_time, get_current_summation_delivered; get_connection_status; get_instantaneous_demand; get_current_price; get_message; get_device_info.\n\tvar queryCommand = \"<Command><Name>get_connection_status</Name></Command>\\r\\n\";\n\tself.serialPort.write(queryCommand, function(err, results) {\n\t\tself.serialPort.write(\"<Command><Name>get_message</Name></Command>\\r\\n\", function(err, results) {\n\t\t\tself.serialPort.write(\"<Command><Name>get_current_price</Name></Command>\\r\\n\", function(err, results) {\n\t\t\t}); \n\t\t}); \n\t}); \n}", "_createSerialPort(comName) {\n return new Promise((resolve, reject) => {\n if (comName === null) return;\n\n //----------------------- create OSC serial port -----------------------//\n this.serialPort = new osc.SerialPort({\n devicePath: comName, \n bitrate: 115200,\n });\n\n //------------------------- when port is ready -------------------------//\n this.serialPort.once('ready', () => {\n\n ////////// route and emit messages that are not hello\n this.serialPort.on('message', (message) => {\n\n //--------------------------------------------------------------------\n if (message.address === '/movuino') {\n this.emit('osc', 'serial', { address: message.address, args: message.args});\n //--------------------------------------------------------------------\n } else if (message.address === '/wifi/state' && message.args.length > 0) {\n this.info.wifiState = message.args[0];\n if (this.info.wifiState === 1) {\n // when wifiState becomes 1, we need to check the new ip address\n this._serialRpc('/hello')\n .then((hello) => {\n // this.info.name = hello[1];\n this.info.movuinoip = hello[3];\n return this.attachUDPPort();\n })\n .then(() => {\n this.emit('state', {\n wifiState: this.info.wifiState,\n movuinoip: this.info.movuinoip,\n });\n });\n } else {\n this.emit('state', { wifiState: this.info.wifiState });\n }\n //--------------------------------------------------------------------\n } else if (message.address === '/wifi/set' && message.args.length > 3) {\n this.info.ssid = message.args[0];\n this.info.password = message.args[1];\n this.info.hostip = message.args[2];\n\n this.emit('settings', {\n ssid: this.info.ssid,\n password: this.info.password,\n hostip: this.info.hostip,\n });\n }\n });\n\n ////////// catch osc errors and simply ignore them\n this.serialPort.on('error', (err) => { console.log('osc error : ' + err.message); });\n\n ////////// say hello, set ports and config, get wifi credentials \n this._serialRpc('/hello')\n .then((hello) => {\n console.log(hello);\n if (hello[0] === 'movuino') {\n this.info.name = hello[1];\n this.info.wifiState = hello[2];\n this.info.movuinoip = hello[3];\n this.info.movuinoid = hello[4];\n this.info.firmwareVersion = hello[5];\n return this._serialRpc('/ports/get');\n } \n })\n .then((ports) => {\n const inputPort = config.movuinoOscServer.remotePort;\n const outputPort = config.movuinoOscServer.localPort;\n\n if (ports[0] !== inputPort || ports[1] !== outputPort) {\n return this._serialRpc('/ports/set', [\n { type: 'i', value: inputPort },\n { type: 'i', value: outputPort },\n ]);\n }\n\n return Promise.resolve();\n })\n .then(() => {\n return this._serialRpc('/range/set', [\n { type: 'i', value: config.movuinoSettings.accelRange }, // +/- 16g // * 9.81 / 16\n { type: 'i', value: config.movuinoSettings.gyroRange }, // +/- 2000 deg/sec // * 36 / 200\n ]);\n })\n .then(() => { return this._serialRpc('/serial/enable', [{ type: 'i', value: 1 }]); })\n .then(() => { return this._serialRpc('/magneto/enable', [{ type: 'i', value: 1 }]); })\n .then(() => { return this._serialRpc('/frameperiod/set', [{ type: 'i', value: 10 }]); })\n .then(() => { return this._serialRpc('/wifi/get'); })\n .then((credentials) => {\n ////////// if everything went well, emit all needed information and resolve\n this.info.ssid = credentials[0];\n this.info.password = credentials[1];\n this.info.hostip = credentials[2];\n\n this.info.serialPortReady = true;\n\n this.emit('settings', {\n ssid: this.info.ssid,\n password: this.info.password,\n hostip: this.info.hostip,\n name: this.info.name\n });\n\n this.emit('state', {\n serialPortReady: this.info.serialPortReady,\n wifiState: this.info.wifiState,\n movuinoip: this.info.movuinoip,\n });\n\n resolve();\n });\n });\n\n this.serialPort.open();\n });\n }", "function isConnected() {\n\treturn serialPort && serialPort.isOpen();\n}", "async close()\n {\n if (this.serialPort && this.serialPort.isOpen)\n {\n await new Promise((resolve, reject) => {\n this.serialPort.close(function(err) { \n if (err)\n reject(err);\n else\n resolve();\n });\n });\n }\n }", "sendOnPort(portNum) {\n this._sendingPort = portNum;\n }", "function createSerialPort (path) {\r\n return new SerialPort(\r\n path,\r\n {\r\n baudRate: 115200,\r\n autoOpen: false,\r\n }\r\n );\r\n}", "async function uBitOpenDevice(device, callback) {\n const transport = new DAPjs.WebUSB(device)\n const target = new DAPjs.DAPLink(transport)\n let buffer=\"\" // Buffer of accumulated messages\n const parser = /([^.:]*)\\.*([^:]+|):(.*)/ // Parser to identify time-series format (graph:info or graph.series:info)\n \n target.on(DAPjs.DAPLink.EVENT_SERIAL_DATA, data => {\n buffer += data;\n let firstNewline = buffer.indexOf(\"\\n\")\n while(firstNewline>=0) {\n let messageToNewline = buffer.slice(0,firstNewline)\n let now = new Date() \n // Deal with line\n // If it's a graph/series format, break it into parts\n let parseResult = parser.exec(messageToNewline)\n if(parseResult) {\n let graph = parseResult[1]\n let series = parseResult[2]\n let data = parseResult[3]\n let callbackType = \"graph-event\"\n // If data is numeric, it's a data message and should be sent as numbers\n if(!isNaN(data)) {\n callbackType = \"graph-data\"\n data = parseFloat(data)\n }\n // Build and send the bundle\n let dataBundle = {\n time: now,\n graph: graph, \n series: series, \n data: data\n }\n callback(callbackType, device, dataBundle)\n } else {\n // Not a graph format. Send it as a console bundle\n let dataBundle = {time: now, data: messageToNewline}\n callback(\"console\", device, dataBundle)\n }\n buffer = buffer.slice(firstNewline+1) // Advance to after newline\n firstNewline = buffer.indexOf(\"\\n\") // See if there's more data\n }\n });\n await target.connect();\n await target.setSerialBaudrate(115200)\n //await target.disconnect();\n device.target = target; // Store the target in the device object (needed for write)\n device.callback = callback // Store the callback for the device\n callback(\"connected\", device, null) \n target.startSerialRead()\n return Promise.resolve()\n}", "function sendData(data) {\n /*\n if(this.port != null && this.parser != null){\n\n if(bufferData){\n port.write(Buffer.from(data.mx));\n console.log(data.mx);\n }else{\n port.write(data.mx);\n console.log(data.mx);\n }\n }\n */\n //port.write(\"X\" + toString(data.mx) \"Y\" + toString(data.my));\n port.write(\"X\" + data.mx.toString());\n //setInterval(port.write(\"X\" + data.mx.toString()), 1000);\n //console.log(data.mx.toString());\n\n}", "function openHandler (self) {\n\tvar parser = new xml2js.Parser();\n\tvar linenumber = 0;\n\tvar buffer = \"\";\t// read buffer.\n\tvar parseBuffer=\"\"; // for xml parsing\n\tvar tmpBuffer = \"\";\n\tvar line = \"\"; // line read;\n\t//var lines;\n \n winston.info('serial device opened at ...' + new Date());\n \n if (state.FIRST_RUN) {\n\t\tstate.FIRST_RUN = false;\n\t\tself.emit(\"open\");\n\t}\t\n\t\n\t// add serial port data handler\t\n\tself.serialPort.on('data', function(evtdata) {\n\t\tstate.PORT_INITIALIZED = true;\n\t\twinston.silly(\"Receiving data....\");\n\t\tif (newDay()) rolloverDay();\n\t\tline = evtdata.toString();\t\n\t\tbuffer += line;\t\t// append to the read buffer\n\t\ttmpBuffer=\"\";\n\t\tparseBuffer=\"\";\n\t\tvar lines = S(buffer).lines();\n\t\tfor (var i=0; i< lines.length; i++){\n\t\t\ttmpBuffer += lines[i];\n\t\t\tif (lines[i].endsWith('>')){\n\t\t\t\ttmpBuffer += '\\r\\n';\n\t\t\t}\n\t\t\tif ((lines[i].indexOf('</') == 0) && (lines[i].endsWith('>'))){\n\t\t\t\tparseBuffer=tmpBuffer;\n\t\t\t\tlinenumber =0;\n\t\t\t\ttmpBuffer=\"\";\n\t\t\t}\n\t\t}\n\t\tbuffer = tmpBuffer;\n\t\n\t\tif ( parseBuffer != \"\") {\t\t// check if last part of XML element.\n\t\t\twinston.silly('Raw Data:\\n' + parseBuffer);\n\t\t\t\n\t\t\t// try to parse buffer\n\t\t\ttry {\n\t\t\t\tparser.parseString(parseBuffer, function (err, result) {\n\t\t\t\t\tif (err) {\n\t\t\t\t\t\twinston.error(\"parser error: \" + Object.keys(err)[0] +\":\" + Object.values(err)[0]);\n\t\t\t\t\t\twinston.debug(\"details: \" + err + \"\\nRaw Buffer\\n\" + parseBuffer);\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.InstantaneousDemand) {\n\t\t\t\t\t\tvar timestamp = parseInt( result.InstantaneousDemand.TimeStamp );\n\t\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\t\tvar demand = parseInt( result.InstantaneousDemand.Demand, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.InstantaneousDemand.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.InstantaneousDemand.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tdemand = demand < 0x80000000 ? demand : - ~demand - 1;\n\t\t\t\t\t\tdemand = 1000*demand*multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"demand: \" + timestamp.toLocaleString() + \" : \" + demand);\n\t\t\t\t\t\t// emit power event\n\t\t\t\t\t\tvar power = { value: demand, unit: \"W\", timestamp: timestamp.toISOString() };\n\t\t\t\t\t\tstate.POLL_DEMAND = false;\n\t\t\t\t\t\tstate.failCount=0;\n\t\t\t\t\t\t//winston.debug(\"DEMAND POLL FLAG demand:\" + state.POLL_DEMAND + \" , Sum:\" + state.POLL_ENERGY + \" , Current:\"+ state.POLL_USAGE_CURRENT +\" , Last\" + state.POLL_USAGE_LAST );\n\t\t\t\t\t\tif (state.POLL_ENERGY) {\n\t\t\t\t\t\t\tdata.powerTable.add(demand,timestamp);\n\t\t\t\t\t\t\tmqttMsg.add(power,\"demand\");\n\t\t\t\t\t\t\tself.getSumEnergy();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tself.emit(\"demand\", power);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.CurrentSummationDelivered) {;\n\t\t\t\t\t\tvar timestamp = parseInt( result.CurrentSummationDelivered.TimeStamp );\n\t\t\t\t\t\ttimestamp = new Date(dateOffset+timestamp*1000);\n\t\t\t\t\t\tvar used = parseInt( result.CurrentSummationDelivered.SummationDelivered, 16 );\n\t\t\t\t\t\tvar fedin = parseInt( result.CurrentSummationDelivered.SummationReceived, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.CurrentSummationDelivered.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.CurrentSummationDelivered.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\tfedin = fedin * multiplier / divisor;\n\t\t\t\t\t\tdata.energyInToday = used;\n\t\t\t\t\t\tdata.energyIn.add(data.energyInToday,timestamp);\n\t\t\t\t\t\tif (data.energyInYday == 0 ) data.energyInYday = data.energyInToday;\n\t\t\t\t\t\tif (data.energyInThisMonth == 0 ) data.energyInThisMonth = data.energyInToday;\n\t\t\t\t\t\tdata.energyOutToday = fedin;\n\t\t\t\t\t\tdata.energyOut.add(data.energyOutToday,timestamp);\n\t\t\t\t\t\tif (data.energyOutYday == 0 ) data.energyOutYday = data.energyOutToday;\n\t\t\t\t\t\tif (data.energyOutThisMonth == 0 ) data.energyOutThisMonth = data.energyOutToday;\n\t\t\t\t\t\tused = (data.energyInToday - data.energyInYday);\n\t\t\t\t\t\tfedin = (data.energyOutToday - data.energyOutYday);\n\t\t\t\t\t\twinston.info(\"Today used: \" + used.toFixed(2) + \", togrid:\" + fedin.toFixed(2) + \", Month used:\" + (data.energyInToday - data.energyInThisMonth).toFixed(2) +\", togrid:\" + (data.energyOutToday - data.energyOutThisMonth).toFixed(2) );\t\t\t\t\t\n\t\t\t\t\t\tdata.energyOutTMDays = Math.round((timestamp.getTime() - data.energyOutTMStartDate.getTime())/(1000*60*60*24)); \n\t\t\t\t\t\t\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar energyIn = { value: used, unit: \"KWh\" , thismonth: (data.energyInToday - data.energyInThisMonth), lastmonth:data.energyInLastMonth, lifetime:data.energyInToday, timestamp: timestamp.toISOString() };\n\t\t\t\t\t\tvar energyOut = { value: fedin, unit: \"KWh\", thismonth: (data.energyOutToday - data.energyOutThisMonth), lastmonth:data.energyOutLastMonth, lifetime:data.energyOutToday , tmstartdate: data.energyOutTMStartDate.toISOString(), tmdays:data.energyOutTMDays , lmstartdate:data.energyOutLMStartDate.toISOString(), lmenddate:data.energyOutLMEndDate.toISOString(), lmdays: data.energyOutLMDays, timestamp: timestamp.toISOString() };\n\n\t\t\t\t\t\t//self.emit(\"energy-in\", energyIn);\n\t\t\t\t\t\t//self.emit(\"energy-out\", energyOut);\n\t\t\t\t\t\tstate.POLL_ENERGY = false\n\t\t\t\t\t\tmqttMsg.add(energyIn,\"energyin\");\n\t\t\t\t\t\tmqttMsg.add(energyOut,\"energyout\");\n\t\t\t\t\t\tself.getCurrentPeriodUsage();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.CurrentPeriodUsage) {\n\t\t\t\t\t\tvar timestamp = new Date();\n\t\t\t\t\t\tvar startdate = parseInt( result.CurrentPeriodUsage.StartDate );\n\t\t\t\t\t\tstartdate = new Date(dateOffset+startdate*1000);\n\t\t\t\t\t\tvar days = Math.round((timestamp.getTime() - startdate.getTime())/(1000*60*60*24));\n\t\t\t\t\t\tvar used = parseInt( result.CurrentPeriodUsage.CurrentUsage, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.CurrentPeriodUsage.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.CurrentPeriodUsage.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\t//winston.info(\"after divisor, miltiplier - \" + multiplier + \", divisor - \" + divisor);\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"Current Period Usage: \" + timestamp.toLocaleString() + \" : \" + used.toFixed(2) + \" - Days: \" + days + \" - Start Date \" + startdate.toLocaleString());\n\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar currentUsage = { value: used, unit: \"KWh\" , timestamp: timestamp.toISOString() , startdate: startdate.toISOString(), days: days };\n\t\t\t\t\t\t//self.emit(\"usage-current\", currentUsage);\n\t\t\t\t\t\tstate.POLL_USAGE_CURRENT = false;\n\t\t\t\t\t\tmqttMsg.add(currentUsage,\"currentusage\");\n\t\t\t\t\t\tself.getLastPeriodUsage();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.LastPeriodUsage) {\n\t\t\t\t\t\tvar timestamp = new Date();\n\t\t\t\t\t\tvar startdate = parseInt( result.LastPeriodUsage.StartDate );\n\t\t\t\t\t\tstartdate = new Date(dateOffset+startdate*1000);\n\t\t\t\t\t\tvar enddate = parseInt( result.LastPeriodUsage.EndDate );\n\t\t\t\t\t\tenddate = new Date(dateOffset+enddate*1000);\n\t\t\t\t\t\tvar days = Math.round((enddate.getTime() - startdate.getTime())/(1000*60*60*24));\n\t\t\t\t\t\tvar used = parseInt( result.LastPeriodUsage.LastUsage, 16 );\n\t\t\t\t\t\tvar multiplier = parseInt( result.LastPeriodUsage.Multiplier, 16 );\n\t\t\t\t\t\tif (multiplier == 0) { multiplier = 1;}\n\t\t\t\t\t\tvar divisor = parseInt( result.LastPeriodUsage.Divisor, 16 );\n\t\t\t\t\t\tif (divisor == 0) { divisor = 1;}\n\t\t\t\t\t\tused = used * multiplier / divisor;\n\t\t\t\t\t\twinston.info(\"Last Period Usage: \" + timestamp.toLocaleString() + \" : \" + used.toFixed(2) + \" - Days: \" + days +\" - Start Date \" + startdate.toLocaleString() + \" - End Date \" + enddate.toLocaleString());\n\t\t\t\t\t\t// publish summation on MQTT service\n\t\t\t\t\t\tvar lastUsage = { value: used , unit: \"KWh\" , timestamp: timestamp.toISOString() , startdate: startdate.toISOString(), enddate: enddate.toISOString(), days: days };\n\n\t\t\t\t\t\t//self.emit(\"usage-last\", lastUsage);\n\t\t\t\t\t\tstate.POLL_USAGE_LAST = false;\n\t\t\t\t\t\tmqttMsg.add(lastUsage,\"lastusage\");\n\t\t\t\t\t\tfireMqtt();\n\t\t\t\t\t}\n\t\t\t\t\telse if (result.ConnectionStatus) {\n\t\t\t\t\t\twinston.info(\"connection status: \" + result.ConnectionStatus.Status);\n\t\t\t\t\t\tself.emit(\"connection\", result.ConnectionStatus.Status);\n\t\t\t\t\t}\n\t\t\t\t\telse if ( (!result.InstantaneousDemand) && (!result.CurrentSummationDelivered) && (!result.CurrentPeriodUsage) && (!result.LastPeriodUsage)){\n\t\t\t\t\t\t\twinston.info(\"Other Command: \" + Object.keys(result)[0] +\":\" + Object.values(result)[0]);\n\t\t\t\t\t\t\twinston.debug(util.format('%o',result));\t// display data read in\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t} catch (ex){\n\t\t\t\twinston.error(\"Uncaught exception liklely in XML2js parser\\n\" + ex);\n\t\t\t\twinston.debug(\"Details\\n\" + Object.keys(ex)[0] +\":\" + Object.values(ex)[0]);\n\t\t\t}\n\t\t\tparseBuffer = \"\";\t// reset the read buffer\n\t\t}\t\n\t});\n\tsetTimeout(setPortStatus, 15000);\n}", "function readSerialData(data) {\n // if there are webSocket connections, send the serial data\n // to all of them:\n console.log(data);\n if (connections.length > 0) {\n broadcast(data);\n }\n}", "function readSerialData(data) {\n // if there are webSocket connections, send the serial data\n // to all of them:\n console.log(data);\n if (connections.length > 0) {\n broadcast(data);\n }\n}", "function serialEvent() {\n inData = serial.readLine();\n let splitData = split(inData, '|');\n if (splitData.length === 7) {\n b1 = int(trim(splitData[0]));\n b2 = int(trim(splitData[1]));\n slider = int(trim(splitData[2]));\n shaked = int(trim(splitData[3]));\n light = int(trim(splitData[4]));\n sound = int(trim(splitData[5]));\n temp = int(trim(splitData[6]));\n newValue = true;\n } else {\n newValue = false;\n }\n}", "async function eventSerializer(){\n return new Promise(async (resolve, reject) =>{\n port\n .on('open', async () =>{\n process.stdout.write('\\x07\\x07\\x07\\x07');//Synchronized with 4 beep sound\n\n port.on('data', async (data) =>{\n data = data.toString('utf8').replace(/[wkg]/gi, '');\n if(isNaN(data)) return resolve();\n \n data = Number(data);\n if(signalDebug) console.log(`${prev} ${curr} Rate : ${stable} Stable : ${isStable} Sent : ${isSent}`);\n \n curr = data;\n\n if(data == 0){\n zero++\n\n if(STABLE_THRESHOLD < zero) isSent = false, zero = 0;\n }\n else zero = 0;\n\n if(data == 0 || Math.abs(data) <= THRESHOLD){\n return resolve();\n }\n\n if(stable < STABLE_THRESHOLD) isStable = false;\n else isStable = true;\n\n if(curr == prev){\n stable++;\n \n if(isStable && !isSent){\n prev = curr, stable = 0, isStable = false, isSent = true;\n let buf = `${String(curr)}`;\n \n \n process.stdout.write('\\x07');//Beep sound with \"please wait\"\n if(timeDebug) console.time('I/O');//Start KB I/O\n await robot.typeString(buf);\n if(timeDebug) console.timeLog('I/O');\n await robot.keyTap('tab')\n process.stdout.write('\\x07');//Beep sound with \"good to go\"\n if(timeDebug) console.timeLog('I/O');//End KB I/O\n if(timeDebug) console.timeEnd('I/O');\n }\n }\n else prev = curr, curr = 0, stable = 0, isStable = false, isSent = false;\n \n resolve();\n });\n })\n .on('error', async (error) =>{\n console.log(error);\n })\n })\n}", "function listPorts() {\n dataPort = [];\n SerialPort.list().then(\n ports => {\n ports.forEach(port => {\n dataPort.push(port.path + \"\");\n // console.log(\"burak\");\n // console.log(port.path);\n })\n },\n err => {\n console.error('Error listing ports', err)\n }\n )\n }", "function listPorts(err, ports){\n\tports.forEach(function(port){\n\t\tconsole.log(port.comName);\n\t\tconsole.log(port.pnpId);\n\t\tconsole.log(port.manufacturer);\n\t if(port.manufacturer.indexOf(\"Arduino\") > -1){\n\t\t arduinoPort = port.comName;\n\t\t console.log(\"Arduino is: \" + arduinoPort);\n\t\t\tarduino = new sp.SerialPort(arduinoPort, {\n\t\t\t\tbaudrate: 115200,\n\t\t\t\tparser: sp.parsers.readline(\"\\n\")\n\t\t\t});\n\t\t\tarduino.on(\"open\", onOpen);\n\t }\n\t});\n}", "function setMotorsMovementSpeed({comName, speed=600}) {\n if (!openedPorts[comName]) {\n console.warn(comName + ' not available.', speed);\n return;\n }\n\n openedPorts[comName].write(`M99 R${speed}\\n`, err => {\n if (err) {\n return console.error('Error on write: ', err);\n }\n\n console.info('SET SPEED SENT', speed);\n });\n}", "function readRHUSB() {\n port.write(\"PA\\r\\n\");\n}", "handleSerialPortsMessage(message) {\n // Extract the presets data\n var serialPorts = JSON.parse(message['serialPorts']);\n // Pass them ?\n this.top.getPorter().onSerialPortsMessageReceived(serialPorts);\n }", "function onSliderOutToSerialValueChanged() {\n console.log(\"Slider:\", sliderOutToSerial.value());\n\n if (serial.isOpen()) {\n serial.writeLine(sliderOutToSerial.value());\n }\n}", "start() {\n return new Promise((resolve, reject) => {\n this.buildModemInterface().then((serial_port) => {\n this.serial = serial_port;\n resolve();\n }).catch((err) => {\n reject(err);\n });\n })\n }", "onReady() {\n return __awaiter(this, void 0, void 0, function* () {\n // Initialize your adapter here\n // The adapters config (in the instance object everything under the attribute \"native\") is accessible via\n // this.config:\n this.log.info(\"config ComPort: \" + this.config.comPort);\n this.log.info(\"config sensorHeight: \" + this.config.sensorHeight);\n this.log.info(\"config cisternDiameter: \" + this.config.cisternDiameter);\n this.log.info(\"config updateCycle: \" + this.config.updateCycle);\n this.updateCycle = this.config.updateCycle;\n const port = new SerialPort(this.config.comPort, {\n baudRate: 9600,\n dataBits: 8,\n stopBits: 1,\n parity: \"none\",\n }, error => {\n if (error !== null) {\n console.error(error);\n }\n });\n const blp = new SerialPort.parsers.ByteLength({ length: 2 });\n port.pipe(blp);\n blp.on(\"data\", (x) => this.sniff(x));\n /*\n For every state in the system there has to be also an object of type state\n Here a simple template for a boolean variable named \"testVariable\"\n Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables\n */\n yield this.setObjectAsync(\"distance\", {\n type: \"state\",\n common: {\n name: \"distance\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"waterLevel\", {\n type: \"state\",\n common: {\n name: \"waterLevel\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"timestamp\", {\n type: \"state\",\n common: {\n name: \"timestamp\",\n type: \"string\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"volume\", {\n type: \"state\",\n common: {\n name: \"volume\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"diffPerHour\", {\n type: \"state\",\n common: {\n name: \"diffPerHour\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"diffPerDay\", {\n type: \"state\",\n common: {\n name: \"diffPerDay\",\n type: \"number\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n yield this.setObjectAsync(\"status\", {\n type: \"state\",\n common: {\n name: \"status\",\n type: \"string\",\n role: \"value\",\n read: true,\n write: true,\n },\n native: {},\n });\n // in this template all states changes inside the adapters namespace are subscribed\n this.subscribeStates(\"*\");\n // await this.getStateAsync(\"volume\");\n /*\n setState examples\n you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)\n */\n // the variable testVariable is set to true as command (ack=false)\n // await this.setStateAsync(\"distance\", 88);\n // this.setState()\n });\n }", "respondToArduino(command){\n BluetoothSerial.write(command)\n .then((res) => {\n console.log(res, command)\n })\n .catch((err) => console.log(err.message))\n }", "function serialEvent(){\n\n}", "function SerialJS(SerialJS_serialPort__var, SerialJS_lib__var, SerialJS_serialP__var, SerialJS_buffer__var, SerialJS_index__var) {\n\nvar _this;\nthis.setThis = function(__this) {\n_this = __this;\n};\n\nthis.ready = false;\n//Attributes\nthis.SerialJS_serialPort__var = SerialJS_serialPort__var;\nthis.SerialJS_lib__var = SerialJS_lib__var;\nthis.SerialJS_serialP__var = SerialJS_serialP__var;\nthis.SerialJS_buffer__var = SerialJS_buffer__var;\nthis.SerialJS_index__var = SerialJS_index__var;\n//message queue\nconst queue = [];\nthis.getQueue = function() {\nreturn queue;\n};\n\n//callbacks for third-party listeners\nconst receive_bytesOnreadListeners = [];\nthis.getReceive_bytesonreadListeners = function() {\nreturn receive_bytesOnreadListeners;\n};\n//ThingML-defined functions\nfunction receive(SerialJS_receive_byte__var) {\nif(_this.SerialJS_buffer__var[0]\n === 0x13 && SerialJS_receive_byte__var === 0x12 || _this.SerialJS_buffer__var[0]\n === 0x12) {\nif( !((SerialJS_receive_byte__var === 0x13)) || _this.SerialJS_buffer__var[_this.SerialJS_index__var - 1]\n === 0x7D) {\nSerialJS_buffer__var[_this.SerialJS_index__var] = SerialJS_receive_byte__var;\n_this.SerialJS_index__var = _this.SerialJS_index__var + 1;\n\n}\nif(SerialJS_receive_byte__var === 0x13 && !((_this.SerialJS_buffer__var[_this.SerialJS_index__var - 1]\n === 0x7D))) {\nprocess.nextTick(sendReceive_bytesOnRead.bind(_this, _this.SerialJS_buffer__var.slice()));\n_this.SerialJS_index__var = 0;\nvar i__var = 0;\n\nwhile(i__var < 18) {\nSerialJS_buffer__var[i__var] = 0x13;\ni__var = i__var + 1;\n\n}\n\n}\n\n}\n}\n\nthis.receive = function(SerialJS_receive_byte__var) {\nreceive(SerialJS_receive_byte__var);};\n\nfunction initSerial() {\nvar i__var = 0;\n\nwhile(i__var < 18) {\nSerialJS_buffer__var[i__var] = 0x13;\ni__var = i__var + 1;\n\n}\n_this.SerialJS_serialP__var = new _this.SerialJS_lib__var.SerialPort(_this.SerialJS_serialPort__var, {baudrate: 9600, parser: _this.SerialJS_lib__var.parsers.byteLength(1)}, false);;\n_this.SerialJS_serialP__var.open(function (error) {\nif (error){\nconsole.log(\"ERROR: \" + (\"Problem opening the serial port... It might work, though most likely not :-)\"));\nconsole.log(error);\nconsole.log(\"ERROR: \" + (\"Available serial ports:\"));\n_this.SerialJS_lib__var.list(function (err, ports) {\n ports.forEach(function(port) {\n console.log(port.comName); \n });\n });\n}else{\n_this.SerialJS_serialP__var.on('data', function(data) {\nreceive(data[0]);\n});\nconsole.log((\"Serial port opened sucessfully!\"));\n}})\n}\n\nthis.initSerial = function() {\ninitSerial();};\n\nfunction killSerial() {\n_this.SerialJS_serialP__var.close(function (error) {\nif (error){\nconsole.log(\"ERROR: \" + (\"Problem closing the serial port...\"));\nconsole.log(error);\n}else\nconsole.log((\"serial port closed!\"));\n});\n}\n\nthis.killSerial = function() {\nkillSerial();};\n\n//Internal functions\nfunction sendReceive_bytesOnRead(b) {\n//notify listeners\nconst arrayLength = receive_bytesOnreadListeners.length;\nfor (var _i = 0; _i < arrayLength; _i++) {\nreceive_bytesOnreadListeners[_i](b);\n}\n}\n\n//State machine (states and regions)\nthis.build = function() {\nthis.SerialJS_behavior = new StateJS.StateMachine(\"behavior\").entry(function () {\ninitSerial();\nconsole.log((\"Serial port ready!\"));\n})\n\n.exit(function () {\nkillSerial();\nconsole.log((\"Serial port killed, RIP!\"));\n})\n\n;\nthis._initial_SerialJS_behavior = new StateJS.PseudoState(\"_initial\", this.SerialJS_behavior, StateJS.PseudoStateKind.Initial);\nvar SerialJS_behavior_default = new StateJS.State(\"default\", this.SerialJS_behavior);\nthis._initial_SerialJS_behavior.to(SerialJS_behavior_default);\nSerialJS_behavior_default.to(null).when(function (message) { v_b = message[2];return message[0] === \"write\" && message[1] === \"write_bytes\";}).effect(function (message) {\n v_b = message[2];_this.SerialJS_serialP__var.write(v_b, function(err, results) {\n});\n});\n}\n}", "function gotData(data){\n console.log(\"Recieved from the serial port: \" + data);\n sph = data;\n}", "function bleConsole(value){\n const y = document.getElementById('serial')\n /* check if the device is connected if true send file*/\n if(isConnected){\n /* need to read the value of the TX_char\n * may need some kind of loop or trigger to watch if new data comes in????\n * not sure what I want to implement for this yet....\n */\n // y.innerText = TX_characteristic.readValue(); TODO does not work\n }else{\n const x = document.getElementById('console');\n x.style.display =\"none\";\n alert(\"MicroTrynkit device not connected. Please pair it first.\");\n }\n\n}", "function serialWriteTextData(textData) {\n if (serial.isOpen()) {\n // console.log(\"Writing to serial: \", textData);\n serial.writeLine(textData);\n }\n}", "function leerPesoyRacion(){\n port.on('open', function() {\n port.write('main screen turn on', function(err) {\n if (err) {\n return console.log('Error: ', err.message);\n }\n console.log('mensaje 4 escrito');\n });\n setTimeout(function(){\n port.write('>4', function(err) {\n if (err) {\n return console.log('Error: ', err.message);\n }\n console.log('cmd 4');\n });\n }, 2000);\n });\n}", "function mySelectEvent() {\n let item = portSelector.value();\n // give it an extra property for hiding later:\n portSelector.visible = true;\n // if there's a port open, close it:\n if (serial.serialport != null) {\n serial.close();\n }\n // open the new port:\n serial.open(item);\n}", "function serial_cmd(cmd)\n{\n //-- Degbug\n console.log(\"Comand: \" + cmd + \" Length: \" + cmd.length);\n\n //-- Actuar sobre los LEDs\n for (let led of outputbits) {\n\n //-- Leer el bit de la variable binaria,\n //-- si se ha recibido el comando correcto\n let bit = bitvar(cmd, led.varid)\n\n //-- Actuar sobre el LED del panel si se ha recibido el bit\n if (bit) {\n console.log(\"Bit: \" + bit)\n led.set(bit);\n }\n }\n}", "get_serialMode()\n {\n return this.liveFunc._serialMode;\n }", "_closeSerialPort() {\n return new Promise((resolve, reject) => {\n if (this.serialPort !== null) {\n this.serialPort.removeAllListeners();\n\n const deinitSerial = () => {\n this.serialPort = null;\n this.info.serialPortReady = false;\n\n if (this.info.wifiState === 2) {\n this.info.wifiState = 0;\n this.detachUDPPort();\n }\n\n this.emit('state', {\n serialPortReady: this.info.serialPortReady,\n wifiState: this.info.wifiState,\n });\n resolve();\n }\n\n const closeListener = () => {\n console.log('normal close');\n deinitSerial();\n }\n\n const errorListener = (err) => {\n if (err.message === 'Port is not open') {\n console.log('port not open');\n this.serialPort.removeListener('close', closeListener);\n this.serialPort.removeListener('error', errorListener);\n deinitSerial();\n }\n }\n\n this.serialPort.once('close', closeListener);\n this.serialPort.on('error', errorListener); \n this.serialPort.close();\n } else {\n resolve();\n }\n }); \n }", "function onSendInterval() {\n let content = JSON.stringify({A0: analogRead(A0)});\n console.log('Send: ' + content);\n var options = {\n host: SMARTTHINGS_HOST,\n port: SMARTTHINGS_PORT,\n path:'/',\n method:'POST',\n headers: { \"Content-Type\":\"application/json\", \"Content-Length\":content.length }\n };\n http.request(options, (res) => {\n let allData = \"\";\n res.on('data', function(data) { allData += data; });\n res.on('close', function(data) { console.log(\"Closed: \" + allData); }); \n }).end(content);\n}", "send(msg) {\n if (this.connectionId < 0) {\n throw 'Invalid connection';\n }\n chrome.serial.send(this.connectionId, str2ab(msg), function () {\n });\n }", "function onData(data) {\n console.log(\"meteor onData: \" + data);\n // let dataArr = data.split(\",\");\n // console.log(dataArr);\n if (data >= 380) {\n console.log('number of #metoo: ' + count);\n console.log('arduino:' + data);\n //console.log('led');\n writeSerialData(count + '|');\n } else {\n console.log('stop');\n console.log('arduino:' + data);\n}\n}", "function mouseClicked() {\n if (!serial.isOpen()) {\n serial.connectAndOpen(null, serialOptions);\n }\n}", "function WebUSBSerialCommunicator (params) {\n var self = this;\n\n self.debugMode = false;\n if(typeof params !== \"undefined\" &&\n params !== null &&\n typeof params.debug === \"boolean\") {\n self.debugMode = params.debug;\n }\n\n if(typeof params !== \"undefined\" &&\n params !== null &&\n typeof params.device === \"object\") {\n if (params.device.vendorId === FTDI_USB_VENDOR_ID && params.device.productId === FTDI_USB_PRODUCT_ID) {\n this.serial = new WebFTDIUSBSerialPort({\n device: params.device,\n debug: self.debugMode\n });\n } else if (params.device.vendorId === NATIVE_USB_VENDOR_ID && params.device.productId === NATIVE_USB_PRODUCT_ID) {\n this.serial = new WebNativeUSBSerialPort({\n device: params.device,\n debug: self.debugMode\n });\n } else {\n throw new Error(\"Device's vendor ID and product ID do not match a TappyUSB\");\n }\n } else if (typeof params !== \"undefined\" &&\n params !== null &&\n typeof params.serial === \"object\"){\n // this is just for testing and should not be used\n this.serial = params.serial;\n } else {\n throw new Error(\"Must specify a TappyUSB device\");\n }\n\n this.isConnecting = false;\n this.hasAttached = false;\n this.disconnectImmediately = false;\n this.disconnectCb = function() {};\n\n this.dataReceivedCallback = function(bytes) {\n\n };\n this.errorCallback = function(data) {\n\n };\n this.readCallback = function(buff) {\n self.dataReceivedCallback(new Uint8Array(buff));\n };\n }", "async function findUSBDevice(event) {\n // STEP 1A: Auto-Select first port\n if (event.type == 'AutoConnect' || event.type == 'Reconnect') {\n // ports = await getPorts()\n //STEP 1A: GetPorts - Automatic at initialization\n // -Enumerate all attached devices\n // -Check for permission based on vendorID & productID\n devices = await navigator.usb.getDevices();\n ports = devices.map((device) => new serial.Port(device)); //return port\n\n if (ports.length == 0) {\n port.statustext_connect =\n 'NO USB DEVICE automatically found on page load';\n console.log(port.statustext_connect);\n } else {\n var statustext = '';\n if (event.type == 'AutoConnect') {\n statustext = 'AUTO-CONNECTED USB DEVICE ON PAGE LOAD!';\n } else if (event.type == 'Reconnect') {\n statustext = 'RECONNECTED USB DEVICE!';\n }\n port = ports[0];\n try {\n await port.connect();\n } catch (error) {\n console.log(error);\n }\n port.statustext_connect = statustext;\n console.log(port.statustext_connect);\n\n //Hide manual connect button upon successful connect\n document.querySelector('button[id=connectusb]').style.display = 'none';\n }\n }\n\n // STEP 1B: User connects to Port\n if (\n event.type == 'pointerup' ||\n event.type == 'touchend' ||\n event.type == 'mouseup'\n ) {\n event.preventDefault(); //prevents additional downstream call of click listener\n try {\n //STEP 1B: RequestPorts - User based\n // -Get device list based on Arduino filter\n // -Look for user activation to select device\n const filters = [\n { vendorId: 0x2341, productId: 0x8036 },\n { vendorId: 0x2341, productId: 0x8037 },\n { vendorId: 0x2341, productId: 0x804d },\n { vendorId: 0x2341, productId: 0x804e },\n { vendorId: 0x2341, productId: 0x804f },\n { vendorId: 0x2341, productId: 0x8050 },\n ];\n\n device = await navigator.usb.requestDevice({ filters: filters });\n port = new serial.Port(device); //return port\n\n await port.connect();\n\n port.statustext_connect = 'USB DEVICE CONNECTED BY USER ACTION!';\n console.log(port.statustext_connect);\n\n //Hide manual connect button upon successful connect\n document.querySelector('button[id=connectusb]').style.display = 'none';\n } catch (error) {\n console.log(error);\n }\n waitforClick.next(1);\n }\n} //FUNCTION findUSBDevice", "connect(path) {\n //TODO: accept connexionOptions\n chrome.serial.connect(path, this.onConnectComplete.bind(this))\n }", "userInput(input){\n this.upySerial.serial.write(input)\n }", "function serialEvent(){\n//receive serial data here\n var data = serial.readLine();\n console.log(data);\n let vis = data.split(\" , \");\n if (vis.length > 1) {\n \tcircleWidth = Number(vis[0]);\n \tcircleHeight = Number(vis[1]);\n \tbackground(circleWidth*2, circleHeight, circleWidth);\n }\n\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i]);\n }\n}", "function printList(portList) {\n // portList is an array of serial port names\n for (var i = 0; i < portList.length; i++) {\n // Display the list the console:\n console.log(i + \" \" + portList[i]);\n }\n}", "async function blxConnectionFast(){\n for(let i=0;i<3;i++){\n //console.log(\"Set FAST:\" + con_fast_speed)\n await sleepMs(500) \n await blxDeviceCmd('C' + con_fast_speed, 32000) // Anscheinend Timeout ca. 30 sec\n //console.log(\"FAST OK:\" + con_act_speed)\n if(blxErrMsg) return\n if(con_act_speed > 50){\n const sptxt = 'BLE Low Speed: ' + con_fast_speed + \"->\" + con_act_speed\n terminalPrint('WARNING: ' + sptxt )\n if(blxUserCB) blxUserCB('WARN',2,sptxt) // Warning 2\n }else return\n let ns\n ns = parseInt(con_fast_speed)\n if(isNaN(ns)) break\n con_fast_speed = (++ns).toString()\n }\n }", "function ZNPSerial() {\n}" ]
[ "0.83013713", "0.827232", "0.825203", "0.825203", "0.80018634", "0.7850609", "0.76897776", "0.7666061", "0.75112784", "0.74730825", "0.72880846", "0.7275577", "0.71368736", "0.70893687", "0.7045895", "0.699966", "0.69972616", "0.6989601", "0.693551", "0.6915174", "0.6894452", "0.68174356", "0.67808545", "0.6766506", "0.6736642", "0.66611624", "0.66611624", "0.66522336", "0.66240484", "0.649975", "0.64850354", "0.6453505", "0.6419023", "0.6402242", "0.63817257", "0.63631105", "0.6349851", "0.6344722", "0.63351035", "0.6318712", "0.62969685", "0.628075", "0.6280186", "0.6265156", "0.62319064", "0.6152282", "0.6030065", "0.59613925", "0.59491956", "0.59392625", "0.5903058", "0.5896616", "0.58855474", "0.58731097", "0.5852961", "0.58155835", "0.5806971", "0.5805811", "0.5792105", "0.5765738", "0.57632643", "0.57529247", "0.57155436", "0.56914634", "0.56739384", "0.56739384", "0.5665588", "0.5665147", "0.55918986", "0.55867344", "0.5571159", "0.5567029", "0.55669314", "0.5527247", "0.55180854", "0.5508394", "0.550439", "0.5501958", "0.5495232", "0.5488995", "0.54816145", "0.5476691", "0.5476594", "0.543142", "0.5431161", "0.54167545", "0.5403761", "0.5402031", "0.5393935", "0.538969", "0.53749603", "0.5363901", "0.53509355", "0.5341335", "0.5331813", "0.5312376", "0.5311343", "0.5311343", "0.5304132", "0.5288024" ]
0.6674045
25
turns a 2D path into an indexed 3D mesh
function meshify(path) { var mesh2d = stroke.build(path) mesh2d.positions = mesh2d.positions.map(function(p) { return [p[0], p[1], p[2]||0] }) return mesh2d }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "path(x, y, path) {\n\t\t//let vertices = Matter.Vertices.fromPath(path);\n\t\tlet vertices = this.matter.vertices.fromPath(path);\n\t\tvar poly = this.add.polygon(x, y, path, COLOR.OUTER);\n\n\t\treturn this.matter.add.gameObject(poly, {\n\t\t\tisStatic: true,\n\t\t\tshape: {\n\t\t\t\ttype: 'fromVerts',\n\t\t\t\tverts: path,\n\t\t\t\tflagInternal: false\n\t\t\t},\n\t\t\trender: {\n\t\t\t\tfillColor: COLOR.OUTER,\n\t\t\t\tlineColor: COLOR.OUTER,\n\t\t\t\tfillOpacity: 1,\n\t\t\t\twireframes: false,\n\n\t\t\t\t// add stroke and line width to fill in slight gaps between fragments\n\t\t\t\tstrokeStyle: COLOR.OUTER,\n\t\t\t\tlineWidth: 3\n\t\t\t}\n\t\t},\n\t\t);\n\t\t//return Matter.Bodies.fromVertices(x, y, vertices, {\n\t\t// return this.matter.add.fromVertices(x, y, vertices, {\n\t\t// \tisStatic: true,\n\t\t// \trender: {\n\t\t// \t\tfillColor: COLOR.OUTER,\n\t\t// \t\tlineColor: COLOR.OUTER,\n\t\t// \t\tfillOpacity: 1,\n\t\t// \t\twireframes: false,\n\n\t\t// \t\t// add stroke and line width to fill in slight gaps between fragments\n\t\t// \t\tstrokeStyle: COLOR.OUTER,\n\t\t// \t\tlineWidth: 3\n\t\t// \t}\n\t\t// });\n\t}", "function Path3D(path,firstNormal,raw){this.path=path;this._curve=new Array();this._distances=new Array();this._tangents=new Array();this._normals=new Array();this._binormals=new Array();for(var p=0;p<path.length;p++){this._curve[p]=path[p].clone();// hard copy\n}this._raw=raw||false;this._compute(firstNormal);}", "mesh(volume, dims)\n {\n //Precalculate direction vectors for convenience\n var dir = new Array(3)\n for (var i = 0; i < 3; ++i) {\n dir[i] = [[0, 0, 0], [0, 0, 0]]\n dir[i][0][(i + 1) % 3] = 1\n dir[i][1][(i + 2) % 3] = 1\n }\n //March over the volume\n var vertices = []\n , faces = []\n , x = [0, 0, 0]\n , B = [[false, true] //Incrementally update bounds (this is a bit ugly)\n , [false, true]\n , [false, true]]\n , n = -dims[0] * dims[1]\n for (B[2] = [false, true], x[2] = -1; x[2] < dims[2]; B[2] = [true, (++x[2] < dims[2] - 1)])\n for (n -= dims[0], B[1] = [false, true], x[1] = -1; x[1] < dims[1]; B[1] = [true, (++x[1] < dims[1] - 1)])\n for (n -= 1, B[0] = [false, true], x[0] = -1; x[0] < dims[0]; B[0] = [true, (++x[0] < dims[0] - 1)], ++n) {\n //Read current voxel and 3 neighboring voxels using bounds check results\n var p = (B[0][0] && B[1][0] && B[2][0]) ? volume[n] : 0\n , b = [(B[0][1] && B[1][0] && B[2][0]) ? volume[n + 1] : 0\n , (B[0][0] && B[1][1] && B[2][0]) ? volume[n + dims[0]] : 0\n , (B[0][0] && B[1][0] && B[2][1]) ? volume[n + dims[0] * dims[1]] : 0\n ]\n //Generate faces\n for (var d = 0; d < 3; ++d)\n if ((!!p) !== (!!b[d])) {\n var s = !p ? 1 : 0\n var t = [x[0], x[1], x[2]]\n , u = dir[d][s]\n , v = dir[d][s ^ 1]\n ++t[d]\n\n var vertex_count = vertices.length\n vertices.push([t[0], t[1], t[2]])\n vertices.push([t[0] + u[0], t[1] + u[1], t[2] + u[2]])\n vertices.push([t[0] + u[0] + v[0], t[1] + u[1] + v[1], t[2] + u[2] + v[2]])\n vertices.push([t[0] + v[0], t[1] + v[1], t[2] + v[2]])\n faces.push([vertex_count, vertex_count + 1, vertex_count + 2, vertex_count + 3, s ? b[d] : p])\n }\n }\n return {vertices: vertices, faces: faces}\n }", "function array_2d_to_3d() {\n // Reset 3d line array\n array_line_3d = [];\n var x, y, z;\n var direction = true; // used to invert the order of points on a layer\n // this is useful for a path that changes directions every layer\n var point_index = 0;\n // Loop for the total amount of layers\n for (var layer_index = 0; layer_index < parameters.num_of_layers; layer_index++) {\n array_line_3d[layer_index] = []; // Adding layer info\n // Loop over the line #number of nodes\n // Every layer needs to reverse de points order to have a path that returns through that inverts direction\n // Avoiding jumps\n // line is printed inverting direction every layer. Used for prints without jumps\n var start, loop_cond, inc; \n if(direction) { \n start = 0; \n inc = 1; \n loop_cond = function(){return point_index < globals.array_line_2d.length}; \n } else { \n start = globals.array_line_2d.length - 1; \n inc = -1; \n loop_cond = function(){return point_index >= 0}; \n }\n // console.log(\"LOGIC: start = \" + start + \", direction = \" + direction + \", inc = \" + inc);\n for (point_index=start; loop_cond(); point_index += inc) {\n // Scale model to delta_x parameter and round to 3 decimals\n x = Math.round(1000 * globals.array_line_2d[point_index][0] * parameters.width_x/100)/1000;\n y = Math.round(1000 * globals.array_line_2d[point_index][1] * parameters.width_x/100)/1000;\n z = parameters.first_height + layer_index * parameters.layer_height;\n z = Math.round(1000 * z) / 1000;\n // Scale model based on top layer scale %\n x = x * scale_layer(layer_index);\n y = y * scale_layer(layer_index);\n // Rotate layers based on rotation parameters deg/layers\n var rotated_coordinates = rotate_point(x, y, layer_index);\n x = rotated_coordinates[0];\n y = rotated_coordinates[1];\n array_line_3d[layer_index].push([x, y, z]); // Adding coordinates info\n }\n if(globals.open_line) {\n direction = !direction;// Reverse direction\n }\n }\n // Convert path to conitnuous path in Z axis too\n // If line is not a closed path, do not calculate continuous path\n // due to to reach same point on a layer, 2 layers need to be walked (1 forward, 1 backwards)\n // this increases the height distance between this points = 2*layer_height\n // Possible solution is for none-closed-lines double the amount of layers, and reduce the layer_height to half \n if (parameters.continuous_path && !globals.open_line) {\n continuous_path_calculation();\n }\n add_extrusion_values();\n // console.log(array_line_3d);\n draw_shape_into_3dviewer();\n // Center array after drawing to avoid messing drawing location\n center_array_line_3d();\n}", "function meshFromSlicePile(slicePile, isoLevel, sliceDim, sideLength, verticalLength){\r\n let geoRecons = new THREE.Geometry();\r\n let marchedTriangles;\r\n let verticeIndex = 0;\r\n let localCube = new Object();\r\n let vertDiv = slicePile.length\r\n localCube.p = [];\r\n localCube.val = [];\r\n for(let ind=0; ind<8; ind++){//Init localCube object\r\n localCube.p[ind] = new THREE.Vector3(0, 0, 0);\r\n localCube.val[ind] = 0;\r\n }\r\n let i, j, k;\r\n for(i=0; i<sliceDim-1; i++){\r\n for(j=0; j<sliceDim-1; j++){\r\n for(k=0; k<vertDiv-1; k++){\r\n//TODO: Used bitwise operation on cube edge index\r\n //localCube.p[ind].x = (sideLength / sliceDim) * (i + (ind AND 1) XOR (ind AND 2))\r\n localCube.p[0].x = (sideLength / sliceDim) * i\r\n localCube.p[1].x = (sideLength / sliceDim) * (i+1)\r\n localCube.p[2].x = (sideLength / sliceDim) * (i+1)\r\n localCube.p[3].x = (sideLength / sliceDim) * i\r\n localCube.p[4].x = (sideLength / sliceDim) * i\r\n localCube.p[5].x = (sideLength / sliceDim) * (i+1)\r\n localCube.p[6].x = (sideLength / sliceDim) * (i+1)\r\n localCube.p[7].x = (sideLength / sliceDim) * i\r\n //localCube.p[ind].z = (sideLength / sliceDim) * (i + (ind AND 2))\r\n localCube.p[0].z = (sideLength / sliceDim) * j\r\n localCube.p[1].z = (sideLength / sliceDim) * j\r\n localCube.p[2].z = (sideLength / sliceDim) * (j+1)\r\n localCube.p[3].z = (sideLength / sliceDim) * (j+1)\r\n localCube.p[4].z = (sideLength / sliceDim) * j\r\n localCube.p[5].z = (sideLength / sliceDim) * j\r\n localCube.p[6].z = (sideLength / sliceDim) * (j+1)\r\n localCube.p[7].z = (sideLength / sliceDim) * (j+1)\r\n //localCube.p[ind].y = (sideLength / sliceDim) * (i + (ind AND 4))\r\n localCube.p[0].y = (verticalLength / vertDiv) * k\r\n localCube.p[1].y = (verticalLength / vertDiv) * k\r\n localCube.p[2].y = (verticalLength / vertDiv) * k\r\n localCube.p[3].y = (verticalLength / vertDiv) * k\r\n localCube.p[4].y = (verticalLength / vertDiv) * (k+1)\r\n localCube.p[5].y = (verticalLength / vertDiv) * (k+1)\r\n localCube.p[6].y = (verticalLength / vertDiv) * (k+1)\r\n localCube.p[7].y = (verticalLength / vertDiv) * (k+1)\r\n\r\n \r\n //localCube.val[ind] = slicePile[k+(ind AND 4)][i+(ind AND 1)XOR(ind AND 2)][j+(ind AND 2)]\r\n localCube.val[0] = slicePile[k][i][j]\r\n localCube.val[1] = slicePile[k][i+1][j]\r\n localCube.val[2] = slicePile[k][i+1][j+1]\r\n localCube.val[3] = slicePile[k][i][j+1]\r\n localCube.val[4] = slicePile[k+1][i][j]\r\n localCube.val[5] = slicePile[k+1][i+1][j]\r\n localCube.val[6] = slicePile[k+1][i+1][j+1]\r\n localCube.val[7] = slicePile[k+1][i][j+1]\r\n\r\n marchedTriangles = cubeTriangles(localCube, isoLevel)\r\n for(let n=0; n<marchedTriangles.numTriangles; n++){\r\n geoRecons.vertices.push(marchedTriangles[n][0].clone());\r\n geoRecons.vertices.push(marchedTriangles[n][1].clone());\r\n geoRecons.vertices.push(marchedTriangles[n][2].clone());\r\n geoRecons.faces.push(new THREE.Face3(verticeIndex, verticeIndex + 1, verticeIndex + 2));\r\n verticeIndex += 3;\r\n }\r\n }\r\n }\r\n }\r\n const redColor = new THREE.Color(\"rgb(200, 220, 20)\");\r\n let reconsMaterial = new THREE.MeshPhongMaterial({color: redColor, side:THREE.DoubleSide});\r\n reconsMaterial.specular.copy(redColor);\r\n geoRecons.computeFaceNormals()\r\n let meshRecons = new THREE.Mesh(geoRecons, reconsMaterial);\r\n return meshRecons\r\n}", "function mapSidePath(i) {\n // Added support for 0 value in columns, where height is 0\n // but the shape is rendered.\n // Height is used from 1st to 6th element of pArr\n if (h === 0 && i > 1 && i < 6) { // [2, 3, 4, 5]\n return {\n x: pArr[i].x,\n // when height is 0 instead of cuboid we render plane\n // so it is needed to add fake 10 height to imitate cuboid\n // for side calculation\n y: pArr[i].y + 10,\n z: pArr[i].z\n };\n }\n // It is needed to calculate dummy sides (front/back) for breaking\n // points in case of x and depth values. If column has side,\n // it means that x values of front and back side are different.\n if (pArr[0].x === pArr[7].x && i >= 4) { // [4, 5, 6, 7]\n return {\n x: pArr[i].x + 10,\n // when height is 0 instead of cuboid we render plane\n // so it is needed to add fake 10 height to imitate cuboid\n // for side calculation\n y: pArr[i].y,\n z: pArr[i].z\n };\n }\n // Added dummy depth\n if (d === 0 && i < 2 || i > 5) { // [0, 1, 6, 7]\n return {\n x: pArr[i].x,\n // when height is 0 instead of cuboid we render plane\n // so it is needed to add fake 10 height to imitate cuboid\n // for side calculation\n y: pArr[i].y,\n z: pArr[i].z + 10\n };\n }\n return pArr[i];\n }", "function CulledMesh(volume, dims) {\n //Precalculate direction vectors for convenience\n var dir = new Array(3);\n for(var i=0; i<3; ++i) {\n dir[i] = [[0,0,0], [0,0,0]];\n dir[i][0][(i+1)%3] = 1;\n dir[i][1][(i+2)%3] = 1;\n }\n //March over the volume\n var vertices = []\n , faces = []\n , x = [0,0,0]\n , B = [[false,true] //Incrementally update bounds (this is a bit ugly)\n ,[false,true]\n ,[false,true]]\n , n = -dims[0]*dims[1];\n for( B[2]=[false,true],x[2]=-1; x[2]<dims[2]; B[2]=[true,(++x[2]<dims[2]-1)])\n for(n-=dims[0],B[1]=[false,true],x[1]=-1; x[1]<dims[1]; B[1]=[true,(++x[1]<dims[1]-1)])\n for(n-=1, B[0]=[false,true],x[0]=-1; x[0]<dims[0]; B[0]=[true,(++x[0]<dims[0]-1)], ++n) {\n //Read current voxel and 3 neighboring voxels using bounds check results\n var p = (B[0][0] && B[1][0] && B[2][0]) ? volume[n] : 0\n , b = [ (B[0][1] && B[1][0] && B[2][0]) ? volume[n+1] : 0\n , (B[0][0] && B[1][1] && B[2][0]) ? volume[n+dims[0]] : 0\n , (B[0][0] && B[1][0] && B[2][1]) ? volume[n+dims[0]*dims[1]] : 0\n ];\n //Generate faces\n for(var d=0; d<3; ++d)\n if((!!p) !== (!!b[d])) {\n var s = !p ? 1 : 0;\n var t = [x[0],x[1],x[2]]\n , u = dir[d][s]\n , v = dir[d][s^1];\n ++t[d];\n \n var vertex_count = vertices.length;\n vertices.push([t[0], t[1], t[2] ]);\n vertices.push([t[0]+u[0], t[1]+u[1], t[2]+u[2] ]);\n vertices.push([t[0]+u[0]+v[0], t[1]+u[1]+v[1], t[2]+u[2]+v[2]]);\n vertices.push([t[0] +v[0], t[1] +v[1], t[2] +v[2]]);\n faces.push([vertex_count, vertex_count+1, vertex_count+2, vertex_count+3, s ? b[d] : p]);\n }\n }\n return { vertices:vertices, faces:faces };\n}", "function Surface3d(a1,b1,c1,a2,b2,c2,a3,b3,c3,a4,b4,c4){\r\n\r\n var edge1 = new Line([[a1,b1,c1],[a2,b2,c2]])\r\n var edge2 = new Line([[a2,b2,c2],[a3,b3,c3]])\r\n var edge3 = new Line([[a3,b3,c3],[a4,b4,c4]])\r\n var edge4 = new Line([[a4,b4,c4],[a1,b1,c1]])\r\n var square = [\r\n edge1.gObject(red,5),\r\n edge2.gObject(red,5),\r\n edge3.gObject(red,5),\r\n edge4.gObject(red,5),\r\n {\r\n type: \"mesh3d\",\r\n x: [a1,a2,a3,a4],\r\n y: [b1,b2,b3,b4],\r\n z: [c1,c2,c3,c4],\r\n i : [0, 0],\r\n j : [2, 3],\r\n k : [1, 2],\r\n opacity: 0.8,\r\n colorscale: [['0', impBlue], ['1', impBlue]],\r\n intensity: [0.8,0.8],\r\n showscale: false\r\n }\r\n ]\r\n return square;\r\n}", "function Path3D(path, firstNormal, raw) {\n if (firstNormal === void 0) { firstNormal = null; }\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n for (var p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._compute(firstNormal);\n }", "function Path3D(path, firstNormal, raw) {\n this.path = path;\n this._curve = new Array();\n this._distances = new Array();\n this._tangents = new Array();\n this._normals = new Array();\n this._binormals = new Array();\n for (var p = 0; p < path.length; p++) {\n this._curve[p] = path[p].clone(); // hard copy\n }\n this._raw = raw || false;\n this._compute(firstNormal);\n }", "function path(x, y, path) {\n console.log(x, y, path);\n const vertices = Matter.Vertices.fromPath(path);\n return Matter.Bodies.fromVertices(x, y, vertices, {\n isStatic: true,\n render: {\n fillStyle: COLOR.OUTER,\n\n // add stroke and line width to fill in slight gaps between fragments\n strokeStyle: COLOR.OUTER,\n lineWidth: 1\n }\n });\n }", "_buildTriangles() {\n // geometry.faces.push( new THREE.Face3( 0, 1, 2 ) );\n\n // temporary vertice for buiding triangles\n var aIndex = undefined;\n var bIndex = undefined;\n var cIndex = undefined;\n var dIndex = undefined;\n\n // part 2: building the triangles from the vertice\n for (var iy = 0; iy < this.height - 1; iy++) {\n\n for (var ix = 0; ix < this.width - 1; ix++) {\n\n // (0, 0)\n if (ix == 0 && iy == 0) {\n aIndex = 0;\n bIndex = 1;\n cIndex = 2;\n dIndex = 3;\n\n // (1, 0)\n } else if (ix == 1 && iy == 0) {\n aIndex = ix;\n bIndex = (ix * 2) + 2;\n cIndex = (ix * 2) + 3;\n dIndex = ((ix - 1) * 2) + 2;\n\n // (0, 1)\n } else if (ix == 0 && iy == 1) {\n aIndex = 3;\n bIndex = 2;\n cIndex = this.firstRowSum + 1;\n dIndex = this.firstRowSum + 2;\n\n // (1, 1)\n } else if (ix == 1 && iy == 1) {\n aIndex = 2;\n bIndex = 5;\n cIndex = this.firstRowSum + 3;\n dIndex = this.firstRowSum + 1;\n\n // 1st row (except 1st col)\n } else if (iy == 0) {\n aIndex = ix * 2;\n bIndex = (ix * 2) + 2;\n cIndex = (ix * 2) + 3;\n dIndex = ((ix - 1) * 2) + 3;\n\n // 2nd row (except 1st and 2nd col)\n } else if (iy == 1) {\n aIndex = (ix * 2) + 1;\n bIndex = (ix * 2) + 3;\n cIndex = this.firstRowSum + 2 + ix;\n dIndex = this.firstRowSum + 1 + ix;\n\n // 1st col (except 1st and 2nd row)\n } else if (ix == 0) {\n aIndex = this.firstRowSum + (iy - 2) * this.width + 2;\n bIndex = this.firstRowSum + (iy - 2) * this.width + 1;\n cIndex = this.firstRowSum + (iy - 1) * this.width + 1;\n dIndex = this.firstRowSum + (iy - 1) * this.width + 2;\n\n // 2nd col (except 1st and 2nd row)\n } else if (ix == 1) {\n aIndex = this.firstRowSum + (iy - 2) * this.width + 1;\n bIndex = this.firstRowSum + (iy - 2) * this.width + 3;\n cIndex = this.firstRowSum + (iy - 1) * this.width + 3;\n dIndex = this.firstRowSum + (iy - 1) * this.width + 1;\n\n // # all other cases\n } else {\n aIndex = this.firstRowSum + this.width * (iy - 2) + ix + 1;\n bIndex = this.firstRowSum + this.width * (iy - 2) + ix + 2;\n cIndex = this.firstRowSum + this.width * (iy - 1) + ix + 2;\n dIndex = this.firstRowSum + this.width * (iy - 1) + ix + 1;\n }\n\n var face1 = new THREE.Face3(aIndex, bIndex, cIndex);\n var face2 = new THREE.Face3(aIndex, cIndex, dIndex);\n\n // getting a relevant color depending on altitude\n var altitude = Math.floor((this.geometry.vertices[aIndex].y) * this._groundResolution + this.min);\n var altiColor = this.altitudeColorPicker2(altitude);\n\n if (typeof altiColor === \"undefined\") {\n console.log(altitude);\n } else {\n face1.color.setRGB(altiColor.r, altiColor.g, altiColor.b);\n face2.color.setRGB(altiColor.r, altiColor.g, altiColor.b);\n }\n\n // Add triangle T1, vertices a, b, c\n this.geometry.faces.push(face1);\n\n // Add triangle T2, vertices a, c, d\n this.geometry.faces.push(face2);\n\n }\n\n }\n }", "getGeometryData (geomData) {\n let result = {};\n\n let meshData = geomData.mesh[0];\n let meshSource = meshData.source;\n let vertices = meshData.vertices[0];\n\n if (!meshData.triangles) {\n throw new Error('Only triangles mesh supported');\n }\n\n let triangles = meshData.triangles[0];\n let stride = triangles.input.length;\n\n if (meshData.vertices.length > 1) {\n throw new Error('Multiple mesh.vertices not supported');\n }\n\n let sources = {};\n\n function appendInputSource (input, defaultOffset = 0) {\n for (let i = 0; i < input.length; i++) {\n let inputData = input[i].$;\n let semantic = inputData.semantic;\n\n let offset = inputData.offset;\n if (offset === undefined) {\n offset = defaultOffset;\n }\n\n if (semantic === 'VERTEX') {\n appendInputSource(vertices.input, offset);\n continue;\n };\n\n let source = inputData.source.slice(1); // skip leading #\n if (inputData.set !== undefined) {\n semantic += inputData.set;\n }\n\n sources[semantic] = {\n source: source,\n offset: parseInt(offset)\n };\n }\n }\n\n appendInputSource(triangles.input);\n\n for (let semantic in sources) {\n let source = sources[semantic];\n let arrayID = source.source;\n let offset = source.offset;\n\n result[semantic] = {\n data: this.getGeometryArray(arrayID, meshSource),\n offset: offset\n }\n }\n\n let indices = triangles.p[0].split(\" \");\n for (let i = 0; i < indices.length; i++) {\n indices[i] = parseInt(indices[i]);\n }\n\n result.indices = indices;\n result.stride = stride;\n result.triangleCount = parseInt(triangles.$.count);\n result.renderMode = MODE_TRIANGLES;\n\n return result;\n }", "function insert_per_vertex_tangents_to_parsed_OBJ( mesh )\n {\n /// 1 Initialize each vertex tangent and bitangent to zero.\n /// 2 Iterate over each face and calculate the xyz-to-uv mapping for its edge vectors.\n /// 3 Use the mapping to recover xyz vectors for the u and v directions.\n /// 4 Contribute the face's tangent and bitangent to each of its vertices's tangents and bitangents.\n /// 5 Normalize each vertex tangent and bitangent.\n /// 6 Create faceVertexIndices.tangents and .bitangents.\n \n // Your code goes here.\n\t\tvar vertex_tangents = [];\n\t\tvar vertex_bitangents = [];\n\t\tvar UV = mat3.create();\n\t\tvar UV_inverse = mat3.create();\n\t\tvar dv_matrix = mat3.create();\n\t\tvar result = mat3.create();\n\t\tvar tangent = [];\n\t\tvar bitangent = [];\n for( var i = 0; i < mesh.vertex.positions.length; ++i )\n {\n vertex_tangents.push( [ 0., 0., 0. ] );\n\t\t\tvertex_bitangents.push( [ 0., 0., 0. ] );\n }\n\t\n for( var i = 0; i < mesh.faceVertexIndices.positions.length; ++i )\n {\n var fvi = mesh.faceVertexIndices.positions[i];\n\t\t\tvar fti = mesh.faceVertexIndices.texCoords[i];\n\t\t\t//console.log(\"fvi\" +fvi);\n // 2,3\n\t\t\t//change in positions\n var dPos1 = sub( mesh.vertex.positions[ fvi[1] ], mesh.vertex.positions[ fvi[0] ] );\n var dPos2 = sub( mesh.vertex.positions[ fvi[2] ], mesh.vertex.positions[ fvi[0] ] );\n\t\t\t//change in tex\n var dUV1 = sub( mesh.vertex.texCoords[ fti[1] ], mesh.vertex.texCoords[ fti[0] ] );\n var dUV2 = sub( mesh.vertex.texCoords[ fti[2] ], mesh.vertex.texCoords[ fti[0] ] );\n\t\t\t\n\t\t\t//make a 3*3\n\t\t\tUV[0] = dUV1[0];\n\t\t\tUV[1] = dUV1[1];\n\t\t\tUV[2] = 0.;\n\t\t\t\n\t\t\tUV[3] = dUV2[0];\n\t\t\tUV[4] = dUV2[1];\n\t\t\tUV[5] = 0.;\n\t\t\t\n\t\t\tUV[6] = 0.;\n\t\t\tUV[7] = 0.;\n\t\t\tUV[8] = 1.;\n\t\t\t\n\t\t\t//inverseof 3*3\n\t\t\tmat3.invert(UV_inverse, UV);\n\t\t\t\n\t\t\t//dpos 3*3\n\t\t\tdv_matrix[0] = dPos1[0]; dv_matrix[1] = dPos1[1]; dv_matrix[2] = dPos1[2];\n\t\t\tdv_matrix[3] = dPos2[0]; dv_matrix[4] = dPos2[1]; dv_matrix[5] = dPos2[2];\n\t\t\tdv_matrix[6] = 0.; dv_matrix[7] = 0.; dv_matrix[8] = 1.;\n\t\t\t\n\t\t\tmat3.multiply(result, dv_matrix, UV_inverse);\n\t\t\t\n\t\t\ttangent[0] = result[0]; tangent[1] = result[3]; tangent[2] = result[6];\n\t\t\tbitangent[0] = result[1]; bitangent[1] = result[4]; bitangent[2] = result[7];\n\t\t\t\n\t\t\tnormalized(tangent); normalized(bitangent);\n \n\t\t\t// 4\n for( var vi = 0; vi < fvi.length; ++vi )\n {\n vertex_tangents[ fvi[ vi ] ] = add( vertex_tangents[ fvi[ vi ] ], tangent );\n\t\t\t\tvertex_bitangents[ fvi[ vi ] ] = add( vertex_bitangents[ fvi[ vi ] ], bitangent );\n }\n }\n // 5\n for( var i = 0; i < vertex_tangents.length; ++i )\n {\n vertex_tangents[i] = normalized( vertex_tangents[i] );\n\t\t\t//console.log(\"vertex tangents\" + vertex_tangents[i]);\n }\n\t\tfor( var i = 0; i < vertex_bitangents.length; ++i )\n {\n vertex_bitangents[i] = normalized( vertex_bitangents[i] );\n\t\t\t//console.log(\"vertex bitangents\" + vertex_bitangents[i]);\n\t\t}\n // 6\n mesh.vertex.tangents = vertex_tangents;\n\t\tmesh.vertex.bitangents = vertex_bitangents;\n mesh.faceVertexIndices.tangents = mesh.faceVertexIndices.positions.map( function( face ) { return face.slice(0); } );\n\t\tmesh.faceVertexIndices.bitangents = mesh.faceVertexIndices.positions.map( function( face ) { return face.slice(0); } );\n\n\t}", "function createVertexData2() {\r\n\tvar n = 64;\r\n\tvar m = 18;\r\n\tvar a = 0.5;\r\n\tvar b = 0.3;\r\n\tvar c = 0.1;\r\n\tvar d = 6;\r\n\tvar du = 2 * Math.PI / n;\r\n\tvar dv = 2 * Math.PI / m;\r\n\r\n\t// Counter for entries in index array.\r\n\tlet iLines = 0;\r\n\tlet iTris = 0;\r\n\r\n\t// Positions.\r\n\tvertices2 = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\t// Index data.\r\n\tindicesLines2 = new Uint16Array(2 * 2 * n * m);\r\n\tindicesTris2 = new Uint16Array(3 * 2 * n * m);\r\n\r\n\t// Colors.\r\n\tcolors2 = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\tfor (let i = 0, u = -1; i <= n; i++, u += du) {\r\n\t\tfor (let j = 0, v = -1; j <= m; j++, v += dv) {\r\n\t\t\tconst iVertex = i * (m + 1) + j;\r\n \r\n\t\t\tvar x = (a + b * Math.cos(d * u) + c * Math.cos(v)) * Math.cos(u);\r\n\t\t\tvar z = a * c * Math.sin(v);\r\n\t\t\tvar y = (a + b * Math.cos(d * u) + c * Math.cos(v)) * Math.sin(u);\r\n \r\n\t\t\tvertices2[iVertex * 3] = x;\r\n\t\t\tvertices2[iVertex * 3 + 1] = y;\r\n\t\t\tvertices2[iVertex * 3 + 2] = z;\r\n\t\t\t\r\n\t\t\tif (j && i) {\r\n\t\t\t\tindicesLines2[iLines++] = iVertex - 1;\r\n\t\t\t\tindicesLines2[iLines++] = iVertex;\r\n\t\t\t\tindicesLines2[iLines++] = iVertex - (m + 1);\r\n\t\t\t\tindicesLines2[iLines++] = iVertex;\r\n\t\t\t\t\r\n\t\t\t\tindicesTris2[iTris++] = iVertex;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1);\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1) - 1;\r\n\t\t\t\tindicesTris2[iTris++] = iVertex - (m + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "dedupePathParts(path) {\n let startPathIdxs = [];\n let curPathIdx = -1;\n let startPartPos = 0;\n let intersections = [];\n let pathParts = [];\n for (let i = 1; i < path.length; i++) {\n let lastKey = path[i - 1].x + \"__\" + path[i - 1].y;\n let key = path[i].x + \"__\" + path[i].y;\n if (this.pathsMatrix[lastKey] && this.pathsMatrix[key] && !this.pathsMatrix[key][curPathIdx]) {\n let commonIdxs = _.intersection(_.keys(this.pathsMatrix[lastKey]), _.keys(this.pathsMatrix[key]));\n if (commonIdxs.length > 0) {\n if (curPathIdx === -1 && i !== 1) {\n pathParts.push({\n path: path.slice(startPartPos, i),\n startPathIdxs: startPathIdxs,\n endPathIdxs: getPathIdxs(this.pathsMatrix, lastKey),\n intersections: intersections\n });\n }\n curPathIdx = commonIdxs[0];\n }\n else {\n startPathIdxs = getPathIdxs(this.pathsMatrix, lastKey);\n startPartPos = i - 1;\n intersections = [];\n curPathIdx = -1;\n }\n }\n else if (this.pathsMatrix[lastKey] && !this.pathsMatrix[key]) {\n if (curPathIdx === -1) {\n intersections.push(..._.map(_.keys(this.pathsMatrix[lastKey]), (idx) => {\n return {\n idx: idx,\n from: i - startPartPos,\n pos: this.pathsMatrix[lastKey][idx]\n };\n }));\n }\n else {\n startPathIdxs = getPathIdxs(this.pathsMatrix, lastKey);\n startPartPos = i - 1;\n intersections = [];\n }\n curPathIdx = -1;\n }\n }\n if (curPathIdx === -1) {\n pathParts.push({\n path: path.slice(startPartPos),\n startPathIdxs: startPathIdxs,\n endPathIdxs: [],\n intersections: intersections\n });\n }\n // console.log(\"---\");\n // pathParts.forEach((pathPart) => {\n // console.log(pathPart);\n // });\n return pathParts;\n }", "_createMesh() {\n var element = this._element;\n var w = element.calculatedWidth;\n var h = element.calculatedHeight;\n\n var r = this._rect;\n\n // Note that when creating a typed array, it's initialized to zeros.\n // Allocate memory for 4 vertices, 8 floats per vertex, 4 bytes per float.\n var vertexData = new ArrayBuffer(4 * 8 * 4);\n var vertexDataF32 = new Float32Array(vertexData);\n\n // Vertex layout is: PX, PY, PZ, NX, NY, NZ, U, V\n // Since the memory is zeroed, we will only set non-zero elements\n\n // POS: 0, 0, 0\n vertexDataF32[5] = 1; // NZ\n vertexDataF32[6] = r.x; // U\n vertexDataF32[7] = r.y; // V\n\n // POS: w, 0, 0\n vertexDataF32[8] = w; // PX\n vertexDataF32[13] = 1; // NZ\n vertexDataF32[14] = r.x + r.z; // U\n vertexDataF32[15] = r.y; // V\n\n // POS: w, h, 0\n vertexDataF32[16] = w; // PX\n vertexDataF32[17] = h; // PY\n vertexDataF32[21] = 1; // NZ\n vertexDataF32[22] = r.x + r.z; // U\n vertexDataF32[23] = r.y + r.w; // V\n\n // POS: 0, h, 0\n vertexDataF32[25] = h; // PY\n vertexDataF32[29] = 1; // NZ\n vertexDataF32[30] = r.x; // U\n vertexDataF32[31] = r.y + r.w; // V\n\n var vertexDesc = [\n { semantic: SEMANTIC_POSITION, components: 3, type: TYPE_FLOAT32 },\n { semantic: SEMANTIC_NORMAL, components: 3, type: TYPE_FLOAT32 },\n { semantic: SEMANTIC_TEXCOORD0, components: 2, type: TYPE_FLOAT32 }\n ];\n\n var device = this._system.app.graphicsDevice;\n var vertexFormat = new VertexFormat(device, vertexDesc);\n var vertexBuffer = new VertexBuffer(device, vertexFormat, 4, BUFFER_STATIC, vertexData);\n\n var mesh = new Mesh(device);\n mesh.vertexBuffer = vertexBuffer;\n mesh.primitive[0].type = PRIMITIVE_TRIFAN;\n mesh.primitive[0].base = 0;\n mesh.primitive[0].count = 4;\n mesh.primitive[0].indexed = false;\n mesh.aabb.setMinMax(Vec3.ZERO, new Vec3(w, h, 0));\n\n this._updateMesh(mesh);\n\n return mesh;\n }", "function PathControls() {\n\t\treturn {\n\t\t\tsimple: function(vertices) {\n\t\t\t\tvar division = \"EnsemblBacteria\";\n\n\t\t\t\t// (totalParticles - 1) because (fore = [i+1])\n\t\t\t\tvar totalParticles = vertices.length;\n\t\t\t\tvar pathControls = [];\n\t\t\t\tfor (var i = 0 ; i < totalParticles - 1 ; i++) {\n\t\t\t\t\tvar baseParticle = vertices[i];\n\t\t\t\t\tvar foreParticle = vertices[i + 1];\n\t\t\t\t\tvar midCoord = new THREE.Vector3(0,0,0);\n\t\t\t\t\tmidCoord.addVectors(baseParticle,foreParticle).divideScalar(2);\n\t\t\t\t\tvar midOffset = new THREE.Vector3(0,0,0);\n\t\t\t\t\tmidOffset.copy(midCoord).sub(baseParticle);\n\t\t\t\t\tif (i === 0 && division != \"EnsemblBacteria\") { // insert backprojected first coord\n\t\t\t\t\t\tvar preCoord;\n\t\t\t\t\t\t// if (division == \"EnsemblBacteria\") {\n\t\t\t\t\t\t// \tpreCoord = vertices[totalParticles - 1];\n\t\t\t\t\t\t// } else {\n\t\t\t\t\t\t\tpreCoord = new THREE.Vector3(0,0,0);\n\t\t\t\t\t\t// }\n\t\t\t\t\t\tpreCoord.copy(baseParticle).sub(midOffset);\n\t\t\t\t\t\tpathControls.push(preCoord);\n\t\t\t\t\t}\n\t\t\t\t\t//pathControls.push(baseParticle);\n\t\t\t\t\tpathControls.push(midCoord);\n\t\t\t\t\t// if (i == totalParticles - 2) {\n\t\t\t\t\t// //\tpathControls.push(foreParticle);\n\t\t\t\t\t// \tvar chromEnd = new THREE.Vector3(0,0,0);\n\t\t\t\t\t// \tchromEnd.copy(foreParticle).add(midOffset);\n\t\t\t\t\t// \tpathControls.push(chromEnd);\n\t\t\t\t\t// };\n\t\t\t\t\tif (i == totalParticles - 2 && division != \"EnsemblBacteria\") {\n\t\t\t\t\t//\tpathControls.push(foreParticle);\n\t\t\t\t\t\tvar chromEnd;\n\t\t\t\t\t\t// if (division == \"EnsemblBacteria\") {\n\t\t\t\t\t\t// \tchromEnd = vertices[0];\n\t\t\t\t\t\t// } else {\n\t\t\t\t\t\t\tchromEnd = new THREE.Vector3(0,0,0);\n\t\t\t\t\t\t// }\n\t\t\t\t\t\tchromEnd.copy(foreParticle).add(midOffset);\n\t\t\t\t\t\tpathControls.push(chromEnd);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn pathControls;\n\t\t\t},\n\t\t\tcubic: function(vertices, closed) {\n\t\t\t\tclosed = closed || false; // closed if circular chromosome eg. Bacteria\n\t\t\t\tvar controlLength = 1; // variable for possible corner tweaking\n\n\t\t\t\t// (totalParticles - 1) because (fore = [i+1])\n\t\t\t\tvar totalParticles = vertices.length;\n\t\t\t\tvar pathControls = {};\n\t\t\t\tpathControls.vertices = [];\n\t\t\t\tpathControls.colors = [];\n\t\t\t\tvar previousOffset = new THREE.Vector3(0,0,0);\n\n\t\t\t\t// if (closed) {\n\t\t\t\t// \tvar firstParticle = vertices[0];\n\t\t\t\t// \tvar nthParticle = vertices[totalParticles - 1];\n\t\t\t\t// \tvar closedControl = new THREE.Vector3(0,0,0);\n\t\t\t\t// \tif (closed) closedControl.addVectors(nthParticle, firstParticle).divideScalar(2);\n\t\t\t\t// }\n\n\t\t\t\tfor (var i = 0 ; i < totalParticles ; i++) {\n\n\t\t\t\t\tvar baseParticle = vertices[i];\n\t\t\t\t\tvar foreParticle = new THREE.Vector3(0,0,0);\n\t\t\t\t\tif (i == totalParticles - 1) {\n\t\t\t\t\t\tif (closed) {\n\t\t\t\t\t\t\t// fore particle == first particle\n\t\t\t\t\t\t\tforeParticle = vertices[0];\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// fore particle == extend same dist as to previous particle\n\t\t\t\t\t\t\t// really ???\n\t\t\t\t\t\t\t//foreParticle.copy(baseParticle).addVectors(baseParticle, vertices[i - 1]);\n\t\t\t\t\t\t\tforeParticle.copy(baseParticle).add(new THREE.Vector3(0.5, 0.5, 0.5));\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tforeParticle = vertices[i + 1];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tvar midControl = new THREE.Vector3(0,0,0);\n\t\t\t\t\t// if (i == totalParticles - 1) {\n\t\t\t\t\t// \tif (closed) {\n\t\t\t\t\t// \t\t// use first particle mid point as closed chromatin...\n\t\t\t\t\t// \t\tmidControl.copy(closedControl);\n\t\t\t\t\t// \t} else {\n\t\t\t\t\t// \t\t// use previous particle mid point as no more foreward...\n\t\t\t\t\t// \t\tmidControl.addVectors(baseParticle, vertices[i - 1]).divideScalar(2);\n\t\t\t\t\t// \t}\n\t\t\t\t\t// } else {\n\t\t\t\t\t\tmidControl.addVectors(baseParticle, foreParticle).divideScalar(2);\n\t\t\t\t\t// }\n\t\t\t\t\t\n\t\t\t\t\tvar midOffset = new THREE.Vector3(0,0,0);\n\t\t\t\t\tmidOffset.copy(midControl).sub(baseParticle);\n\n\t\t\t\t\tif (i === 0) {\n\t\t\t\t\t\tif (closed) {\n\t\t\t\t\t\t\t// set previous for first particle\n\t\t\t\t\t\t\tvar previousControl = new THREE.Vector3(0,0,0);\n\t\t\t\t\t\t\tpreviousControl.addVectors(vertices[totalParticles - 1], vertices[0]).divideScalar(2);\n\t\t\t\t\t\t\tpreviousOffset.copy(previousControl).sub(vertices[totalParticles - 1]);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tpreviousOffset.copy(midOffset);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tvar backControl = new THREE.Vector3(0,0,0);\n\t\t\t\t\tbackControl.copy(baseParticle).sub(midOffset);\n\n\t\t\t\t\tvar foreControl = new THREE.Vector3(0,0,0);\n\t\t\t\t\tforeControl.copy(baseParticle).add(previousOffset);\n\n\t\t\t\t\t// Node tangent\n\t\t\t\t\tvar baseTangent = new THREE.Vector3(0,0,0);\n\t\t\t\t\tbaseTangent.subVectors(foreControl, backControl).divideScalar(controlLength);\n\t\t\t\t\tbackControl.copy(baseParticle).sub(baseTangent);\n\t\t\t\t\tforeControl.copy(baseParticle).add(baseTangent);\n\n\t\t\t\t\t// Add controls to array\n\t\t\t\t\tpathControls.vertices.push(backControl);\n\t\t\t\t\t\tpathControls.colors.push(new THREE.Color(0xcccccc));\n\t\t\t\t\tpathControls.vertices.push(baseParticle);\n\t\t\t\t\t\tpathControls.colors.push(new THREE.Color(0x000000));\n\t\t\t\t\tpathControls.vertices.push(foreControl);\n\t\t\t\t\t\tpathControls.colors.push(new THREE.Color(0xcccccc));\n\n\t\t\t\t\tpreviousOffset = midOffset;\n\t\t\t\t}\n\t\t\t\t// add start and end controls\n\t\t\t\t// requires calc of join midway on cubicBezier between start and end\n\t\t\t\tvar startBackControl = new THREE.Vector3(0,0,0);\n\t\t\t\tvar startPoint = new THREE.Vector3(0,0,0);\n\t\t\t\tvar endForeControl = new THREE.Vector3(0,0,0);\n\t\t\t\tvar endPoint = new THREE.Vector3(0,0,0);\n\n\t\t\t\tvar totalControls = pathControls.vertices.length;\n\t\t\t\tvar p1 = pathControls.vertices[totalControls-2]; // last particle\n\t\t\t\tvar p2 = pathControls.vertices[totalControls-1]; // last fore control\n\t\t\t\tvar p3 = pathControls.vertices[0]; // first back control\n\t\t\t\tvar p4 = pathControls.vertices[1]; // first particle\n\t\t\t\tif (closed) {\n\t\t\t\t\t// curve between start and end Controls\n\t\t\t\t\tvar joinCurve = new THREE.CubicBezierCurve3(p1,p2,p3,p4);\n\t\t\t\t\t// split join curve in two\n\t\t\t\t\tvar joinMidpoint = joinCurve.getPointAt(0.5);\n\t\t\t\t\tvar joinTangent = joinCurve.getTangent(0.5).multiplyScalar(1);\n\n\t\t\t\t\t// NEEDS ROUNDING OFF TO NEAREST 0.5??? Math.round(num*2)/2;\n\t\t\t\t\tstartBackControl.copy(joinMidpoint).sub(joinTangent);\n\t\t\t\t\tstartPoint.copy(joinMidpoint);\n\t\t\t\t\tendForeControl.copy(joinMidpoint).add(joinTangent);\n\t\t\t\t\tendPoint.copy(joinMidpoint);\n\t\t\t\t} else {\n\t\t\t\t\tstartBackControl.copy(p3);\n\t\t\t\t\tstartPoint.copy(p3);\n\t\t\t\t\tendForeControl.copy(p2);\n\t\t\t\t\tendPoint.copy(p2);\n\t\t\t\t}\n\t\t\t\tpathControls.vertices.unshift(startBackControl);\n\t\t\t\t\tpathControls.colors.unshift(new THREE.Color(0xffff00));\n\t\t\t\tpathControls.vertices.unshift(startPoint);\n\t\t\t\t\tpathControls.colors.unshift(new THREE.Color(0xff0000));\n\t\t\t\tpathControls.vertices.push(endForeControl);\n\t\t\t\t\tpathControls.colors.push(new THREE.Color(0x00ffff));\n\t\t\t\tpathControls.vertices.push(endPoint);\n\t\t\t\t\tpathControls.colors.push(new THREE.Color(0x0000ff));\n\n\t\t\t\treturn pathControls;\n\t\t\t}\n\t\t};\n\t}", "function FieldPath (name, yPoints, zPoints) {\n this.name = name;\n this.xPoints = []; // anterior-posterior\n this.yPoints = yPoints; // superior-inferior\n this.zPoints = zPoints; //lateral-medial\n\n this.side = \"right\";\n // Need to assert yPoints.length = zPoints.length\n this.numPoints = yPoints.length\n this.switchSide = switchSide;\n this.renderPath = renderPath;\n this.material = new THREE.LineBasicMaterial({\n linewidth: 3,\n linecap: \"round\",\n linejoin: \"round\",\n });\n this.changeToDash = changeToDash;\n\n // Initialise xPoints with integers from 0 to numLength\n for (var i=0; i<this.numPoints; i++) {\n this.xPoints.push(2*i);\n }\n\n function switchSide() {\n this.zPoints = this.zPoints.map(n => n * (-1));\n switch(this.side) {\n case \"right\":\n this.side = \"left\";\n break;\n case \"left\":\n this.side = \"right\";\n break;\n }\n }\n\n function renderPath(parent, color, zOffset) {\n // zOffset to show all lines without superimposition\n this.material.color.set(color)\n var zPointsOffset = this.zPoints.map(n => n + zOffset);\n var geometry = new THREE.Geometry();\n for (var i=0; i<this.numPoints; i++) {\n var xc = this.xPoints[i];\n var yc = this.yPoints[i];\n var zc = zPointsOffset[i];\n geometry.vertices.push(new THREE.Vector3(xc, yc, zc));\n }\n geometry.computeLineDistances();\n var line = new THREE.Line(geometry, this.material);\n parent.add(line);\n }\n\n function changeToDash() {\n this.material = new THREE.LineDashedMaterial({\n linewidth: 2,\n linecap: \"round\",\n linejoin: \"round\",\n dashSize: 0.2,\n gapSize: 0.05,\n })\n }\n\n}", "function IndexGeometry( geometry ){\n\tvar faces = geometry.faces;\n\tthis.geometry = geometry;\n\tthis.vertices = {};\n\tthis.triNode = null;\n\n\tvar keys = 'abc'.split('');\n\tfor( var i=0, l=faces.length; i<l; i+=1 ){\n\t\tvar face = faces[i];\n\t\tfor( var j=0, jl=keys.length; j<jl; j+=1 ){\n\t\t\tif( this.vertices.hasOwnProperty( face[keys[j]] ) ){\n\t\t\t\tthis.vertices[''+face[keys[j]]].push( face );\n\t\t\t}else{\n\t\t\t\tthis.vertices[''+face[keys[j]]] = [ face ];\n\t\t\t}\n\t\t}\n\t}\n}", "function zToL(path){\n var ret = [];\n var startPoint = ['L',0,0];\n\n for(var i=0, len=path.length; i<len; i++){\n var pt = path[i];\n switch(pt[0]){\n case 'M':\n startPoint = ['L', pt[1], pt[2]];\n ret.push(pt);\n break;\n case 'Z':\n ret.push(startPoint);\n break;\n default: \n ret.push(pt);\n }\n }\n return ret;\n}", "function c(e){var a,l,c,u=i.length/3,h=e.extractPoints(t),d=h.shape,p=h.holes;// check direction of vertices\nif(!1===Xr.isClockWise(d))// also check if holes are in the opposite direction\nfor(d=d.reverse(),a=0,l=p.length;a<l;a++)c=p[a],!0===Xr.isClockWise(c)&&(p[a]=c.reverse());var f=Xr.triangulateShape(d,p);// join vertices of inner and outer paths to a single array\nfor(a=0,l=p.length;a<l;a++)c=p[a],d=d.concat(c);// vertices, normals, uvs\nfor(a=0,l=d.length;a<l;a++){var m=d[a];i.push(m.x,m.y,0),r.push(0,0,1),o.push(m.x,m.y)}// incides\nfor(a=0,l=f.length;a<l;a++){var g=f[a],v=g[0]+u,y=g[1]+u,x=g[2]+u;n.push(v,y,x),s+=3}}", "function createVertexData() {\r\n\tvar n = 32;\r\n\tvar m = 16;\r\n\tvar R = 0.5;\r\n\tvar r = 0.1;\r\n\tvar a = 1;\r\n\tvar du = 2 * Math.PI / n;\r\n\tvar dv = 2 * Math.PI / m;\r\n\r\n\t// Counter for entries in index array.\r\n\tlet iLines = 0;\r\n\tlet iTris = 0;\r\n\r\n\t// Positions.\r\n\tvertices = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\t// Index data.\r\n\tindicesLines = new Uint16Array(2 * 2 * n * m);\r\n\tindicesTris = new Uint16Array(3 * 2 * n * m);\r\n\r\n\t// Colors.\r\n\tcolors = new Float32Array(3 * (n + 1) * (m + 1));\r\n\r\n\tfor (let i = 0, u = -1; i <= n; i++, u += du) {\r\n\t\tfor (let j = 0, v = -1; j <= m; j++, v += dv) {\r\n\t\t\tconst iVertex = i * (m + 1) + j;\r\n\t\t\t\r\n\t\t\tvar x = (R + r * Math.cos(v) * (a + Math.sin(u))) * Math.cos(u);\r\n\t\t\tvar y = (R + r * Math.cos(v) * (a + Math.sin(u))) * Math.sin(u);\r\n\t\t\tvar z = r * Math.sin(v) * (a + Math.sin(u));\r\n\r\n\t\t\tvertices[iVertex * 3] = x;\r\n\t\t\tvertices[iVertex * 3 + 1] = y;\r\n\t\t\tvertices[iVertex * 3 + 2] = z;\r\n\t\t\t\r\n\t\t\tif (j && i) {\r\n\t\t\t\tindicesLines[iLines++] = iVertex - 1;\r\n\t\t\t\tindicesLines[iLines++] = iVertex;\r\n\t\t\t\tindicesLines[iLines++] = iVertex - (m + 1);\r\n\t\t\t\tindicesLines[iLines++] = iVertex;\r\n\t\t\t\t\r\n\t\t\t\tindicesTris[iTris++] = iVertex;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1);\r\n\t\t\t\tindicesTris[iTris++] = iVertex - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1) - 1;\r\n\t\t\t\tindicesTris[iTris++] = iVertex - (m + 1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}", "function zToL(path) {\n var ret = [];\n var startPoint = ['L', 0, 0];\n\n for (var i = 0, len = path.length; i < len; i++) {\n var pt = path[i];\n switch (pt[0]) {\n case 'M':\n startPoint = ['L', pt[1], pt[2]];\n ret.push(pt);\n break;\n case 'Z':\n ret.push(startPoint);\n break;\n default:\n ret.push(pt);\n }\n }\n return ret;\n}", "function l$1(r){if(!r)return null;if(\"mesh\"===r.type)return r.toJSON();let f=null;const l=r.spatialReference,h=S(l);if(!h)return r.toJSON();const d=l.isWebMercator?102100:4326,I=r$5[d].maxX,g=r$5[d].minX,b=r$5[d].plus180Line,v=r$5[d].minus180Line;let J;const N=r.toJSON();if(l$2(N))J=y$1(N,I,g);else if(s$4(N))N.points=N.points.map((n=>y$1(n,I,g))),J=N;else if(u$1(N))J=p$1(N,h);else if(y$2(N)||f$2(N)){const n=M;c$1(n,N);const m={xmin:n[0],ymin:n[1],xmax:n[2],ymax:n[3]},s=i$3(m.xmin,g)*(2*I),e=0===s?N:u(N,s);m.xmin+=s,m.xmax+=s,y$3(m,b)&&m.xmax!==I||y$3(m,v)&&m.xmin!==g?f=e:J=e;}else J=r.toJSON();if(null!==f){return (new j$1).cut(f,I)}return J}", "function mesh1D(array, level) {\n var zc = zeroCrossings(array, level)\n var n = zc.length\n var npos = new Array(n)\n var ncel = new Array(n)\n for(var i=0; i<n; ++i) {\n npos[i] = [ zc[i] ]\n ncel[i] = [ i ]\n }\n return {\n positions: npos,\n cells: ncel\n }\n}", "function getFlatIndexFrom3D(shape) {\n var strides = util.computeStrides(shape).map(function (d) { return d.toString(); });\n return \"\\n int getFlatIndex(ivec3 coords) {\\n return coords.x * \" + strides[0] + \" + coords.y * \" + strides[1] + \" + coords.z;\\n }\\n\";\n}", "to3D() {\r\n if (this.dimension === 3) {\r\n return;\r\n }\r\n console.assert(this.dimension === 2);\r\n let cpoints = this.cpoints.toArray();\r\n for (let i = 0; i < cpoints.length; i++) {\r\n cpoints[i].push(0);\r\n }\r\n this.cpoints = common_1.arr(cpoints);\r\n }", "to3D() {\r\n if (this.dimension === 3) {\r\n return;\r\n }\r\n console.assert(this.dimension === 2);\r\n let cpoints = this.cpoints.toArray();\r\n for (let i = 0; i < cpoints.length; i++) {\r\n cpoints[i].push(0);\r\n }\r\n this.cpoints = common_1.arr(cpoints);\r\n }", "function path(d) {\n var r = dimensions.map(function(p) {return [position(p), y[p](d[p])]});\n/* r.push({(r[13][0]), 0});\n r.push({(r[0][0]), 0});*/\n if(d[\"District\"] != \"Median\"){\n var ra = [[r[13][0], h], [r[0][0], h]];\n r.push(ra[0]);\n r.push(ra[1]);\n }\n //console.log(r);\n return line(r);\n// return line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; }));\n}", "function __splitPath(path) {\n \n var count = 0;\n var result = [], tmp = [];\n for ( var i = 0; i < path.length; i++) {\n //log(i+\") \"+path[i]);\n if (i && path[i][0] === 'M') {\n var tmpClone = tmp.slice(0);\n result.push(tmpClone);\n tmp = [];\n }\n tmp.push(path[i]); \n }\n var tmpClone = tmp.slice(0);\n result.push(tmpClone);\n \n //log(\"found \"+result.length+\" paths\");\n //for ( var i = 0; i < result.length; i++) \n // log(result[i]);\n return result;\n}", "vPath(num, x, y){\n for(let p = 0; p < num; p++){\n path = paths.create(TILE_WIDTH * x, TILE_HEIGHT * y + (TILE_HEIGHT * p), 'path');\n path.body.immovable = true;\n }\n }", "create_path_from_adjacent(v, s) { \r\n if (v.segments.length < 2) {\r\n console.log(\"Invalid input to create_path_from_adjacent\");\r\n return;\r\n }\r\n \r\n var v1 = s.other_vert(v), v2 = v.other_segment(s).other_vert(v);\r\n var av1 = this.get_vdata(v1.eid, false), av2 = this.get_vdata(v2.eid, false);\r\n \r\n if (av1 === undefined && av2 === undefined) {\r\n console.log(\"no animation data to interpolate\");\r\n return;\r\n } else if (av1 === undefined) {\r\n av1 = av2;\r\n } else if (av2 === undefined) {\r\n av2 = av1;\r\n } \r\n \r\n var av3 = this.get_vdata(v.eid, true);\r\n \r\n var keyframes = new set();\r\n for (var v of av1.verts) {\r\n keyframes.add(get_vtime(v));\r\n }\r\n \r\n for (var v of av2.verts) {\r\n keyframes.add(get_vtime(v));\r\n }\r\n \r\n var co = new Vector2();\r\n \r\n //ensure step func interpolation mode is off for this\r\n var oflag1 = av1.animflag, oflag2 = av2.animflag;\r\n \r\n av1.animflag &= VDAnimFlags.STEP_FUNC;\r\n av2.animflag &= VDAnimFlags.STEP_FUNC;\r\n \r\n for (var time of keyframes) {\r\n var co1 = av1.evaluate(time), co2 = av2.evaluate(time);\r\n \r\n co.load(co1).add(co2).mulScalar(0.5);\r\n av3.update(co, time);\r\n }\r\n \r\n av3.animflag = oflag1 | oflag2;\r\n \r\n av1.animflag = oflag1;\r\n av2.animflag = oflag2;\r\n }", "constructor({ eta = 0.1, phi = 0.1, deta = 0.025, dphi = 0.025, rmin = 20, rmax = 50 }) {\n super();\n this.parameters = { eta, phi, deta, dphi, rmin, rmax };\n this.type = 'GeoTrd3Buffer';\n \n // helper arrays\n let vertices = [], // 3 entries per vector\n \tindices = []; // 1 entry per index, 3 entries form face3\n\n\t\tlet theta1 = ( Math.atan( Math.exp( ( -( eta - deta ) ) ) ) * 2 ),\n\t\t\ttheta2 = ( Math.atan( Math.exp( ( -( eta + deta ) ) ) ) * 2 ),\n\t\t\tphi1 = phi - dphi,\n\t\t\tphi2 = phi + dphi;\n\n\t\t// four vertices, upper half\n\t\tvertices.push(\trmax * Math.cos( phi2 ), rmax * Math.sin( phi2 ), rmax / Math.tan( theta1 ),\n\t\t\t\t\t\trmax * Math.cos( phi1 ), rmax * Math.sin( phi1 ), rmax / Math.tan( theta1 ),\n\t\t\t\t\t\trmax * Math.cos( phi1 ), rmax * Math.sin( phi1 ), rmax / Math.tan( theta2 ),\n\t\t\t\t\t\trmax * Math.cos( phi2 ), rmax * Math.sin( phi2 ), rmax / Math.tan( theta2 ) );\n\n\t\t// four vertices, lower half\n\t\tvertices.push(\trmin * Math.cos( phi2 ), rmin * Math.sin( phi2 ), rmin / Math.tan( theta1 ),\n\t\t\t\t\t\trmin * Math.cos( phi1 ), rmin * Math.sin( phi1 ), rmin / Math.tan( theta1 ),\n\t\t\t\t\t\trmin * Math.cos( phi1 ), rmin * Math.sin( phi1 ), rmin / Math.tan( theta2 ),\n\t\t\t\t\t\trmin * Math.cos( phi2 ), rmin * Math.sin( phi2 ), rmin / Math.tan( theta2 ) );\n\n\t\tlet i0, i1, i2, i3;\n\n\t\t// six planes of the trapezoid\n\t\ti0 = 3; i1 = 2; i2 = 1; i3 = 0;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 4; i1 = 5; i2 = 6; i3 = 7;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 4; i1 = 7; i2 = 3; i3 = 0;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 1; i1 = 2; i2 = 6; i3 = 5;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 5; i1 = 4; i2 = 0; i3 = 1;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\t\ti0 = 2; i1 = 3; i2 = 7; i3 = 6;\n\t\tindices.push( i3, i0, i1, i3, i1, i2 );\n\n // convert data into buffers\n this.setIndex( indices );\n this.addAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );\n this.computeVertexNormals();\n }", "function createTwoCubes() {\n // create a cube using coordinates\n var mesh = new Mesh3D();\n mesh.quad([0, 0, 0], [0, 10, 0], [10, 10, 0], [10, 0, 0]);\n mesh.quad([0, 0, 0], [10, 0, 0], [10, 0, 10], [0, 0, 10]);\n mesh.quad([10, 0, 0], [10, 10, 0], [10, 10, 10], [10, 0, 10]);\n mesh.quad([0, 0, 0], [0, 0, 10], [0, 10, 10], [0, 10, 0]);\n mesh.quad([0, 10, 0], [0, 10, 10], [10, 10, 10], [10, 10, 0]);\n mesh.quad([0, 0, 10], [10, 0, 10], [10, 10, 10], [0, 10, 10]);\n // another cube\n mesh.quad([20, 20, 20], [20, 30, 20], [30, 30, 20], [30, 20, 20]);\n mesh.quad([20, 20, 20], [30, 20, 20], [30, 20, 30], [20, 20, 30]);\n mesh.quad([30, 20, 20], [30, 30, 20], [30, 30, 30], [30, 20, 30]);\n mesh.quad([20, 20, 20], [20, 20, 30], [20, 30, 30], [20, 30, 20]);\n mesh.quad([20, 30, 20], [20, 30, 30], [30, 30, 30], [30, 30, 20]);\n mesh.quad([20, 20, 30], [30, 20, 30], [30, 30, 30], [20, 30, 30]);\n // return both of the cubes in one mesh\n return mesh;\n}", "function loadOBJ(data) {\n var lines = data.split(\"\\n\");\n // 1-based indexing\n var vs = [new vector_1[\"default\"](0, 0, 0)];\n var triangles = [];\n var _loop_1 = function (line) {\n var parts = line.split(\" \");\n var keyword = parts[0];\n var args = parts.slice(1);\n switch (keyword) {\n case \"v\": {\n var f = args.map(function (a) { return parseFloat(a); });\n var v = new vector_1[\"default\"](f[0], f[1], f[2]);\n vs.push(v);\n break;\n }\n case \"f\": {\n var fvs_1 = [];\n args.forEach(function (arg, i) {\n var vertex = (arg + \"//\").split(\"/\");\n fvs_1[i] = parseIndex(vertex[0], vs.length);\n });\n for (var i = 1; i < fvs_1.length - 1; i++) {\n var i1 = 0;\n var i2 = i;\n var i3 = i + 1;\n var t = new triangle_1[\"default\"](vs[fvs_1[i1]], vs[fvs_1[i2]], vs[fvs_1[i3]]);\n triangles.push(t);\n }\n }\n }\n };\n for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {\n var line = lines_1[_i];\n _loop_1(line);\n }\n return new mesh_1[\"default\"](triangles);\n}", "function calcVertices(){\r\n //create first row of face normals set to 0\r\n normRow = [];\r\n for(var k=0; k<=shape.length; k++){\r\n normRow.push(new coord(0,0,0));\r\n }\r\n normFaces.push(normRow);\r\n\r\n for (var i=0; i<shape[0].length-1; i++) {\r\n normRow = [];\r\n for (j=0; j<shape.length-1; j++) {\r\n \r\n var index = (vert.length/3);\r\n var currentLine = shape[j];\r\n var nextLine = shape[j+1];\r\n var thirdLine = shape[j+2];\r\n\r\n //push four points to make polygon\r\n vert.push(currentLine[i].x, currentLine[i].y, currentLine[i].z);\r\n vert.push(currentLine[i + 1].x, currentLine[i + 1].y, currentLine[i + 1].z);\r\n vert.push(nextLine[i + 1].x, nextLine[i + 1].y, nextLine[i + 1].z);\r\n vert.push(nextLine[i].x, nextLine[i].y, nextLine[i].z); \r\n \r\n //1st triangle in poly\r\n ind.push(index, index + 1, index + 2); //0,1,2\r\n //2nd triangle in poly\r\n ind.push(index, index + 2, index + 3); //0,2,3\r\n \r\n //CALCULATE SURFACE NORMALS\r\n \r\n var Snorm = calcNormal(nextLine[i], currentLine[i], currentLine[i+1]);\r\n \r\n if (j===0 || j===shape.length-2){\r\n //pushes first and last faces twice for first vertex\r\n normRow.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n }\r\n normRow.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n \r\n Snorm.normalize();\r\n \r\n surfaceNormz.push(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]);\r\n flatNormz.push(new coord(Snorm.elements[0], Snorm.elements[1], Snorm.elements[2]));\r\n \r\n //push start point for drawing\r\n drawFnormz.push(currentLine[i].x);\r\n drawFnormz.push(currentLine[i].y);\r\n drawFnormz.push(currentLine[i].z);\r\n //push normal vector\r\n drawFnormz.push(currentLine[i].x + Snorm.elements[0]*100);\r\n drawFnormz.push(currentLine[i].y + Snorm.elements[1]*100);\r\n drawFnormz.push(currentLine[i].z + Snorm.elements[2]*100); \r\n \r\n //CALCULATE FLAT COLORS\r\n \r\n var lightDir = new Vector3([1, 1, 1]);\r\n lightDir.normalize();\r\n \r\n //cos(theta) = dot product of lightDir and normal vector\r\n var FdotP = (lightDir.elements[0]*Snorm.elements[0])+(lightDir.elements[1]*Snorm.elements[1])+ (lightDir.elements[2]*Snorm.elements[2]);\r\n //surface color = light color x base color x FdotP (DIFFUSE)\r\n var R = 1.0 * 0.0 * FdotP;\r\n var G = 1.0 * 1.0 * FdotP;\r\n var B = 1.0 * 0.0 * FdotP;\r\n\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n flatColor.push(R, G, B);\r\n }\r\n normFaces.push(normRow); //pushes new row \r\n }\r\n //create last row of face normals set to 0\r\n normRow = [];\r\n for(var c=0; c<=shape.length; c++){\r\n normRow.push(new coord(0,0,0));\r\n }\r\n normFaces.push(normRow);\r\n \r\n //push surface normal colors - red\r\n for (j=0; j<drawFnormz.length; j+=3){\r\n normColor.push(1.0);\r\n normColor.push(0.0);\r\n normColor.push(0.0);\r\n }\r\n}", "function mesh1D(array, level) {\n\t var zc = zeroCrossings(array, level)\n\t var n = zc.length\n\t var npos = new Array(n)\n\t var ncel = new Array(n)\n\t for(var i=0; i<n; ++i) {\n\t npos[i] = [ zc[i] ]\n\t ncel[i] = [ i ]\n\t }\n\t return {\n\t positions: npos,\n\t cells: ncel\n\t }\n\t}", "function mesh1D(array, level) {\n\t var zc = zeroCrossings(array, level)\n\t var n = zc.length\n\t var npos = new Array(n)\n\t var ncel = new Array(n)\n\t for(var i=0; i<n; ++i) {\n\t npos[i] = [ zc[i] ]\n\t ncel[i] = [ i ]\n\t }\n\t return {\n\t positions: npos,\n\t cells: ncel\n\t }\n\t}", "subdivide_triangle( a, b, c, count ) { \n\n // Base case of recursion - we've hit the finest level of detail we want. \n if( count <= 0) {\n this.indices.push( a,b,c ); \n return; \n }\n\n // So we're not at the base case. So, build 3 new vertices at midpoints,\n // and extrude them out to touch the unit sphere (length 1).\n var ab_vert = this.arrays.position[a].mix( this.arrays.position[b], 0.5).normalized(), \n ac_vert = this.arrays.position[a].mix( this.arrays.position[c], 0.5).normalized(),\n bc_vert = this.arrays.position[b].mix( this.arrays.position[c], 0.5).normalized(); \n\n // Here, push() returns the indices of the three new vertices (plus one).\n var ab = this.arrays.position.push( ab_vert ) - 1,\n ac = this.arrays.position.push( ac_vert ) - 1, \n bc = this.arrays.position.push( bc_vert ) - 1; \n\n // Recurse on four smaller triangles, and we're done. Skipping every fourth vertex index in \n // our list takes you down one level of detail, and so on, due to the way we're building it.\n this.subdivide_triangle( a, ab, ac, count - 1 );\n this.subdivide_triangle( ab, b, bc, count - 1 );\n this.subdivide_triangle( ac, bc, c, count - 1 );\n this.subdivide_triangle( ab, bc, ac, count - 1 );\n }", "function meshify(topology, key) {\n var object = topology.objects[key];\n var features = topojson.feature(topology, object).features;\n var mesh = topojson.mesh(topology, object);\n return {\n features: features,\n mesh: mesh\n };\n }", "translated(dx, dy, dz) {\n let vertices = this.vertices.map(\n ([x, y, z]) => [x + dx, y + dy, z + dz]);\n return new Mesh(vertices, this.faces, this.faceNormals, this.vertexNormals, false);\n }", "function getMorphTrianglePositions(morph, ia, ib, ic, a, b, c) {\n var ia3 = ia * 3;\n var ib3 = ib * 3;\n var ic3 = ic * 3;\n var positions1 = morph.targets[morph.key1].positions;\n var positions2 = morph.targets[morph.key2].positions;\n var decodeMat1 = morph.targets[morph.key1].positionDecodeMat;\n var decodeMat2 = morph.targets[morph.key2].positionDecodeMat;\n\n if (morph.compressedPositions) {\n SceneJS_math_decompressPosition(a1, positions1.subarray(ia3, ia3 + 3), decodeMat1);\n SceneJS_math_decompressPosition(a2, positions2.subarray(ia3, ia3 + 3), decodeMat2);\n SceneJS_math_decompressPosition(b1, positions1.subarray(ib3, ib3 + 3), decodeMat1);\n SceneJS_math_decompressPosition(b2, positions2.subarray(ib3, ib3 + 3), decodeMat2);\n SceneJS_math_decompressPosition(c1, positions1.subarray(ic3, ic3 + 3), decodeMat1);\n SceneJS_math_decompressPosition(c2, positions2.subarray(ic3, ic3 + 3), decodeMat2);\n } else {\n a1.set(positions1.subarray(ia3, ia3 + 3));\n a2.set(positions2.subarray(ia3, ia3 + 3));\n b1.set(positions1.subarray(ib3, ib3 + 3));\n b2.set(positions2.subarray(ib3, ib3 + 3));\n c1.set(positions1.subarray(ic3, ic3 + 3));\n c2.set(positions2.subarray(ic3, ic3 + 3));\n }\n\n vec3.lerp(a, a1, a2, morph.factor);\n vec3.lerp(b, b1, b2, morph.factor);\n vec3.lerp(c, c1, c2, morph.factor);\n }", "function makeCube2(){\n var vertexBuf = [];\n var triBuf = [];\n var normBuf = [];\n var vertices = [[0,0,1],[1,0,1],[1,1,1],[0,1,1],[0,0,0],[1,0,0],[1,1,0],[0,1,0]];\n var triangles = [[6,2,3],[3,7,6],[4,0,1],[1,5,4]];\n var normals = [[0,1,0],[0,1,0],[0,-1,0],[0,-1,0],[0,1,0],[0,1,0],[0,-1,0],[0,-1,0]];\n\n for(var i=0; i<vertices.length; i++)\n {\n vertexBuf.push(vertices[i][0],vertices[i][1],vertices[i][2]);\n }\n\n for(var i=0; i<triangles.length; i++)\n {\n triBuf.push(triangles[i][0],triangles[i][1],triangles[i][2]);\n }\n\n for(var i=0; i<normals.length; i++)\n {\n normBuf.push(normals[i][0],normals[i][1],normals[i][2]);\n }\n //triBufSize = triangles.length;\nreturn({vertices:vertexBuf, normals:normBuf, triangles:triBuf, triSize:triangles.length});\n}", "function loadQuantizedMeshTerrainData(buffer) {\n var pos = 0;\n var cartesian3Elements = 3;\n var boundingSphereElements = cartesian3Elements + 1;\n var cartesian3Length = Float64Array.BYTES_PER_ELEMENT * cartesian3Elements;\n var boundingSphereLength = Float64Array.BYTES_PER_ELEMENT * boundingSphereElements;\n var encodedVertexElements = 3;\n var encodedVertexLength = Uint16Array.BYTES_PER_ELEMENT * encodedVertexElements;\n var triangleElements = 3;\n var bytesPerIndex = Uint16Array.BYTES_PER_ELEMENT;\n var triangleLength = bytesPerIndex * triangleElements;\n\n var view = new DataView(buffer);\n\n addRow(\"header\", \"CenterX\", view.getFloat64(pos, true));\n addRow(\"header\", \"CenterY\", view.getFloat64(pos + 8, true));\n addRow(\"header\", \"CenterZ\", view.getFloat64(pos + 16, true));\n\n pos += cartesian3Length;\n\n var minimumHeight = view.getFloat32(pos, true);\n addRow(\"header\", \"MinimumHeight\", minimumHeight);\n pos += Float32Array.BYTES_PER_ELEMENT;\n\n var maximumHeight = view.getFloat32(pos, true);\n addRow(\"header\", \"MaximumHeight\", maximumHeight);\n pos += Float32Array.BYTES_PER_ELEMENT;\n\n addRow(\"header\", \"BoundingSphereCenterX\", view.getFloat64(pos, true));\n addRow(\"header\", \"BoundingSphereCenterY\", view.getFloat64(pos + 8, true));\n addRow(\"header\", \"BoundingSphereCenterZ\", view.getFloat64(pos + 16, true));\n addRow(\"header\", \"BoundingSphereCenterRadius\", view.getFloat64(pos + 24, true));\n pos += boundingSphereLength;\n\n addRow(\"header\", \"HorizonOcclusionPointX\", view.getFloat64(pos, true));\n addRow(\"header\", \"HorizonOcclusionPointY\", view.getFloat64(pos + 8, true));\n addRow(\"header\", \"HorizonOcclusionPointZ\", view.getFloat64(pos + 16, true));\n pos += cartesian3Length;\n\n var vertexCount = view.getUint32(pos, true);\n\n document.getElementById(\"verticesTitle\").innerHTML = \"Vertices: \" + vertexCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n\n var encodedVertexBuffer = new Uint16Array(buffer, pos, vertexCount * 3);\n pos += vertexCount * encodedVertexLength;\n\n if (vertexCount > 64 * 1024) {\n // More than 64k vertices, so indices are 32-bit.\n bytesPerIndex = Uint32Array.BYTES_PER_ELEMENT;\n triangleLength = bytesPerIndex * triangleElements;\n }\n\n // Decode the vertex buffer.\n var uBuffer = encodedVertexBuffer.subarray(0, vertexCount);\n var vBuffer = encodedVertexBuffer.subarray(vertexCount, 2 * vertexCount);\n var heightBuffer = encodedVertexBuffer.subarray(vertexCount * 2, 3 * vertexCount);\n\n var i;\n var u = 0;\n var v = 0;\n var height = 0;\n\n function zigZagDecode(value) {\n return (value >> 1) ^ (-(value & 1));\n }\n\n for (i = 0; i < vertexCount; ++i) {\n u += zigZagDecode(uBuffer[i]);\n v += zigZagDecode(vBuffer[i]);\n height += zigZagDecode(heightBuffer[i]);\n\n addRow(\"vertices\", [uBuffer[i], vBuffer[i], heightBuffer[i]], [u, v, height]);\n\n uBuffer[i] = u;\n vBuffer[i] = v;\n heightBuffer[i] = height;\n }\n\n // skip over any additional padding that was added for 2/4 byte alignment\n if (pos % bytesPerIndex !== 0) {\n pos += (bytesPerIndex - (pos % bytesPerIndex));\n }\n\n var triangleCount = view.getUint32(pos, true);\n document.getElementById(\"trianglesTitle\").innerHTML = \"Triangles: \" + triangleCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n\n var indices = createTypedArrayFromArrayBuffer(vertexCount, buffer, pos, triangleCount * triangleElements);\n pos += triangleCount * triangleLength;\n\n // High water mark decoding based on decompressIndices_ in webgl-loader's loader.js.\n // https://code.google.com/p/webgl-loader/source/browse/trunk/samples/loader.js?r=99#55\n // Copyright 2012 Google Inc., Apache 2.0 license.\n var highest = 0;\n for (i = 0; i < indices.length; ++i) {\n var code = indices[i];\n \n indices[i] = highest - code;\n if (code === 0) {\n ++highest;\n }\n }\n\n for (i = 0; i < indices.length; ) {\n addRow(\"triangles\", [i/3], [indices[i], indices[i + 1], indices[i + 2]]);\n i += 3;\n }\n\n\n var westVertexCount = view.getUint32(pos, true);\n document.getElementById(\"westTitle\").innerHTML = \"West Vertices: \" + westVertexCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n var westIndices = createTypedArrayFromArrayBuffer(vertexCount, buffer, pos, westVertexCount);\n pos += westVertexCount * bytesPerIndex;\n for (i = 0; i < westVertexCount; ++i) {\n addRow(\"west\", i, westIndices[i]);\n }\n\n var southVertexCount = view.getUint32(pos, true);\n document.getElementById(\"southTitle\").innerHTML = \"South Vertices: \" + southVertexCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n var southIndices = createTypedArrayFromArrayBuffer(vertexCount, buffer, pos, southVertexCount);\n pos += southVertexCount * bytesPerIndex;\n for (i = 0; i < southVertexCount; ++i) {\n addRow(\"south\", i, southIndices[i]);\n }\n\n var eastVertexCount = view.getUint32(pos, true);\n document.getElementById(\"eastTitle\").innerHTML = \"East Vertices: \" + eastVertexCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n var eastIndices = createTypedArrayFromArrayBuffer(vertexCount, buffer, pos, eastVertexCount);\n pos += eastVertexCount * bytesPerIndex;\n for (i = 0; i < eastVertexCount; ++i) {\n addRow(\"east\", i, eastIndices[i]);\n }\n\n var northVertexCount = view.getUint32(pos, true);\n document.getElementById(\"northTitle\").innerHTML = \"North Vertices: \" + northVertexCount;\n pos += Uint32Array.BYTES_PER_ELEMENT;\n var northIndices = createTypedArrayFromArrayBuffer(vertexCount, buffer, pos, northVertexCount);\n pos += northVertexCount * bytesPerIndex;\n for (i = 0; i < northVertexCount; ++i) {\n addRow(\"north\", i, northIndices[i]);\n }\n\n var encodedNormalBuffer;\n var waterMaskBuffer;\n while (pos < view.byteLength) {\n var extensionId = view.getUint8(pos, true);\n pos += Uint8Array.BYTES_PER_ELEMENT;\n var extensionLength = view.getUint32(pos, true);\n pos += Uint32Array.BYTES_PER_ELEMENT;\n\n if (extensionId === 1) {\n encodedNormalBuffer = new Uint8Array(buffer, pos, vertexCount * 2);\n\n for (i = 0; i < vertexCount; ) {\n \tvar decoded = [0,0,0];\n \tvar encodedX = encodedNormalBuffer[i];\n \tvar encodedY = encodedNormalBuffer[i+1];\n addRow(\"normals\", [encodedX, encodedY], octDecode(encodedX, encodedY));\n i += 2;\n }\n\n } else if (extensionId === 2) {\n waterMaskBuffer = new Uint8Array(buffer, pos, extensionLength);\n }\n pos += extensionLength;\n }\n}", "function cubeTriangles(grid, isoLevel)\r\n{\r\n let triangles = [];\r\n let cubeindex = 0;\r\n let vertlist = [];\r\n\r\n /*\r\n Determine the index into the edge table which\r\n tells us which vertices are inside of the surface\r\n */\r\n cubeindex = 0;\r\n if (grid.val[0] < isoLevel) cubeindex |= 1;\r\n if (grid.val[1] < isoLevel) cubeindex |= 2;\r\n if (grid.val[2] < isoLevel) cubeindex |= 4;\r\n if (grid.val[3] < isoLevel) cubeindex |= 8;\r\n if (grid.val[4] < isoLevel) cubeindex |= 16;\r\n if (grid.val[5] < isoLevel) cubeindex |= 32;\r\n if (grid.val[6] < isoLevel) cubeindex |= 64;\r\n if (grid.val[7] < isoLevel) cubeindex |= 128;\r\n\r\n /* Cube is entirely in/out of the surface */\r\n if (edgeTable[cubeindex] == 0)\r\n return(0);\r\n\r\n /* Find the vertices where the surface intersects the cube */\r\n if (edgeTable[cubeindex] & 1) vertlist[0] = vertexInterp(isoLevel,grid.p[0],grid.p[1],grid.val[0],grid.val[1]);\r\n if (edgeTable[cubeindex] & 2) vertlist[1] = vertexInterp(isoLevel,grid.p[1],grid.p[2],grid.val[1],grid.val[2]);\r\n if (edgeTable[cubeindex] & 4) vertlist[2] = vertexInterp(isoLevel,grid.p[2],grid.p[3],grid.val[2],grid.val[3]);\r\n if (edgeTable[cubeindex] & 8) vertlist[3] = vertexInterp(isoLevel,grid.p[3],grid.p[0],grid.val[3],grid.val[0]);\r\n if (edgeTable[cubeindex] & 16) vertlist[4] = vertexInterp(isoLevel,grid.p[4],grid.p[5],grid.val[4],grid.val[5]);\r\n if (edgeTable[cubeindex] & 32) vertlist[5] = vertexInterp(isoLevel,grid.p[5],grid.p[6],grid.val[5],grid.val[6]);\r\n if (edgeTable[cubeindex] & 64) vertlist[6] = vertexInterp(isoLevel,grid.p[6],grid.p[7],grid.val[6],grid.val[7]);\r\n if (edgeTable[cubeindex] & 128) vertlist[7] = vertexInterp(isoLevel,grid.p[7],grid.p[4],grid.val[7],grid.val[4]);\r\n if (edgeTable[cubeindex] & 256) vertlist[8] = vertexInterp(isoLevel,grid.p[0],grid.p[4],grid.val[0],grid.val[4]);\r\n if (edgeTable[cubeindex] & 512) vertlist[9] = vertexInterp(isoLevel,grid.p[1],grid.p[5],grid.val[1],grid.val[5]);\r\n if (edgeTable[cubeindex] & 1024) vertlist[10] = vertexInterp(isoLevel,grid.p[2],grid.p[6],grid.val[2],grid.val[6]);\r\n if (edgeTable[cubeindex] & 2048) vertlist[11] = vertexInterp(isoLevel,grid.p[3],grid.p[7],grid.val[3],grid.val[7]);\r\n\r\n /* Create the triangle */\r\n let ntriang = 0;\r\n for (let i=0; triTable[cubeindex][i]!=-1; i+=3) {\r\n triangles[ntriang] = []\r\n triangles[ntriang][0] = vertlist[triTable[cubeindex][i ]];\r\n triangles[ntriang][1] = vertlist[triTable[cubeindex][i+1]];\r\n triangles[ntriang][2] = vertlist[triTable[cubeindex][i+2]];\r\n ntriang++;\r\n }\r\n triangles.numTriangles = ntriang\r\n return(triangles);\r\n}", "update() {\n\n\t\tlet x = new Uint32Array(3);\n\t\tlet R = new Float32Array([1, (this.dimensions[0] + 1), (this.dimensions[0] + 1) * (this.dimensions[1] + 1)]);\n\n\t\tlet grid = new Float32Array(8);\n\n\t\tlet maxVertexCount = R[2] * 2;\n\n\t\tif(maxVertexCount > 65536) {\n\n\t\t\tthrow new Error(\"The specified dimensions exceed the maximum possible number of vertices (65536).\");\n\n\t\t}\n\n\t\tlet indices = new Uint16Array(maxVertexCount * 6);\n\t\tlet vertexIndices = new Uint16Array(maxVertexCount);\n\t\tlet vertices = new Float32Array(vertexIndices.length * 3);\n\t\tlet vertexCounter = 0;\n\t\tlet indexCounter = 0;\n\t\tlet m;\n\n\t\tlet scale = new Float32Array(3);\n\t\tlet shift = new Float32Array(3);\n\n\t\tlet i, j, k, bufferNo, n;\n\t\tlet mask, g, p;\n\n\t\tlet v = new Float32Array(3);\n\t\tlet edgeMask, edgeCount;\n\t\tlet e0, e1, g0, g1, t, a, b;\n\t\tlet s, iu, iv, du, dv;\n\n\t\tfor(i = 0; i < 3; ++i) {\n\n\t\t\tscale[i] = (this.bounds[1][i] - this.bounds[0][i]) / this.dimensions[i];\n\t\t\tshift[i] = this.bounds[0][i];\n\n\t\t}\n\n\t\t// March over the voxel grid.\n\t\tfor(x[2] = 0, n = 0, bufferNo = 1; x[2] < (this.dimensions[2] - 1); ++x[2], n += this.dimensions[0], bufferNo ^= 1, R[2] =- R[2]) {\n\n\t\t\tm = 1 + (this.dimensions[0] + 1) * (1 + bufferNo * (this.dimensions[1] + 1));\n\n\t\t\t// The contents of the vertexIndices will be the indices of the vertices on the previous x/y slice of the volume.\n\t\t\tfor(x[1] = 0; x[1] < this.dimensions[1] - 1; ++x[1], ++n, m += 2) {\n\n\t\t\t\tfor(x[0] = 0, mask = 0, g = 0; x[0] < this.dimensions[0] - 1; ++x[0], ++n, ++m) {\n\n\t\t\t\t\t/* Read in 8 field values around this vertex and store them in an array.\n\t\t\t\t\t * Also calculate 8-bit mask, like in marching cubes, so we can speed up sign checks later.\n\t\t\t\t\t */\n\n\t\t\t\t\tfor(k = 0; k < 2; ++k) {\n\n\t\t\t\t\t\tfor(j = 0; j < 2; ++j) {\n\n\t\t\t\t\t\t\tfor(i = 0; i < 2; ++i, ++g) {\n\n\t\t\t\t\t\t\t\tp = this.potential(\n\t\t\t\t\t\t\t\t\tscale[0] * (x[0] + i) + shift[0],\n\t\t\t\t\t\t\t\t\tscale[1] * (x[1] + j) + shift[1],\n\t\t\t\t\t\t\t\t\tscale[2] * (x[2] + k) + shift[2]\n\t\t\t\t\t\t\t\t);\n\n\t\t\t\t\t\t\t\tgrid[g] = p;\n\t\t\t\t\t\t\t\tmask |= (p < 0) ? (1 << g) : 0;\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t\t// Continue if the cell doesn't intersect the boundary.\n\t\t\t\t\tif(mask !== 0 && mask !== 0xff) {\n\n\t\t\t\t\t\t// Sum up edge intersections.\n\t\t\t\t\t\tedgeMask = EDGE_TABLE[mask];\n\t\t\t\t\t\tv[0] = v[1] = v[2] = 0.0;\n\t\t\t\t\t\tedgeCount = 0;\n\n\t\t\t\t\t\t// For every edge of the cube.\n\t\t\t\t\t\tfor(i = 0; i < 12; ++i) {\n\n\t\t\t\t\t\t\t// Use edge mask to check if it is crossed.\n\t\t\t\t\t\t\tif(edgeMask & (1 << i)) {\n\n\t\t\t\t\t\t\t\t// If it did, increment number of edge crossings.\n\t\t\t\t\t\t\t\t++edgeCount;\n\n\t\t\t\t\t\t\t\t// Now find the point of intersection.\n\n\t\t\t\t\t\t\t\t// Unpack vertices.\n\t\t\t\t\t\t\t\te0 = CUBE_EDGES[i << 1];\n\t\t\t\t\t\t\t\te1 = CUBE_EDGES[(i << 1) + 1];\n\n\t\t\t\t\t\t\t\t// Unpack grid values.\n\t\t\t\t\t\t\t\tg0 = grid[e0];\n\t\t\t\t\t\t\t\tg1 = grid[e1];\n\n\t\t\t\t\t\t\t\t// Compute point of intersection.\n\t\t\t\t\t\t\t\tt = g0 - g1;\n\n\t\t\t\t\t\t\t\t// Threshold check.\n\t\t\t\t\t\t\t\tif(Math.abs(t) > 1e-6) {\n\n\t\t\t\t\t\t\t\t\tt = g0 / t;\n\n\t\t\t\t\t\t\t\t\t// Interpolate vertices and add up intersections (this can be done without multiplying).\n\t\t\t\t\t\t\t\t\tfor(j = 0, k = 1; j < 3; ++j, k <<= 1) {\n\n\t\t\t\t\t\t\t\t\t\ta = e0 & k;\n\t\t\t\t\t\t\t\t\t\tb = e1 & k;\n\n\t\t\t\t\t\t\t\t\t\tif(a !== b) {\n\n\t\t\t\t\t\t\t\t\t\t\tv[j] += a ? 1.0 - t : t;\n\n\t\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\t\tv[j] += a ? 1.0 : 0;\n\n\t\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Average the edge intersections and add them to coordinate.\n\t\t\t\t\t\ts = 1.0 / edgeCount;\n\n\t\t\t\t\t\tfor(i = 0; i < 3; ++i) {\n\n\t\t\t\t\t\t\tv[i] = scale[i] * (x[i] + s * v[i]) + shift[i];\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Add vertex to vertices, store pointer to vertex in vertexIndices.\n\t\t\t\t\t\tvertexIndices[m] = vertexCounter / 3;\n\t\t\t\t\t\tvertices[vertexCounter++] = v[0];\n\t\t\t\t\t\tvertices[vertexCounter++] = v[1];\n\t\t\t\t\t\tvertices[vertexCounter++] = v[2];\n\n\t\t\t\t\t\t// Add faces together by looping over 3 basis components.\n\t\t\t\t\t\tfor(i = 0; i < 3; ++i) {\n\n\t\t\t\t\t\t\t// The first three entries of the edgeMask count the crossings along the edge.\n\t\t\t\t\t\t\tif(edgeMask & (1 << i)) {\n\n\t\t\t\t\t\t\t\t// i = axes we are pointing along. iu, iv = orthogonal axes.\n\t\t\t\t\t\t\t\tiu = (i + 1) % 3;\n\t\t\t\t\t\t\t\tiv = (i + 2) % 3;\n\n\t\t\t\t\t\t\t\t// If we are on a boundary, skip.\n\t\t\t\t\t\t\t\tif(x[iu] !== 0 && x[iv] !== 0) {\n\n\t\t\t\t\t\t\t\t\t// Otherwise, look up adjacent edges in vertexIndices.\n\t\t\t\t\t\t\t\t\tdu = R[iu];\n\t\t\t\t\t\t\t\t\tdv = R[iv];\n\n\t\t\t\t\t\t\t\t\t// Remember to flip orientation depending on the sign of the corner.\n\t\t\t\t\t\t\t\t\tif(mask & 1) {\n\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - dv];\n\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - dv];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du - dv];\n\n\t\t\t\t\t\t\t\t\t} else {\n\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - dv];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du];\n\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - dv];\n\t\t\t\t\t\t\t\t\t\tindices[indexCounter++] = vertexIndices[m - du - dv];\n\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\n\t\tif(indices.length !== indexCounter) { indices = indices.slice(0, indexCounter); }\n\t\tif(vertices.length !== vertexCounter) { vertices = vertices.slice(0, vertexCounter); }\n\n\t\tthis.setIndex(new THREE.BufferAttribute(indices, 1));\n\t\tthis.addAttribute(\"position\", new THREE.BufferAttribute(vertices, 3));\n\t\t//this.addAttribute(\"uv\", new THREE.BufferAttribute(uvs, 2));\n\n\t}", "function StupidMesh(volume, dims) {\n var vertices = [], faces = [], x = [0,0,0], n = 0;\n for(x[2]=0; x[2]<dims[2]; ++x[2])\n for(x[1]=0; x[1]<dims[1]; ++x[1])\n for(x[0]=0; x[0]<dims[0]; ++x[0], ++n)\n if(!!volume[n]) {\n for(var d=0; d<3; ++d) {\n var t = [x[0], x[1], x[2]]\n , u = [0,0,0]\n , v = [0,0,0];\n u[(d+1)%3] = 1;\n v[(d+2)%3] = 1;\n for(var s=0; s<2; ++s) {\n t[d] = x[d] + s;\n var tmp = u;\n u = v;\n v = tmp;\n var vertex_count = vertices.length;\n vertices.push([t[0], t[1], t[2] ]);\n vertices.push([t[0]+u[0], t[1]+u[1], t[2]+u[2] ]);\n vertices.push([t[0]+u[0]+v[0], t[1]+u[1]+v[1], t[2]+u[2]+v[2]]);\n vertices.push([t[0] +v[0], t[1] +v[1], t[2] +v[2]]);\n faces.push([vertex_count, vertex_count+1, vertex_count+2, vertex_count+3, volume[n]]);\n }\n }\n }\n return { vertices:vertices, faces:faces };\n}", "function Paths() {\n\t\treturn {\n\t\t\tsplineNearFit: function(controls, segments) {\n\t\t\t\tvar division = \"EnsemblBacteria\";\n\t\t\t\tvar splinePath;\n\t\t\t\tif (division == \"EnsemblBacteria\") {\n\t\t\t\t\tsplinePath = new THREE.ClosedSplineCurve3(controls);\n\t\t\t\t} else {\n\t\t\t\t\tsplinePath = new THREE.SplineCurve3(controls);\t\t\t\n\t\t\t\t}\n\t\t\t\t// var splineDivisions = splinePath.getSpacedPoints(segments);\n\t\t\t\treturn splinePath;\n\t\t\t},\n\t\t\t// Following paths constructed from curve segments passing through particle centers\n\t\t\tspline: function(controls, segments) {\n\t\t\t\tvar division = \"NotEnsemblBacteria\";\n\t\t\t\tvar curvePath = new THREE.CurvePath();\n\t\t\t\tvar totalControls = controls.length;\n\n\t\t\t\tif (division == \"EnsemblBacteria\") {\n\t\t\t\t\t// REVISE THIS\n\t\t\t\t\tcurvePath= new THREE.ClosedSplineCurve3(controls);\n\t\t\t\t} else {\n\t\t\t\t\tfor (var i = 1 ; i < totalControls - 2 ; i = i + 3) {\n\t\t\t\t\t\tvar p1 = controls[i];\n\t\t\t\t\t\tvar p2 = controls[i+1];\n\t\t\t\t\t\tvar p3 = controls[i+2];\n\t\t\t\t\t\tvar p4 = controls[i+3];\n\n\t\t\t\t\t\tvar p23 = new THREE.Vector3(0,0,0);\n\t\t\t\t\t\tp23.addVectors(p3,p2).divideScalar(2);\n\n\t\t\t\t\t\tvar splineCurve = new THREE.CatmullRomCurve3([p1,p23,p4]);\n\t\t\t\t\t\tcurvePath.add(splineCurve);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn curvePath;\n\t\t\t},\t\t\t\n\t\t\tquadraticBezier: function(controls, segments) {\n\t\t\t\tvar division = \"NotEnsemblBacteria\";\n\t\t\t\tvar quadPath = new THREE.CurvePath();\n\t\t\t\tvar totalControls = controls.length;\n\n\t\t\t\tif (division == \"EnsemblBacteria\") {\n\t\t\t\t\t// REVISE THIS\n\t\t\t\t\tquadPath= new THREE.ClosedSplineCurve3(controls);\n\t\t\t\t} else {\n\t\t\t\t\tfor (var i = 1 ; i < totalControls - 2 ; i = i + 3) {\n\t\t\t\t\t\tvar p1 = controls[i];\n\t\t\t\t\t\tvar p2 = controls[i+1];\n\t\t\t\t\t\tvar p3 = controls[i+2];\n\t\t\t\t\t\tvar p4 = controls[i+3];\n\n\t\t\t\t\t\tvar p23 = new THREE.Vector3(0,0,0);\n\t\t\t\t\t\tp23.addVectors(p3,p2).divideScalar(2);\n\n\t\t\t\t\t\tvar quadCurve = new THREE.QuadraticBezierCurve3(p1,p23,p4);\n\t\t\t\t\t\tquadPath.add(quadCurve);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn quadPath;\n\t\t\t},\t\t\t\n\t\t\tcubicBezier: function(controls, segments, closed) {\n\t\t\t\tclosed = closed || false; // closed if circular chromosome eg. Bacteria\n\t\t\t\tvar cubicPath = new THREE.CurvePath();\n\t\t\t\tvar totalControls = controls.length;\n\t\t\t\tvar cubicCurveStart, cubicCurveEnd;\n\n\t\t\t\t\t// controls[0] == start point\n\t\t\t\t\t// controls[1] == start point fore control\n\t\t\t\t\t// controls[2] == first particle back control\n\t\t\t\t\t// controls[3] == first particle\n\t\t\t\t\t// ...\n\t\t\t\t\t// n == totalControls - 1\n\t\t\t\t\t// controls[n-3] == last particle\n\t\t\t\t\t// controls[n-2] == last particle fore control\n\t\t\t\t\t// controls[n-1] == end point back control\n\t\t\t\t\t// controls[n] == end point (if closed, end point == start point)\n\n\t\t\t\t\tfor (var i = 0 ; i < totalControls - 1 ; i = i + 3) {\n\n\t\t\t\t\t\tvar c1 = controls[i];\n\t\t\t\t\t\tvar c2 = controls[i+1];\n\t\t\t\t\t\tvar c3 = controls[i+2];\n\t\t\t\t\t\tvar c4 = controls[i+3];\n\n\t\t\t\t\t\tvar cubicCurve = new THREE.CubicBezierCurve3(c1,c2,c3,c4);\n\t\t\t\t\t\t cubicPath.add(cubicCurve);\n\t\t\t\t\t}\n\t\t\t\treturn cubicPath;\n\t\t\t}\n\t\t};\n\t}", "function drawQuad(centerPos, transform)\n{\n if(!global.scene.isRecording())\n {\n fadePath = false;\n\n var left = centerPos.x - 3;\n var right = centerPos.x + 3;\n var top = centerPos.z + 3;\n var bottom = centerPos.z - 3; \n \n var colorVal = new vec3(1,1,1);\n \n var v1 = centerPos.add(transform.forward.uniformScale(3.0)).add(transform.right.uniformScale(-3.0));\n var v2 = centerPos.add(transform.forward.uniformScale(-3.0)).add(transform.right.uniformScale(-3.0));\n var v3 = centerPos.add(transform.forward.uniformScale(-3.0)).add(transform.right.uniformScale(3.0));\n var v4 = centerPos.add(transform.forward.uniformScale(3.0)).add(transform.right.uniformScale(3.0));\n builder.appendVerticesInterleaved([\n // Position Normal UV Color Index\n v1.x, centerPos.y, v1.z, 0, 0, 1, 0, 1, colorVal.x,colorVal.y,colorVal.z,0, // 0\n v2.x, centerPos.y, v2.z, 0, 0, 1, 0, 0, colorVal.x,colorVal.y,colorVal.z,0, // 1 \n v3.x, centerPos.y, v3.z, 0, 0, 1, 1, 0, colorVal.x,colorVal.y,colorVal.z,0, // 2\n v4.x, centerPos.y, v4.z, 0, 0, 1, 1, 1, colorVal.x,colorVal.y,colorVal.z,0, // 3 \n ]);\n \n var startIndex = (pointCounter-1) * 4;\n builder.appendIndices([\n 0 + startIndex, 1 + startIndex, 2 + startIndex, // First Triangle\n 2 + startIndex, 3 + startIndex, 0 + startIndex, // Second Triangle\n ]);\n \n if(builder.isValid()){\n script.drawingObject.mesh = builder.getMesh();\n builder.updateMesh();\n }\n else{\n print(\"Follow Path Anim: Mesh data invalid!\");\n }\n } \n}", "static _resolveTri(x, y, meshes, scale, shiftZ) {\n const isect = (new Laser()).raycast(\n new THREE.Vector3(x, y, 12000), // ray origin\n new THREE.Vector3(0, 0, -1), // ray direction\n meshes);\n // console.log('isect:', isect);\n if (! isect) return null;\n\n // console.log('isect:', isect);\n // console.log('isect.point.z:', isect.point.z);\n // console.log('isect.faceIndex:', isect.faceIndex);\n // https://stackoverflow.com/questions/41540313/three-buffergeometry-accessing-face-indices-and-face-normals\n const faceIndex = isect.faceIndex;\n const indexArr = isect.object.geometry.index.array;\n const attrPos = isect.object.geometry.attributes.position;\n const tri = [0, 1, 2].map(i => (new THREE.Vector3())\n .fromBufferAttribute(attrPos, indexArr[3 * faceIndex + i])\n .multiplyScalar(scale)\n // z's of tri is relative to the isect point\n .add(new THREE.Vector3(0, 0, shiftZ ? shiftZ : -isect.point.z)));\n // console.log('isect tri (z-shifted):', tri);\n return { // return new objects to remain pure\n faceIndex: isect.faceIndex,\n isectPoint: isect.point.clone(),\n tri: tri,\n normal: isect.face.normal.clone(),\n };\n }", "function shapeToPath(shape, points, closed) {\n closed = closed !== undefined ? closed : true;\n\n const profileGeometry = new THREE.ShapeGeometry(shape);\n profileGeometry.rotateX(Math.PI * .5);\n\n const profile = profileGeometry.attributes.position;\n const faces = new Float32Array(profile.count * points.length * 3);\n\n for (let i = 0; i < points.length; i++) {\n const v1 = new THREE.Vector2().subVectors(points[i - 1 < 0 ? points.length - 1 : i - 1], points[i]);\n const v2 = new THREE.Vector2().subVectors(points[i + 1 == points.length ? 0 : i + 1], points[i]);\n const angle = v2.angle() - v1.angle();\n const halfAngle = angle * .5;\n let hA = halfAngle;\n let tA = v2.angle() + Math.PI * .5;\n\n if (!closed){\n if (i == 0 || i == points.length - 1) {hA = Math.PI * .5;}\n if (i == points.length - 1) {tA = v1.angle() - Math.PI * .5;}\n }\n\n const shift = Math.tan(hA - Math.PI * .5);\n const shiftMatrix = new THREE.Matrix4().set(\n 1, 0, 0, 0,\n -shift, 1, 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1\n );\n\n const tempAngle = tA;\n const rotationMatrix = new THREE.Matrix4().set(\n Math.cos(tempAngle), -Math.sin(tempAngle), 0, 0,\n Math.sin(tempAngle), Math.cos(tempAngle), 0, 0,\n 0, 0, 1, 0,\n 0, 0, 0, 1\n );\n\n const translationMatrix = new THREE.Matrix4().set(\n 1, 0, 0, points[i].x,\n 0, 1, 0, points[i].y,\n 0, 0, 1, 0,\n 0, 0, 0, 1,\n );\n\n const cloneProfile = profile.clone();\n cloneProfile.applyMatrix4(shiftMatrix);\n cloneProfile.applyMatrix4(rotationMatrix);\n cloneProfile.applyMatrix4(translationMatrix);\n\n faces.set(cloneProfile.array, cloneProfile.count * i * 3);\n }\n\n const index = [];\n const lastCorner = closed == false ? points.length - 1: points.length;\n\n for (let i = 0; i < lastCorner; i++) {\n for (let j = 0; j < profile.count; j++) {\n const currCorner = i;\n const nextCorner = i + 1 == points.length ? 0 : i + 1;\n const currPoint = j;\n const nextPoint = j + 1 == profile.count ? 0 : j + 1;\n\n const a = nextPoint + profile.count * currCorner;\n const b = currPoint + profile.count * currCorner;\n const c = currPoint + profile.count * nextCorner;\n const d = nextPoint + profile.count * nextCorner;\n\n index.push(a, b, d);\n index.push(b, c, d);\n }\n }\n\n if (!closed) {\n // cheating because we know the profile length is 4 (for now)\n const p1 = 0 + profile.count * 0;\n const p2 = 1 + profile.count * 0;\n const p3 = 2 + profile.count * 0;\n const p4 = 3 + profile.count * 0;\n index.push(p1, p2, p3);\n index.push(p1, p3, p4);\n const lc = lastCorner;\n const p5 = 0 + profile.count * lc;\n const p6 = 1 + profile.count * lc;\n const p7 = 2 + profile.count * lc;\n const p8 = 3 + profile.count * lc;\n index.push(p7, p6, p5);\n index.push(p8, p7, p5);\n }\n\n return {index, faces};\n}", "function PathMap() {\n /**\n * Contains a map of path elements\n *\n * <h1>Path definition</h1>\n * A parameterized path is defined like this:\n * <pre>\n * 'GATEWAY_PARALLEL': {\n * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n * height: 17.5,\n * width: 17.5,\n * heightElements: [2.5, 7.5],\n * widthElements: [2.5, 7.5]\n * }\n * </pre>\n * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling\n * is based on the ratio between the specified height and width in this object and the\n * height and width that is set as scale target (Note x,y coordinates will be scaled with\n * individual ratios).</p>\n * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.\n * The scaling is based on the computed ratios.\n * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using\n * the computed ratio coefficient.\n * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.\n * <ul>\n * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>\n * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>\n * </ul>\n * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.\n * </p>\n m1,1\n l 0,55.3\n c 29.8,19.7 48.4,-4.2 67.2,-6.7\n c 12.2,-2.3 19.8,1.6 30.8,6.2\n l 0,-54.6\n z\n */\n this.pathMap = {\n 'KNOWLEDGE_SOURCE': {\n d: 'm {mx},{my} ' + 'l 0,{e.y0} ' + 'c {e.x0},{e.y1} {e.x1},-{e.y2} {e.x2},-{e.y3} ' + 'c {e.x3},-{e.y4} {e.x4},{e.y5} {e.x5},{e.y6} ' + 'l 0,-{e.y7}z',\n width: 100,\n height: 65,\n widthElements: [29.8, 48.4, 67.2, 12.2, 19.8, 30.8],\n heightElements: [55.3, 19.7, 4.2, 6.7, 2.3, 1.6, 6.2, 54.6]\n },\n 'BUSINESS_KNOWLEDGE_MODEL': {\n d: 'm {mx},{my} l {e.x0},-{e.y0} l {e.x1},0 l 0,{e.y1} l -{e.x2},{e.y2} l -{e.x3},0z',\n width: 125,\n height: 45,\n widthElements: [13.8, 109.2, 13.8, 109.1],\n heightElements: [13.2, 29.8, 13.2]\n },\n 'TEXT_ANNOTATION': {\n d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',\n width: 10,\n height: 30,\n widthElements: [10],\n heightElements: [30]\n }\n };\n this.getRawPath = function getRawPath(pathId) {\n return this.pathMap[pathId].d;\n };\n /**\n * Scales the path to the given height and width.\n * <h1>Use case</h1>\n * <p>Use case is to scale the content of elements (event, gateways) based\n * on the element bounding box's size.\n * </p>\n * <h1>Why not transform</h1>\n * <p>Scaling a path with transform() will also scale the stroke and IE does not support\n * the option 'non-scaling-stroke' to prevent this.\n * Also there are use cases where only some parts of a path should be\n * scaled.</p>\n *\n * @param {String} pathId The ID of the path.\n * @param {Object} param <p>\n * Example param object scales the path to 60% size of the container (data.width, data.height).\n * <pre>\n * {\n * xScaleFactor: 0.6,\n * yScaleFactor:0.6,\n * containerWidth: data.width,\n * containerHeight: data.height,\n * position: {\n * mx: 0.46,\n * my: 0.2,\n * }\n * }\n * </pre>\n * <ul>\n * <li>targetpathwidth = xScaleFactor * containerWidth</li>\n * <li>targetpathheight = yScaleFactor * containerHeight</li>\n * <li>Position is used to set the starting coordinate of the path. M is computed:\n * <ul>\n * <li>position.x * containerWidth</li>\n * <li>position.y * containerHeight</li>\n * </ul>\n * Center of the container <pre> position: {\n * mx: 0.5,\n * my: 0.5,\n * }</pre>\n * Upper left corner of the container\n * <pre> position: {\n * mx: 0.0,\n * my: 0.0,\n * }</pre>\n * </li>\n * </ul>\n * </p>\n *\n */\n this.getScaledPath = function getScaledPath(pathId, param) {\n var rawPath = this.pathMap[pathId];\n // positioning\n // compute the start point of the path\n var mx, my;\n if (param.abspos) {\n mx = param.abspos.x;\n my = param.abspos.y;\n }\n else {\n mx = param.containerWidth * param.position.mx;\n my = param.containerHeight * param.position.my;\n }\n var coordinates = {}; // map for the scaled coordinates\n if (param.position) {\n // path\n var heightRatio = param.containerHeight / rawPath.height * param.yScaleFactor;\n var widthRatio = param.containerWidth / rawPath.width * param.xScaleFactor;\n // Apply height ratio\n for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {\n coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;\n }\n // Apply width ratio\n for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {\n coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;\n }\n }\n // Apply value to raw path\n var path = format(rawPath.d, {\n mx: mx,\n my: my,\n e: coordinates\n });\n return path;\n };\n}", "function PathMap() {\n /**\n * Contains a map of path elements\n *\n * <h1>Path definition</h1>\n * A parameterized path is defined like this:\n * <pre>\n * 'GATEWAY_PARALLEL': {\n * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n * height: 17.5,\n * width: 17.5,\n * heightElements: [2.5, 7.5],\n * widthElements: [2.5, 7.5]\n * }\n * </pre>\n * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling\n * is based on the ratio between the specified height and width in this object and the\n * height and width that is set as scale target (Note x,y coordinates will be scaled with\n * individual ratios).</p>\n * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.\n * The scaling is based on the computed ratios.\n * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using\n * the computed ratio coefficient.\n * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.\n * <ul>\n * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>\n * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>\n * </ul>\n * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.\n * </p>\n m1,1\n l 0,55.3\n c 29.8,19.7 48.4,-4.2 67.2,-6.7\n c 12.2,-2.3 19.8,1.6 30.8,6.2\n l 0,-54.6\n z\n */\n this.pathMap = {\n 'KNOWLEDGE_SOURCE': {\n d: 'm {mx},{my} ' + 'l 0,{e.y0} ' + 'c {e.x0},{e.y1} {e.x1},-{e.y2} {e.x2},-{e.y3} ' + 'c {e.x3},-{e.y4} {e.x4},{e.y5} {e.x5},{e.y6} ' + 'l 0,-{e.y7}z',\n width: 100,\n height: 65,\n widthElements: [29.8, 48.4, 67.2, 12.2, 19.8, 30.8],\n heightElements: [55.3, 19.7, 4.2, 6.7, 2.3, 1.6, 6.2, 54.6]\n },\n 'BUSINESS_KNOWLEDGE_MODEL': {\n d: 'm {mx},{my} l {e.x0},-{e.y0} l {e.x1},0 l 0,{e.y1} l -{e.x2},{e.y2} l -{e.x3},0z',\n width: 125,\n height: 45,\n widthElements: [13.8, 109.2, 13.8, 109.1],\n heightElements: [13.2, 29.8, 13.2]\n },\n 'TEXT_ANNOTATION': {\n d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',\n width: 10,\n height: 30,\n widthElements: [10],\n heightElements: [30]\n }\n };\n\n this.getRawPath = function getRawPath(pathId) {\n return this.pathMap[pathId].d;\n };\n /**\n * Scales the path to the given height and width.\n * <h1>Use case</h1>\n * <p>Use case is to scale the content of elements (event, gateways) based\n * on the element bounding box's size.\n * </p>\n * <h1>Why not transform</h1>\n * <p>Scaling a path with transform() will also scale the stroke and IE does not support\n * the option 'non-scaling-stroke' to prevent this.\n * Also there are use cases where only some parts of a path should be\n * scaled.</p>\n *\n * @param {String} pathId The ID of the path.\n * @param {Object} param <p>\n * Example param object scales the path to 60% size of the container (data.width, data.height).\n * <pre>\n * {\n * xScaleFactor: 0.6,\n * yScaleFactor:0.6,\n * containerWidth: data.width,\n * containerHeight: data.height,\n * position: {\n * mx: 0.46,\n * my: 0.2,\n * }\n * }\n * </pre>\n * <ul>\n * <li>targetpathwidth = xScaleFactor * containerWidth</li>\n * <li>targetpathheight = yScaleFactor * containerHeight</li>\n * <li>Position is used to set the starting coordinate of the path. M is computed:\n * <ul>\n * <li>position.x * containerWidth</li>\n * <li>position.y * containerHeight</li>\n * </ul>\n * Center of the container <pre> position: {\n * mx: 0.5,\n * my: 0.5,\n * }</pre>\n * Upper left corner of the container\n * <pre> position: {\n * mx: 0.0,\n * my: 0.0,\n * }</pre>\n * </li>\n * </ul>\n * </p>\n *\n */\n\n\n this.getScaledPath = function getScaledPath(pathId, param) {\n var rawPath = this.pathMap[pathId]; // positioning\n // compute the start point of the path\n\n var mx, my;\n\n if (param.abspos) {\n mx = param.abspos.x;\n my = param.abspos.y;\n } else {\n mx = param.containerWidth * param.position.mx;\n my = param.containerHeight * param.position.my;\n }\n\n var coordinates = {}; // map for the scaled coordinates\n\n if (param.position) {\n // path\n var heightRatio = param.containerHeight / rawPath.height * param.yScaleFactor;\n var widthRatio = param.containerWidth / rawPath.width * param.xScaleFactor; // Apply height ratio\n\n for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {\n coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;\n } // Apply width ratio\n\n\n for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {\n coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;\n }\n } // Apply value to raw path\n\n\n var path = format(rawPath.d, {\n mx: mx,\n my: my,\n e: coordinates\n });\n return path;\n };\n } // helpers //////////////////////", "function getSTLFromScene(params) {\n var root = params.root;\n var matrix = params.matrix || new THREE.Matrix4();\n var strbuf = [];\n strbuf.push(\"solid object\");\n\n function addFace(v0, v1, v2) {\n strbuf.push(\"facet normal 0 0 0\");\n strbuf.push(\" outer loop\");\n strbuf.push(\" vertex \" + v0.x + \" \" + v0.y + \" \" + v0.z);\n strbuf.push(\" vertex \" + v1.x + \" \" + v1.y + \" \" + v1.z);\n strbuf.push(\" vertex \" + v2.x + \" \" + v2.y + \" \" + v2.z);\n strbuf.push(\" endloop\");\n strbuf.push(\"endfacet\");\n }\n function addGeometry(geometry, matrix) {\n if (!geometry) {\n return;\n }\n var vertices = geometry.vertices;\n var faces = geometry.faces;\n if (!geometry.isBufferGeometry) {\n if (!vertices || !vertices.length || !faces || !faces.length) {\n return;\n }\n }\n if (geometry.isBufferGeometry) {\n var position = geometry.getAttribute(\"position\").array || [];\n var indices;\n if (geometry.index && geometry.index.array) {\n indices = geometry.index.array || [];\n }\n var v0 = new THREE.Vector3();\n var v1 = new THREE.Vector3();\n var v2 = new THREE.Vector3();\n var a = 0;\n var b = 0;\n var c = 0;\n if (indices) {\n for (var i = 0; i < indices.length; i += 3) {\n var a = indices[i] * 3;\n var b = indices[i + 1] * 3;\n var c = indices[i + 2] * 3;\n v0.set(position[a], position[a + 1], position[a + 2]).applyMatrix4(matrix);\n v1.set(position[b], position[b + 1], position[b + 2]).applyMatrix4(matrix);\n v2.set(position[c], position[c + 1], position[c + 2]).applyMatrix4(matrix);\n addFace(v0, v1, v2);\n }\n } else {\n for (var i = 0; i < position.length; i += 9) {\n var a = i;\n var b = i + 3;\n var c = i + 6;\n v0.set(position[a], position[a + 1], position[a + 2]).applyMatrix4(matrix);\n v1.set(position[b], position[b + 1], position[b + 2]).applyMatrix4(matrix);\n v2.set(position[c], position[c + 1], position[c + 2]).applyMatrix4(matrix);\n addFace(v0, v1, v2);\n }\n }\n } else {\n var i3 = 0;\n var a = 0;\n var b = 0;\n var c = 0;\n for (var i = 0; i < faces.length; i++) {\n var face = faces[i];\n a = face.a;\n b = face.b;\n c = face.c;\n var v0 = vertices[a].clone().applyMatrix4(matrix);\n var v1 = vertices[b].clone().applyMatrix4(matrix);\n var v2 = vertices[c].clone().applyMatrix4(matrix);\n addFace(v0, v1, v2);\n }\n }\n }\n strbuf.push(\"endsolid insole\");\n\n function _doIt(iter, matrix) {\n matrix = matrix.clone().multiply(iter.matrix);\n if (iter.geometry) {\n addGeometry(iter.geometry, matrix);\n }\n for (var i = 0; i < iter.children.length; i++) {\n var child = iter.children[i];\n if (!child) {\n return;\n }\n _doIt(child, matrix);\n }\n }\n _doIt(root, matrix);\n\n return strbuf;\n}", "function curve2dTo3d(w,L,U,D,Q, pg, qg) {\n var i,n, p, q; // a, vx, vy, vz\n for( i=0,n=pg.length; i<n; i++ ) {\n // Pl = <a,b,c>\n p = pg[i];\n // Pw = aX + bY + cZ + Q\n q = qg[i];\n q[0] = w*p[0]*L[0] + w*p[1]*U[0] + w*p[2]*D[0] + Q[0];\n q[1] = w*p[0]*L[1] + w*p[1]*U[1] + w*p[2]*D[1] + Q[1];\n q[2] = w*p[0]*L[2] + w*p[1]*U[2] + w*p[2]*D[2] + Q[2];\n }\n }", "function meshToGeometry(mdata) {\n\n var mesh = mdata.mesh;\n var geometry = createLmvBufferGeometry();\n\n\n geometry.byteSize = 0;\n\n geometry.vb = mesh.vb;\n geometry.vbbuffer = undefined;\n geometry.vbNeedsUpdate = true;\n geometry.byteSize += mesh.vb.byteLength;\n\n geometry.vbstride = mesh.vbstride;\n if (mesh.isLines) /* mesh is SVF lines */\n geometry.isLines = mesh.isLines;\n if (mdata.is2d) /* mesh is from F2D */\n geometry.is2d = true;\n\n geometry.numInstances = mesh.numInstances;\n\n for (var attributeName in mesh.vblayout) {\n var attributeData = mesh.vblayout[attributeName];\n\n //geometry.addAttribute(attributeName, findBufferAttribute(attributeData, geometry.numInstances));\n geometry.attributes[attributeName] = findBufferAttribute(attributeName, attributeData, geometry.numInstances);\n }\n\n //Index buffer setup\n if (!Private_Global.memoryOptimizedLoading) {\n geometry.addAttribute(\"index\", new THREE.BufferAttribute(mesh.indices, 1));\n } else {\n\n geometry.attributes.index = indexAttr;\n geometry.ib = mesh.indices;\n geometry.ibbuffer = undefined;\n }\n\n geometry.attributesKeys = findAttributesKeys(geometry);\n\n geometry.byteSize += mesh.indices.byteLength;\n\n //TODO: Not sure chunking into list of smaller offset/counts\n //is required for LMV data since it's already broken up.\n //if (mesh.indices.length > 65535)\n if (mesh.vb.length / mesh.vbstride > 65535)\n Logger.warn(\"Mesh with >65535 vertices. It will fail to draw.\");\n\n //TODO: This is a transient object that gets freed once the geometry\n //is added to the GeometryList. We can save on the object creation\n //eventually when we do micro optimizations.\n geometry.boundingBox = new THREE.Box3().copy(mesh.boundingBox);\n geometry.boundingSphere = new THREE.Sphere().copy(mesh.boundingSphere);\n\n //MEM\n geometry.drawcalls = null;\n geometry.offsets = null;\n\n mdata.geometry = geometry;\n\n mdata.mesh = null;\n }", "function import3dObjSync(config) {\n var scale = config.scale || 1;\n var xRot = config.xRot || null;\n var yRot = config.yRot || null;\n var zRot = config.zRot || null;\n\n var vertex = [],\n faces = [],\n uvs = [];\n var re = /\\s+/;\n\n var minx, miny, minz, maxx, maxy, maxz;\n minx = miny = minz = maxx = maxy = maxz = 0;\n\n var data = getOBJFileSync(config);\n if (data == false) {\n return;\n }\n var lines = data.split(\"\\n\");\n\n for (let i = 0, imax=lines.length; i < imax; i++) {\n let line = lines[i].split(re);\n switch (line[0]) {\n case \"v\":\n var x = parseFloat(line[1]) * scale,\n y = parseFloat(line[2]) * scale,\n z = parseFloat(line[3]) * scale;\n vertex.push({\n x: x,\n y: y,\n z: z\n });\n if (x < minx) {\n minx = x\n } else {\n if (x > maxx) {\n maxx = x\n }\n }\n if (y < miny) {\n miny = y\n } else {\n if (y > maxy) {\n maxy = y\n }\n }\n if (z < minz) {\n minz = z\n } else {\n if (z > maxz) {\n maxz = z\n }\n }\n break;\n case \"vt\":\n var u = parseFloat(line[1]),\n v = parseFloat(line[2]);\n uvs.push([u, v]);\n break;\n case \"f\":\n line.splice(0, 1);\n var vertices = [],\n uvcoords = [];\n for (var j = 0, vindex, vps; j < line.length; j++) {\n vindex = line[config.reorder ? line.length - j - 1 : j];\n if (vindex.length !== 0) {\n vps = vindex.split(\"/\");\n vertices.push(parseInt(vps[0]) - 1);\n if (vps.length > 1 && vindex.indexOf(\"//\") === -1) {\n var uv = parseInt(vps[1]) - 1;\n if (uvs.length > uv) {\n uvcoords.push(uvs[uv][0], uvs[uv][1])\n }\n }\n }\n }\n faces.push(vertices);\n if (uvcoords.length !== 0) {\n poly.uvs = uvcoords\n }\n break\n }\n }\n if (config.center) {\n var cdispx = (minx + maxx) / 2,\n cdispy = (miny + maxy) / 2,\n cdispz = (minz + maxz) / 2;\n for (var i = 0; i < vertex.length; i++) {\n vertex[i].x -= cdispx;\n vertex[i].y -= cdispy;\n vertex[i].z -= cdispz\n }\n }\n if (config.scaleTo) {\n var sizex = maxx - minx,\n sizey = maxy - miny,\n sizez = maxz - minz;\n var scalefactor = 0;\n if (sizey > sizex) {\n if (sizez > sizey) {\n scalefactor = 1 / (sizez / config.scaleTo)\n } else {\n scalefactor = 1 / (sizey / config.scaleTo)\n }\n } else {\n if (sizez > sizex) {\n scalefactor = 1 / (sizez / config.scaleTo)\n } else {\n scalefactor = 1 / (sizex / config.scaleTo)\n }\n }\n for (let i = 0, imax=vertex.length; i < imax; i++) {\n vertex[i].x *= scalefactor;\n vertex[i].y *= scalefactor;\n vertex[i].z *= scalefactor\n }\n }\n rotateZ3D(zRot, vertex, true);\n rotateY3D(yRot, vertex, true);\n rotateX3D(xRot, vertex, true);\n\n return {\n points: vertex,\n polygons: faces\n }\n }", "static fromJSON(jsnmvtx, ix) {\nvar mvtx;\n//--------\nmvtx = new MeshVertex();\nmvtx.setFromJSON(jsnmvtx, ix);\nreturn mvtx;\n}", "mesh(ID)\n\t{\n\t\t//We don't require ID as an argument, because this method might be called simply to get its structure\n\t\tconst materials ={\n\t\t\tbasic :new THREE.MeshBasicMaterial ({color: 0xfffff, wireframe: true }),//color.r/g/b, wireframe,\n\t\t\tphong :new THREE.MeshPhongMaterial ( ),//color.r/g/b\n\t\t\tstandard:new THREE.MeshStandardMaterial( ),\n\t\t}\n\t\tlet geometry='box'\n\t\tlet material='basic'\n\t\tlet texture='default'\n\t\tlet parent='scene'\n\t\tlet mesh=new THREE.Mesh(geometries[geometry], materials[material])\n\t\tscene.add(mesh)\n\t\tconst item= {\n\t\t\t//NEW STYLE: Should only be able to get directories; not values. It's Unidirectional now.\n\t\t\t//Convention: The name of the function is the name of the threeObject, which is always put in item (for some hackability-->faster dev time but more messy)\n\t\t\tget ID(){return ID},\n\t\t\ttransform:attributes.transform(mesh),\n\t\t\tget material(){return{\n\t\t\t\tget mode(){return material},\n\t\t\t\tset mode(mode){material=mode;mesh.material=materials[mode]},\n\t\t\t\tmodes:materials,\n\t\t\t}},\n\t\t\tget texture(){return texture},\n\t\t\tset texture(value)\n\t\t\t{\n\t\t\t\ttexture=value;\n\t\t\t\tconst map=textures[texture]||textures.default\n\t\t\t\tfor(const material of Object.values(materials))\n\t\t\t\t{\n\t\t\t\t\tmaterial.map=map\n\t\t\t\t}\n\t\t\t},\n\t\t\tget geometry(){return geometry},\n\t\t\tset geometry(value)\n\t\t\t{\n\t\t\t\tif(value in geometries)\n\t\t\t\t\tmesh.geometry=geometries[geometry=value]\n\t\t\t\telse\n\t\t\t\t\tconsole.error('ERROR setting geometry: '+JSON.stringify(value)+' is not in geometries. ')\n\t\t\t},\n\t\t\tget threeObject() {return mesh },\n\t\t\tset parent(itemID)\n\t\t\t{\n\t\t\t\tif(parent===itemID)return\n\t\t\t\tconst item=items[itemID]\n\t\t\t\tif(item===undefined)\n\t\t\t\t\tconsole.error(repr(itemID),'is not a valid parent! (Failed to set parent of '+repr(ID)+')')\n\t\t\t\telse\n\t\t\t\t\tmesh.parent=item.threeObject//MAKE SOME ASSERTIONS HERE\n\t\t\t\tparent=itemID//Even if we did error, we're going to pretend we succedded to we don't spam the console (it would try setting that parent again and agian every frame otherwise)\n\t\t\t},\n\t\t\tget parent ( ){return parent },\n\t\t\tset visible (x){ mesh.visible =Boolean(x)},\n\t\t\tget visible ( ){return mesh.visible },\n\t\t\tset castShadow (x){ mesh.castShadow =x},\n\t\t\tget castShadow ( ){return mesh.castShadow },\n\t\t\tset receiveShadow(x){ mesh.receiveShadow=x},\n\t\t\tget receiveShadow( ){return mesh.receiveShadow },\n\t\t}\n\t\tmesh.userData.item=item//This is to let click events access this item's ID, which have to originate in the threeObject\n\t\treturn item\n\t}", "makeGrid() {\n\t\tlet positions = [];\n\t\tlet normals = [];\n\t\tlet length = 1000;\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tpositions.push(-(length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0 - i); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\n\t\t\tpositions.push((length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0 - i); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\t\t}\n\n\t\tfor (let i = 0; i < length; i++) {\n\t\t\tpositions.push(i - (length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push((length - 1.0) / 2.0); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\n\t\t\tpositions.push(i - (length - 1.0) / 2.0); // x\n\t\t\tpositions.push(0.0); // y\n\t\t\tpositions.push(-(length - 1.0) / 2.0); // z\n\n\t\t\tnormals.push(0);\n\t\t\tnormals.push(1);\n\t\t\tnormals.push(0);\n\t\t}\n\n\t\tlet plane = new Object3d();\n\t\tlet params = gAssetManager.makeModelParams();\n\t\tparams.positions = positions;\n\t\tparams.normals = normals;\n\t\tlet indexBuffer = [];\n\t\tfor (let i = 0; i < 4 * length; i++) indexBuffer.push(i);\n\t\tplane.setModel(\n\t\t\tgAssetManager.makeModelData(params, indexBuffer, \"LINES\")\n\t\t);\n\t\tplane.setMaterial(new DefaultMaterial([0.5, 0.3, 0.5]));\n\n\t\treturn plane;\n\t}", "function paper2matter(paperpath) {\r\n\tvar pp;\r\n\r\n\tif(paperpath._class == \"CompoundPath\"){\r\n\t\tpp = paperpath.children[0].clone();\r\n\t}else{\r\n\t\tpp = paperpath.clone();\r\n\t}\r\n\t//paperpath.simplify(1);\r\n\tpp.flatten(4);\r\n\tvar points = [];\r\n\tfor(var i = 0; i<pp.segments.length; i++){\r\n\t\tvar p = pp.segments[i].point;\r\n\t\tvar vert = {\r\n\t\t\tx: p.x,\r\n\t\t\ty: p.y\r\n\t\t};\r\n\t\tpoints.push(vert);\r\n\t}\r\n\tpp.remove();\r\n\treturn points;\r\n}", "function path(d) {\n //return line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; }));\n return line(dimensions.map(function(dimension) {\n var v = dragging[dimension.name];\n var tx = v == null ? x(dimension.name) : v;\n // if (dimension.name == \"Country\") {\n // console.log(dimension.scale(d[dimension.name]));\n // }\n return [tx, dimension.scale(d[dimension.name])];\n }));\n }", "function createDirectionMatrix3() {\n\t/*\n\t\t8 1 2\n\t\t7 0 3\n\t\t6 5 4\n\t*/\n\tvar M = [\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t\t[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,],\n\t];\n\treturn M;\n}", "constructor({ width = 1.0, height = 1.0, length = 1.0 }) {\n super();\n /* Points 0, 1, 2, 3 are on the left.\n * Points 4, 5, 6, 7 are on the right.\n * x = width, y = length, z = height*/\n const topLeftOut = [(width / 2), 0, (height / 2)];\n const botLeftOut = [(width / 2), 0, -(height / 2)];\n const topLeftIn = [-(width / 2), 0, (height / 2)];\n const botLeftIn = [-(width / 2), 0, -(height / 2)];\n const topRightOut = [(width / 2), length, (height / 2)];\n const botRightOut = [(width / 2), length, -(height / 2)];\n const topRightIn = [-(width / 2), length, (height / 2)];\n const botRightIn = [-(width / 2), length, -(height / 2)];\n this.vertices.push(topLeftOut);\n this.vertices.push(botLeftOut);\n this.vertices.push(topLeftIn);\n this.vertices.push(botLeftIn);\n this.vertices.push(topRightOut);\n this.vertices.push(botRightOut);\n this.vertices.push(topRightIn);\n this.vertices.push(botRightIn);\n\n // Left side face\n this.triangles.push([0, 1, 2]);\n this.triangles.push([2, 3, 1]);\n // Back side face\n this.triangles.push([2, 3, 6]);\n this.triangles.push([3, 6, 7]);\n // Right side face\n this.triangles.push([4, 5, 6]);\n this.triangles.push([5, 6, 7]);\n // Bottom face\n this.triangles.push([3, 5, 1]);\n this.triangles.push([5, 6, 3]);\n // Front side face\n this.triangles.push([1, 5, 4]);\n this.triangles.push([0, 1, 4]);\n // Top face\n this.triangles.push([0, 2, 4]);\n this.triangles.push([2, 4, 6]);\n }", "polygonize(isolevel) {\n\n var vertPositions = [];\n var vertNormals = [];\n\n var cubeindex = 0;\n if (this.grid[0].isovalue < isolevel) cubeindex |= 1;\n if (this.grid[1].isovalue < isolevel) cubeindex |= 2;\n if (this.grid[2].isovalue < isolevel) cubeindex |= 4;\n if (this.grid[3].isovalue < isolevel) cubeindex |= 8;\n if (this.grid[4].isovalue < isolevel) cubeindex |= 16;\n if (this.grid[5].isovalue < isolevel) cubeindex |= 32;\n if (this.grid[6].isovalue < isolevel) cubeindex |= 64;\n if (this.grid[7].isovalue < isolevel) cubeindex |= 128;\n\n if (LUT.EDGE_TABLE[cubeindex] == 0) {\n return {\n cubeIndex: cubeindex,\n vertPositions: vertPositions,\n vertNormals: vertNormals\n };\n }\n\n var lerp;\n if (LUT.EDGE_TABLE[cubeindex] & 1) { // is truthy\n lerp = this.vertexInterpolation(isolevel, this.grid[0], this.grid[1]);\n vertPositions[0] = lerp.pos;\n vertNormals[0] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 2) {\n lerp = this.vertexInterpolation(isolevel, this.grid[1], this.grid[2]);\n vertPositions[1] = lerp.pos;\n vertNormals[1] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 4) {\n lerp = this.vertexInterpolation(isolevel, this.grid[2], this.grid[3]);\n vertPositions[2] = lerp.pos;\n vertNormals[2] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 8) {\n lerp = this.vertexInterpolation(isolevel, this.grid[3], this.grid[0]);\n vertPositions[3] = lerp.pos;\n vertNormals[3] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 16) {\n lerp = this.vertexInterpolation(isolevel, this.grid[4], this.grid[5]);\n vertPositions[4] = lerp.pos;\n vertNormals[4] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 32) {\n lerp = this.vertexInterpolation(isolevel, this.grid[5], this.grid[6]);\n vertPositions[5] = lerp.pos;\n vertNormals[5] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 64) {\n lerp = this.vertexInterpolation(isolevel, this.grid[6], this.grid[7]);\n vertPositions[6] = lerp.pos;\n vertNormals[6] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 128) {\n lerp = this.vertexInterpolation(isolevel, this.grid[7], this.grid[4]);\n vertPositions[7] = lerp.pos;\n vertNormals[7] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 256) {\n lerp = this.vertexInterpolation(isolevel, this.grid[0], this.grid[4]);\n vertPositions[8] = lerp.pos;\n vertNormals[8] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 512) {\n lerp = this.vertexInterpolation(isolevel, this.grid[1], this.grid[5]);\n vertPositions[9] = lerp.pos;\n vertNormals[9] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 1024) {\n lerp = this.vertexInterpolation(isolevel, this.grid[2], this.grid[6]);\n vertPositions[10] = lerp.pos;\n vertNormals[10] = lerp.normal;\n }\n\n if (LUT.EDGE_TABLE[cubeindex] & 2048) {\n lerp = this.vertexInterpolation(isolevel, this.grid[3], this.grid[7]);\n vertPositions[11] = lerp.pos;\n vertNormals[11] = lerp.normal;\n }\n\n return {\n cubeIndex: cubeindex,\n vertPositions: vertPositions,\n vertNormals: vertNormals\n };\n }", "indexVertices() {\n\t\tlet vertices = geometry.mesh.vertices;\n\t\tthis.nV = vertices.length;\n\t\tthis.nI = 0;\n\t\tthis.nB = 0;\n\t\tthis.vertexIndex = {};\n\t\tthis.bVertexIndex = {};\n\n\t\t// count interior vertices and map them to a unique index\n\t\tfor (let v of vertices) {\n\t\t\tif (!v.onBoundary()) {\n\t\t\t\tthis.vertexIndex[v] = this.nI;\n\t\t\t\tthis.nI++;\n\t\t\t}\n\t\t}\n\n\t\t// count boundary vertices and map them to unique indices\n\t\tfor (let v of vertices) {\n\t\t\tif (v.onBoundary()) {\n\t\t\t\tthis.bVertexIndex[v] = this.nB;\n\t\t\t\tthis.vertexIndex[v] = this.nI + this.nB;\n\t\t\t\tthis.nB++;\n\t\t\t}\n\t\t}\n\t}", "function parallelPath(d) {\n return parallelLine(dimensions.map(function (p) { return [parallelPosition(p), parallelY[p](d[p])]; }));\n}", "function mapPath(wire){\r\n\t// Start at origin\r\n\t\tlet x = 0;\r\n\t\tlet y = 0;\r\n\t\tlet steps = 0;\r\n\r\n\t// Create an empty array to pass back after filling\r\n\t\tvar xyArray = new Array();\r\n\t\r\n\tfor(let i=0; i<wire.length; i++){\r\n\t\tlet instruction = wire[i];\r\n\t\tlet direction = instruction.substring(0,1);\r\n\t\tlet travelDist = Number(instruction.substring(1,instruction.length));\r\n\r\n\t\t\tswitch(direction){\r\n\t\t\t\tcase \"R\":\r\n\t\t\t\t\t//Moving X in a positive direction, but Y remains the same...\r\n\t\t\t\t\tfor(let z=0; z<travelDist; z++){\r\n\t\t\t\t\t\tx = x+1;\r\n\t\t\t\t\t\tsteps++;\r\n\t\t\t\t\t\txyArray.push(x + \",\" + y + \",\" + steps);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"L\":\r\n\t\t\t\t\t//Moving X in a negative direction, but Y remains the same.\r\n\t\t\t\t\tfor(let z=0; z<travelDist; z++){\r\n\t\t\t\t\t\tx = x-1;\r\n\t\t\t\t\t\tsteps++;\r\n\t\t\t\t\t\txyArray.push(x + \",\" + y + \",\" + steps);\r\n\t\t\t\t\t}\t\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"U\":\r\n\t\t\t\t\t//Moving Y in a postive direction, but X stays the same.\r\n\t\t\t\t\tfor(let z=0; z<travelDist; z++){\r\n\t\t\t\t\t\ty = y+1;\r\n\t\t\t\t\t\tsteps++;\r\n\t\t\t\t\t\txyArray.push(x + \",\" + y + \",\" + steps);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase \"D\":\r\n\t\t\t\t\t//Moving Y in a negative direction, but X stays the same.\r\n\t\t\t\t\tfor(let z=0; z<travelDist; z++){\r\n\t\t\t\t\t\ty = y-1;\r\n\t\t\t\t\t\tsteps++;\r\n\t\t\t\t\t\txyArray.push(x + \",\" + y + \",\" + steps);\r\n\t\t\t\t\t}\t\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tconsole.log(\"Should never be here....!!!!!\");\r\n\t\t\t}\r\n\r\n\t}\r\n\t\r\n\treturn xyArray;\r\n\t\r\n}", "function PathMap() {\n /**\n * Contains a map of path elements\n *\n * <h1>Path definition</h1>\n * A parameterized path is defined like this:\n * <pre>\n * 'GATEWAY_PARALLEL': {\n * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n * height: 17.5,\n * width: 17.5,\n * heightElements: [2.5, 7.5],\n * widthElements: [2.5, 7.5]\n * }\n * </pre>\n * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling\n * is based on the ratio between the specified height and width in this object and the\n * height and width that is set as scale target (Note x,y coordinates will be scaled with\n * individual ratios).</p>\n * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.\n * The scaling is based on the computed ratios.\n * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using\n * the computed ratio coefficient.\n * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.\n * <ul>\n * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>\n * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>\n * </ul>\n * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.\n * </p>\n */\n this.pathMap = {\n 'EVENT_MESSAGE': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 36,\n width: 36,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'EVENT_SIGNAL': {\n d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x1},0 Z',\n height: 36,\n width: 36,\n heightElements: [18],\n widthElements: [10, 20]\n },\n 'EVENT_ESCALATION': {\n d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x0},-{e.y1} l -{e.x0},{e.y1} Z',\n height: 36,\n width: 36,\n heightElements: [20, 7],\n widthElements: [8]\n },\n 'EVENT_CONDITIONAL': {\n d: 'M {e.x0},{e.y0} l {e.x1},0 l 0,{e.y2} l -{e.x1},0 Z ' +\n 'M {e.x2},{e.y3} l {e.x0},0 ' +\n 'M {e.x2},{e.y4} l {e.x0},0 ' +\n 'M {e.x2},{e.y5} l {e.x0},0 ' +\n 'M {e.x2},{e.y6} l {e.x0},0 ' +\n 'M {e.x2},{e.y7} l {e.x0},0 ' +\n 'M {e.x2},{e.y8} l {e.x0},0 ',\n height: 36,\n width: 36,\n heightElements: [8.5, 14.5, 18, 11.5, 14.5, 17.5, 20.5, 23.5, 26.5],\n widthElements: [10.5, 14.5, 12.5]\n },\n 'EVENT_LINK': {\n d: 'm {mx},{my} 0,{e.y0} -{e.x1},0 0,{e.y1} {e.x1},0 0,{e.y0} {e.x0},-{e.y2} -{e.x0},-{e.y2} z',\n height: 36,\n width: 36,\n heightElements: [4.4375, 6.75, 7.8125],\n widthElements: [9.84375, 13.5]\n },\n 'EVENT_ERROR': {\n d: 'm {mx},{my} {e.x0},-{e.y0} {e.x1},-{e.y1} {e.x2},{e.y2} {e.x3},-{e.y3} -{e.x4},{e.y4} -{e.x5},-{e.y5} z',\n height: 36,\n width: 36,\n heightElements: [0.023, 8.737, 8.151, 16.564, 10.591, 8.714],\n widthElements: [0.085, 6.672, 6.97, 4.273, 5.337, 6.636]\n },\n 'EVENT_CANCEL_45': {\n d: 'm {mx},{my} -{e.x1},0 0,{e.x0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 36,\n width: 36,\n heightElements: [4.75, 8.5],\n widthElements: [4.75, 8.5]\n },\n 'EVENT_COMPENSATION': {\n d: 'm {mx},{my} {e.x0},-{e.y0} 0,{e.y1} z m {e.x1},-{e.y2} {e.x2},-{e.y3} 0,{e.y1} -{e.x2},-{e.y3} z',\n height: 36,\n width: 36,\n heightElements: [6.5, 13, 0.4, 6.1],\n widthElements: [9, 9.3, 8.7]\n },\n 'EVENT_TIMER_WH': {\n d: 'M {mx},{my} l {e.x0},-{e.y0} m -{e.x0},{e.y0} l {e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 2],\n widthElements: [3, 7]\n },\n 'EVENT_TIMER_LINE': {\n d: 'M {mx},{my} ' +\n 'm {e.x0},{e.y0} l -{e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 3],\n widthElements: [0, 0]\n },\n 'EVENT_MULTIPLE': {\n d: 'm {mx},{my} {e.x1},-{e.y0} {e.x1},{e.y0} -{e.x0},{e.y1} -{e.x2},0 z',\n height: 36,\n width: 36,\n heightElements: [6.28099, 12.56199],\n widthElements: [3.1405, 9.42149, 12.56198]\n },\n 'EVENT_PARALLEL_MULTIPLE': {\n d: 'm {mx},{my} {e.x0},0 0,{e.y1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n height: 36,\n width: 36,\n heightElements: [2.56228, 7.68683],\n widthElements: [2.56228, 7.68683]\n },\n 'GATEWAY_EXCLUSIVE': {\n d: 'm {mx},{my} {e.x0},{e.y0} {e.x1},{e.y0} {e.x2},0 {e.x4},{e.y2} ' +\n '{e.x4},{e.y1} {e.x2},0 {e.x1},{e.y3} {e.x0},{e.y3} ' +\n '{e.x3},0 {e.x5},{e.y1} {e.x5},{e.y2} {e.x3},0 z',\n height: 17.5,\n width: 17.5,\n heightElements: [8.5, 6.5312, -6.5312, -8.5],\n widthElements: [6.5, -6.5, 3, -3, 5, -5]\n },\n 'GATEWAY_PARALLEL': {\n d: 'm {mx},{my} 0,{e.y1} -{e.x1},0 0,{e.y0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 30,\n width: 30,\n heightElements: [5, 12.5],\n widthElements: [5, 12.5]\n },\n 'GATEWAY_EVENT_BASED': {\n d: 'm {mx},{my} {e.x0},{e.y0} {e.x0},{e.y1} {e.x1},{e.y2} {e.x2},0 z',\n height: 11,\n width: 11,\n heightElements: [-6, 6, 12, -12],\n widthElements: [9, -3, -12]\n },\n 'GATEWAY_COMPLEX': {\n d: 'm {mx},{my} 0,{e.y0} -{e.x0},-{e.y1} -{e.x1},{e.y2} {e.x0},{e.y1} -{e.x2},0 0,{e.y3} ' +\n '{e.x2},0 -{e.x0},{e.y1} l {e.x1},{e.y2} {e.x0},-{e.y1} 0,{e.y0} {e.x3},0 0,-{e.y0} {e.x0},{e.y1} ' +\n '{e.x1},-{e.y2} -{e.x0},-{e.y1} {e.x2},0 0,-{e.y3} -{e.x2},0 {e.x0},-{e.y1} -{e.x1},-{e.y2} ' +\n '-{e.x0},{e.y1} 0,-{e.y0} -{e.x3},0 z',\n height: 17.125,\n width: 17.125,\n heightElements: [4.875, 3.4375, 2.125, 3],\n widthElements: [3.4375, 2.125, 4.875, 3]\n },\n 'DATA_OBJECT_PATH': {\n d: 'm 0,0 {e.x1},0 {e.x0},{e.y0} 0,{e.y1} -{e.x2},0 0,-{e.y2} {e.x1},0 0,{e.y0} {e.x0},0',\n height: 61,\n width: 51,\n heightElements: [10, 50, 60],\n widthElements: [10, 40, 50, 60]\n },\n 'DATA_OBJECT_COLLECTION_PATH': {\n d: 'm {mx}, {my} ' +\n 'm 0 15 l 0 -15 ' +\n 'm 4 15 l 0 -15 ' +\n 'm 4 15 l 0 -15 ',\n height: 61,\n width: 51,\n heightElements: [12],\n widthElements: [1, 6, 12, 15]\n },\n 'DATA_ARROW': {\n d: 'm 5,9 9,0 0,-3 5,5 -5,5 0,-3 -9,0 z',\n height: 61,\n width: 51,\n heightElements: [],\n widthElements: []\n },\n 'DATA_STORE': {\n d: 'm {mx},{my} ' +\n 'l 0,{e.y2} ' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'l 0,-{e.y2} ' +\n 'c -{e.x0},-{e.y1} -{e.x1},-{e.y1} -{e.x2},0' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0',\n height: 61,\n width: 61,\n heightElements: [7, 10, 45],\n widthElements: [2, 58, 60]\n },\n 'TEXT_ANNOTATION': {\n d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',\n height: 30,\n width: 10,\n heightElements: [30],\n widthElements: [10]\n },\n 'MARKER_SUB_PROCESS': {\n d: 'm{mx},{my} m 7,2 l 0,10 m -5,-5 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_PARALLEL': {\n d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_SEQUENTIAL': {\n d: 'm{mx},{my} m 0,3 l 10,0 m -10,3 l 10,0 m -10,3 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_COMPENSATION': {\n d: 'm {mx},{my} 7,-5 0,10 z m 7.1,-0.3 6.9,-4.7 0,10 -6.9,-4.7 z',\n height: 10,\n width: 21,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_LOOP': {\n d: 'm {mx},{my} c 3.526979,0 6.386161,-2.829858 6.386161,-6.320661 0,-3.490806 -2.859182,-6.320661 ' +\n '-6.386161,-6.320661 -3.526978,0 -6.38616,2.829855 -6.38616,6.320661 0,1.745402 ' +\n '0.714797,3.325567 1.870463,4.469381 0.577834,0.571908 1.265885,1.034728 2.029916,1.35457 ' +\n 'l -0.718163,-3.909793 m 0.718163,3.909793 -3.885211,0.802902',\n height: 13.9,\n width: 13.7,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_ADHOC': {\n d: 'm {mx},{my} m 0.84461,2.64411 c 1.05533,-1.23780996 2.64337,-2.07882 4.29653,-1.97997996 2.05163,0.0805 ' +\n '3.85579,1.15803 5.76082,1.79107 1.06385,0.34139996 2.24454,0.1438 3.18759,-0.43767 0.61743,-0.33642 ' +\n '1.2775,-0.64078 1.7542,-1.17511 0,0.56023 0,1.12046 0,1.6807 -0.98706,0.96237996 -2.29792,1.62393996 ' +\n '-3.6918,1.66181996 -1.24459,0.0927 -2.46671,-0.2491 -3.59505,-0.74812 -1.35789,-0.55965 ' +\n '-2.75133,-1.33436996 -4.27027,-1.18121996 -1.37741,0.14601 -2.41842,1.13685996 -3.44288,1.96782996 z',\n height: 4,\n width: 15,\n heightElements: [],\n widthElements: []\n },\n 'TASK_TYPE_SEND': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 14,\n width: 21,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_SCRIPT': {\n d: 'm {mx},{my} c 9.966553,-6.27276 -8.000926,-7.91932 2.968968,-14.938 l -8.802728,0 ' +\n 'c -10.969894,7.01868 6.997585,8.66524 -2.968967,14.938 z ' +\n 'm -7,-12 l 5,0 ' +\n 'm -4.5,3 l 4.5,0 ' +\n 'm -3,3 l 5,0' +\n 'm -4,3 l 5,0',\n height: 15,\n width: 12.6,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_USER_1': {\n d: 'm {mx},{my} c 0.909,-0.845 1.594,-2.049 1.594,-3.385 0,-2.554 -1.805,-4.62199999 ' +\n '-4.357,-4.62199999 -2.55199998,0 -4.28799998,2.06799999 -4.28799998,4.62199999 0,1.348 ' +\n '0.974,2.562 1.89599998,3.405 -0.52899998,0.187 -5.669,2.097 -5.794,4.7560005 v 6.718 ' +\n 'h 17 v -6.718 c 0,-2.2980005 -5.5279996,-4.5950005 -6.0509996,-4.7760005 z' +\n 'm -8,6 l 0,5.5 m 11,0 l 0,-5'\n },\n 'TASK_TYPE_USER_2': {\n d: 'm {mx},{my} m 2.162,1.009 c 0,2.4470005 -2.158,4.4310005 -4.821,4.4310005 ' +\n '-2.66499998,0 -4.822,-1.981 -4.822,-4.4310005 '\n },\n 'TASK_TYPE_USER_3': {\n d: 'm {mx},{my} m -6.9,-3.80 c 0,0 2.25099998,-2.358 4.27399998,-1.177 2.024,1.181 4.221,1.537 ' +\n '4.124,0.965 -0.098,-0.57 -0.117,-3.79099999 -4.191,-4.13599999 -3.57499998,0.001 ' +\n '-4.20799998,3.36699999 -4.20699998,4.34799999 z'\n },\n 'TASK_TYPE_MANUAL': {\n d: 'm {mx},{my} c 0.234,-0.01 5.604,0.008 8.029,0.004 0.808,0 1.271,-0.172 1.417,-0.752 0.227,-0.898 ' +\n '-0.334,-1.314 -1.338,-1.316 -2.467,-0.01 -7.886,-0.004 -8.108,-0.004 -0.014,-0.079 0.016,-0.533 0,-0.61 ' +\n '0.195,-0.042 8.507,0.006 9.616,0.002 0.877,-0.007 1.35,-0.438 1.353,-1.208 0.003,-0.768 -0.479,-1.09 ' +\n '-1.35,-1.091 -2.968,-0.002 -9.619,-0.013 -9.619,-0.013 v -0.591 c 0,0 5.052,-0.016 7.225,-0.016 ' +\n '0.888,-0.002 1.354,-0.416 1.351,-1.193 -0.006,-0.761 -0.492,-1.196 -1.361,-1.196 -3.473,-0.005 ' +\n '-10.86,-0.003 -11.0829995,-0.003 -0.022,-0.047 -0.045,-0.094 -0.069,-0.139 0.3939995,-0.319 ' +\n '2.0409995,-1.626 2.4149995,-2.017 0.469,-0.4870005 0.519,-1.1650005 0.162,-1.6040005 -0.414,-0.511 ' +\n '-0.973,-0.5 -1.48,-0.236 -1.4609995,0.764 -6.5999995,3.6430005 -7.7329995,4.2710005 -0.9,0.499 ' +\n '-1.516,1.253 -1.882,2.19 -0.37000002,0.95 -0.17,2.01 -0.166,2.979 0.004,0.718 -0.27300002,1.345 ' +\n '-0.055,2.063 0.629,2.087 2.425,3.312 4.859,3.318 4.6179995,0.014 9.2379995,-0.139 13.8569995,-0.158 ' +\n '0.755,-0.004 1.171,-0.301 1.182,-1.033 0.012,-0.754 -0.423,-0.969 -1.183,-0.973 -1.778,-0.01 ' +\n '-5.824,-0.004 -6.04,-0.004 10e-4,-0.084 0.003,-0.586 10e-4,-0.67 z'\n },\n 'TASK_TYPE_INSTANTIATING_SEND': {\n d: 'm {mx},{my} l 0,8.4 l 12.6,0 l 0,-8.4 z l 6.3,3.6 l 6.3,-3.6'\n },\n 'TASK_TYPE_SERVICE': {\n d: 'm {mx},{my} v -1.71335 c 0.352326,-0.0705 0.703932,-0.17838 1.047628,-0.32133 ' +\n '0.344416,-0.14465 0.665822,-0.32133 0.966377,-0.52145 l 1.19431,1.18005 1.567487,-1.57688 ' +\n '-1.195028,-1.18014 c 0.403376,-0.61394 0.683079,-1.29908 0.825447,-2.01824 l 1.622133,-0.01 ' +\n 'v -2.2196 l -1.636514,0.01 c -0.07333,-0.35153 -0.178319,-0.70024 -0.323564,-1.04372 ' +\n '-0.145244,-0.34406 -0.321407,-0.6644 -0.522735,-0.96217 l 1.131035,-1.13631 -1.583305,-1.56293 ' +\n '-1.129598,1.13589 c -0.614052,-0.40108 -1.302883,-0.68093 -2.022633,-0.82247 l 0.0093,-1.61852 ' +\n 'h -2.241173 l 0.0042,1.63124 c -0.353763,0.0736 -0.705369,0.17977 -1.049785,0.32371 -0.344415,0.14437 ' +\n '-0.665102,0.32092 -0.9635006,0.52046 l -1.1698628,-1.15823 -1.5667691,1.5792 1.1684265,1.15669 ' +\n 'c -0.4026573,0.61283 -0.68308,1.29797 -0.8247287,2.01713 l -1.6588041,0.003 v 2.22174 ' +\n 'l 1.6724648,-0.006 c 0.073327,0.35077 0.1797598,0.70243 0.3242851,1.04472 0.1452428,0.34448 ' +\n '0.3214064,0.6644 0.5227339,0.96066 l -1.1993431,1.19723 1.5840256,1.56011 1.1964668,-1.19348 ' +\n 'c 0.6140517,0.40346 1.3028827,0.68232 2.0233517,0.82331 l 7.19e-4,1.69892 h 2.226848 z ' +\n 'm 0.221462,-3.9957 c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_SERVICE_FILL': {\n d: 'm {mx},{my} c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_HEADER': {\n d: 'm {mx},{my} 0,4 20,0 0,-4 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_MAIN': {\n d: 'm {mx},{my} 0,12 20,0 0,-12 z' +\n 'm 0,8 l 20,0 ' +\n 'm -13,-4 l 0,8'\n },\n 'MESSAGE_FLOW_MARKER': {\n d: 'm {mx},{my} m -10.5 ,-7 l 0,14 l 21,0 l 0,-14 z l 10.5,6 l 10.5,-6'\n }\n };\n this.getRawPath = function getRawPath(pathId) {\n return this.pathMap[pathId].d;\n };\n /**\n * Scales the path to the given height and width.\n * <h1>Use case</h1>\n * <p>Use case is to scale the content of elements (event, gateways) based\n * on the element bounding box's size.\n * </p>\n * <h1>Why not transform</h1>\n * <p>Scaling a path with transform() will also scale the stroke and IE does not support\n * the option 'non-scaling-stroke' to prevent this.\n * Also there are use cases where only some parts of a path should be\n * scaled.</p>\n *\n * @param {String} pathId The ID of the path.\n * @param {Object} param <p>\n * Example param object scales the path to 60% size of the container (data.width, data.height).\n * <pre>\n * {\n * xScaleFactor: 0.6,\n * yScaleFactor:0.6,\n * containerWidth: data.width,\n * containerHeight: data.height,\n * position: {\n * mx: 0.46,\n * my: 0.2,\n * }\n * }\n * </pre>\n * <ul>\n * <li>targetpathwidth = xScaleFactor * containerWidth</li>\n * <li>targetpathheight = yScaleFactor * containerHeight</li>\n * <li>Position is used to set the starting coordinate of the path. M is computed:\n * <ul>\n * <li>position.x * containerWidth</li>\n * <li>position.y * containerHeight</li>\n * </ul>\n * Center of the container <pre> position: {\n * mx: 0.5,\n * my: 0.5,\n * }</pre>\n * Upper left corner of the container\n * <pre> position: {\n * mx: 0.0,\n * my: 0.0,\n * }</pre>\n * </li>\n * </ul>\n * </p>\n *\n */\n this.getScaledPath = function getScaledPath(pathId, param) {\n var rawPath = this.pathMap[pathId];\n // positioning\n // compute the start point of the path\n var mx, my;\n if (param.abspos) {\n mx = param.abspos.x;\n my = param.abspos.y;\n }\n else {\n mx = param.containerWidth * param.position.mx;\n my = param.containerHeight * param.position.my;\n }\n var coordinates = {}; // map for the scaled coordinates\n if (param.position) {\n // path\n var heightRatio = (param.containerHeight / rawPath.height) * param.yScaleFactor;\n var widthRatio = (param.containerWidth / rawPath.width) * param.xScaleFactor;\n // Apply height ratio\n for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {\n coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;\n }\n // Apply width ratio\n for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {\n coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;\n }\n }\n // Apply value to raw path\n var path = format(rawPath.d, {\n mx: mx,\n my: my,\n e: coordinates\n });\n return path;\n };\n}", "function Unwrapper( mesh, options )\r\n{\r\n\tvar verticesBuffer = mesh.vertexBuffers[\"vertices\"];\r\n\tvar indicesBuffer = mesh.indexBuffers[\"triangles\"];\r\n\r\n\tif(!indices)\r\n\t{\r\n\t\tconsole.error(\"Only can generate UVs from indexed meshes\");\r\n\t\treturn false;\r\n\t}\r\n\r\n\tvar vertices = verticesBuffer.data;\r\n\tvar indices = IndicesBuffer.data;\r\n\tvar num_triangles = indices.length / 3;\r\n\r\n\t//triplanar separation *********************\r\n\tvar blocks = [];\r\n\tfor(var i = 0; i < 6; ++i)\r\n\t\tblocks[i] = new Unwrapper.Block();\r\n\r\n\tvar AB = vec3.create();\r\n\tvar BC = vec3.create();\r\n\tvar CA = vec3.create();\r\n\tvar N = vec3.create();\r\n\r\n\t//blocks: 0:+X, 1:-X, 2:+Y, 3:-Y, 4:+Z, 5:-Z\r\n\tvar BVs = new Float32Array(6);\r\n\tvar chart_candidates = Array(3);\r\n\r\n\t//for every triangle add it to a chart in a block\r\n\tfor(var i = 0; i < num_triangles; ++i)\r\n\t{\r\n\t\tvar Ai = indices[i*3];\r\n\t\tvar Bi = indices[i*3+1];\r\n\t\tvar Ci = indices[i*3+2];\r\n\r\n\t\tvar A = vertices.subarray( Ai, Ai + 3 );\r\n\t\tvar B = vertices.subarray( Bi, Bi + 3 );\r\n\t\tvar C = vertices.subarray( Ci, Ci + 3 );\r\n\r\n\t\tvec3.sub( AB, B, A );\r\n\t\tvec3.sub( BC, B, C );\r\n\t\tvec3.sub( CA, A, C );\r\n\r\n\t\t//compute normal\r\n\t\tvec3.cross( N, AB, CA ); //we should us AC but doesnt matter, we will fix it\r\n\t\tvar len = vec3.length( N );\r\n\t\tvec3.scale( N, N, -len ); //reverse and normalize\r\n\r\n\t\t//compute which block belongs\r\n\t\tvar max = -2; var block_id = -1;\r\n\t\tBVs[0] = N[0]; BVs[1] = N[1]; BVs[2] = N[2];\r\n\t\tBVs[3] = -N[0]; BVs[4] = -N[1]; BVs[5] = -N[2];\r\n\t\tfor(var j = 0; j < 6; ++j)\r\n\t\t{\r\n\t\t\tif(BVs[j] < max)\r\n\t\t\t\tcontinue;\r\n\t\t\tblock_id = j;\r\n\t\t\tmax = BVs[j];\r\n\t\t}\r\n\r\n\t\t//get block\r\n\t\tvar block = blocks[ block_id ];\r\n\r\n\t\t//search for chart\r\n\t\tvar ABname = Ai + \",\" + Bi;\r\n\t\tvar BCname = Bi + \",\" + Ci;\r\n\t\tvar CAname = Ci + \",\" + Ai;\r\n\r\n\t\tchart = block.by_edge[ ABname ];\r\n\t\tchart_candidates[0] = block.by_edge[ ABname ];\r\n\t\tchart_candidates[1] = block.by_edge[ BCname ];\r\n\t\tchart_candidates[2] = block.by_edge[ CAname ];\r\n\r\n\t\tif( chart_candidates[0] && chart_candidates[1] && chart_candidates[0] != chart_candidates[1] )\r\n\t\t{\r\n\t\t\tchart_candidates[0].mergeWith( chart_candidates[1] );\r\n\t\t\tblock.removeChart( chart_candidates[1] );\r\n\t\t\tchart_candidates[1] = null;\r\n\t\t}\r\n\r\n\t\tif( chart_candidates[0] && chart_candidates[2] && chart_candidates[0] != chart_candidates[2] )\r\n\t\t{\r\n\t\t\tchart_candidates[0].mergeWith( chart_candidates[2] );\r\n\t\t\tblock.removeChart( chart_candidates[2] );\r\n\t\t\tchart_candidates[2] = null;\r\n\t\t}\r\n\r\n\t\tif( chart_candidates[1] && chart_candidates[2] && chart_candidates[1] != chart_candidates[2] )\r\n\t\t{\r\n\t\t\tchart_candidates[1].mergeWith( chart_candidates[2] );\r\n\t\t\tblock.removeChart( chart_candidates[2] );\r\n\t\t\tchart_candidates[2] = null;\r\n\t\t}\r\n\r\n\t\tvar final_chart = chart_candidates[0] || chart_candidates[1] || chart_candidates[2];\r\n\r\n\t\tif( !final_chart )\r\n\t\t{\r\n\t\t\tfinal_chart = new Unwrapper.Chart();\r\n\t\t\tblock.addChart( final_chart );\r\n\t\t}\r\n\r\n\t\t//add triangle to chart\r\n\t\tfinal_chart.addTriangle( A,B,C );\r\n\t}\r\n\r\n\t//put all charts together\r\n\tvar final_chart_list = [];\r\n\tfor(var i = 0; i < blocks.length; ++i)\r\n\t{\r\n\t\tvar block = blocks[i];\r\n\t\tif(block)\r\n\t\t\tfinal_chart_list = final_chart_list.concat( block.charts );\r\n\t}\r\n\r\n\t//compute bounding and area of every chart\r\n\tvar total_area = 0;\r\n\tfor(var i = 0; i < final_chart_list.length; ++i)\r\n\t{\r\n\t\tvar chart = final_chart_list[i];\r\n\t\tchart.computeInfo();\r\n\t\ttotal_area += chart.area;\r\n\t}\r\n\r\n\t//arrange charts from big to small\r\n\tfinal_chart_list.sort( function ( A, B ) { return A.area - B.area; } );\r\n\r\n\t//compute best possible area size\r\n\tvar area_size = Math.sqrt( total_area );\r\n\tfor(var i = 0; i < final_chart_list.length; ++i)\r\n\t{\r\n\t\tvar chart = final_chart_list[i];\r\n\t\tif(area_size < chart.width)\r\n\t\t\tarea_size = chart.width;\r\n\t\tif(area_size < chart.height)\r\n\t\t\tarea_size = chart.height;\r\n\t}\r\n\r\n\tvar root = { x:0, y: 0, width: area_size, height: area_size };\r\n\r\n\t//for every Chart\r\n\t\t//check in which region belongs\r\n\t\t\t//add it to the smallest where it fits\r\n\t\t\t//subdivide\r\n\t\t//no region found, increase size and restart\r\n}", "function render3d() {\n\n createBezierCurves();\n\n // create all models\n var models = [];\n curves.forEach((c)=>{\n models.push(new BezierModel(c.vertices));\n });\n points = [];\n normals = [];\n colors = [];\n texCoordsArray = [];\n // build the main object\n buildObjects({objects:models});\n\n // load colors, points, and normals to buffer\n loadVertices(program);\n loadColors(program);\n loadNormals(program);\n loadTextureArray(program);\n\n}", "function renderPath(path, lineWidth, materials, alphaMap){\n var geometry = new THREE.Geometry();\n geometry.vertices = path;\n var line = new MeshLine();\n line.setGeometry(geometry);\n // jedes MeshLineMaterial unterscheidet sich nur anhand seiner lineWidth\n // wegen Performance: erzeuge je lineWidth bzw. Blitz-Zweig-Level genau 1 Material\n if((lineWidth in materials) === false){\n materials[lineWidth] = new MeshLineMaterial({\n lineWidth: lineWidth,\n //alphaTest: true,\n depthTest: false,\n transparent: true,\n useAlphaMap: 1,\n alphaMap: alphaMap,\n //repeat: new THREE.Vector2(1,1),\n //blending: THREE.AdditiveBlending,\n opacity: 1,\n color: new THREE.Color(0xffffff)\n });\n }\n return new THREE.Mesh(line.geometry, materials[lineWidth]); \n}", "function path(d) {\n\n \t\treturn line(dimensions.map(function(p) { return [position(p), y[p](d[p])]; }));\n\t}", "function fbx_mesh()\n{\n\tthis.id;\n\tthis.model_id;\n\tthis.vertices = new Array();\n\tthis.polygons = new Array();\n\tthis.uvs = new Array();\n\tthis.color = new v4(1.0,1.0,1.0,1.0);\n\tthis.locTrans = new v3(0,0,0);\n\tthis.locRot = new v3(0,0,0);\n\tthis.locScale = new v3(1,1,1);\n\tthis.vertexPosBuffer;\n\tthis.vertexColBuffer;\n\tthis.vertexNormBuffer;\n\tthis.vertexUVBuffer;\n\tthis.material;\n}", "generateTriangles()\n{\n //Your code here\n var dx = (this.maxX - this.minX) / this.div;\n var dy = (this.maxY - this.minY) / this.div;\n \n // Push vertex buffer\n for(var i = 0; i <= this.div; i ++)\n for(var j = 0; j <= this.div; j ++){\n this.vBuffer.push(this.minX + dx * j);\n this.vBuffer.push(this.minY + dy * i);\n this.vBuffer.push(0);\n }\n // Set Normal Buffer\n for(var i = 0; i <= this.div; i ++)\n for(var j = 0; j <= this.div; j ++){\n this.nBuffer.push(0);\n this.nBuffer.push(0);\n this.nBuffer.push(0);\n }\n for(var i = 0; i < this.div; i ++)\n for(var j = 0; j < this.div; j ++){\n \n // Revised div\n var rdiv = this.div + 1;\n // Revised vindex\n var vindex = i * rdiv + j;\n \n\n this.fBuffer.push(vindex);\n this.fBuffer.push(vindex + 1);\n this.fBuffer.push(vindex + rdiv);\n\n this.fBuffer.push(vindex + 1);\n this.fBuffer.push( vindex + 1 + rdiv );\n this.fBuffer.push( vindex + rdiv );\n\n }\n this.numVertices = this.vBuffer.length/3;\n this.numFaces = this.fBuffer.length/3;\n}", "VertexInterp(p1, p2){\n\n var ret = [];\n\n ret[0] = (p1[0]+ p2[0])/2\n ret[1] = (p1[1]+p2[1])/2\n ret[2] = (p1[2]+p2[2])/2\n\n return ret;\n}", "function Sphere( radius, segmentsY, segmentsX ) {\n Drawable.call( this );\n radius = radius || 1;\n\n segmentsY = segmentsY || 10;\n segmentsX = segmentsX || segmentsY;\n\n var R = radius;\n var p = segmentsY;\n var m = segmentsX;\n\n var model = {\n vertices: [],\n indices: []\n };\n \n var prev = function( x, m ) {\n if ( x === 0 ) {\n return ( m - 1 );\n }\n else {\n return ( x -1 );\n }\n };\n \n var y, x, z, r,cnt = 0, cnt2 = 0;\n for ( var i = 1; i < p-1; i++ ) { // end points are missing\n y = R*Math.sin( -Math.PI/2 + i*Math.PI/( p - 1 ) );\n r = R*Math.cos( -Math.PI/2 + i*Math.PI/( p - 1 ) );\n //console.log( \"y , r \" ,y, r );\n for ( var k = 0; k < m; k++ ) {\n x = r*Math.cos( 2*Math.PI*k/ m );\n z = r*Math.sin( 2*Math.PI*k/ m );\n //console.log( x, z );\n model.vertices[ cnt ] = x;\n model.vertices[ cnt+1 ] = y;\n model.vertices[ cnt+2 ] = z;\n cnt = cnt+3;\n }\n //make the triangle\n \n \n if ( i > 1 ) {\n var st = ( i - 2 )*m;\n for ( x = 0; x < m; x++ ) {\n model.indices[ cnt2 ] = st + x;\n model.indices[ cnt2+1 ] = st + prev( x, m ) + m;\n model.indices[ cnt2+2 ] = st + x + m;\n cnt2 += 3;\n \n model.indices[ cnt2 ] = st + x;\n model.indices[ cnt2+1 ] = st + prev( x, m );\n model.indices[ cnt2+2 ] = st + prev( x, m ) + m;\n cnt2 += 3;\n }\n }\n }\n \n model.vertices[ cnt ] = 0;\n model.vertices[ cnt+1 ] = -R;\n model.vertices[ cnt+2 ] = 0;\n var down = cnt/3;\n cnt += 3;\n model.vertices[ cnt ] = 0;\n model.vertices[ cnt+1 ] = R;\n model.vertices[ cnt+2 ] = 0;\n cnt += 3;\n \n var top = down + 1;\n for ( x = 0; x < m; x++ ) {\n model.indices[ cnt2 ] = down;\n model.indices[ cnt2+1 ] = prev( x, m );\n model.indices[ cnt2+2 ] = x;\n cnt2 += 3;\n \n model.indices[ cnt2 ] = down - m + x;\n model.indices[ cnt2+1 ] = down - m + prev( x, m );\n model.indices[ cnt2+2 ] = top;\n cnt2 +=3;\n }\n\n\n\n var vertices = new Buffer().setData( model.vertices );\n// uvcoords = new Buffer().setData( ret.uvcoords );\n// normals = new Buffer().setData( ret.normals );\n\n vertices = new VertexAttribute( 'Position' ).setBuffer( vertices );\n// uvcoords = new VertexAttribute( 'UVCoord' ).setBuffer( uvcoords ).setSize( 2 );\n// normals = new VertexAttribute( 'Normal' ).setBuffer( normals );\n\n var indices = new Buffer( Buffer.ELEMENT_BUFFER ).setData( model.indices );\n\n m = new Mesh();\n m.setVertexAttribute( vertices );\n// m.setVertexAttribute( normals );\n// m.setVertexAttribute( uvcoords );\n m.setIndexBuffer( indices );\n\n this.mesh = m;\n}", "function setPositions(orbit) {\n if(orbit === 'leo'){\n MAX_POINTS = 1000;\n positions = new Float32Array(MAX_POINTS * 3);\n\n if(path.geometry.getAttribute('position')){\n path.geometry.removeAttribute('position');\n }\n\n path.geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));\n\n pos = path.geometry.attributes.position.array;\n step = (2 * Math.PI) / (MAX_POINTS / 2);\n index = 0;\n takeoff = MAX_POINTS / 10;\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta),\n modifier = 1;\n\n if (theta < takeoff * step) {\n modifier = (Math.sqrt(theta) / Math.sqrt(takeoff * step)) * 0.2 + 0.8;\n }\n\n x = r * Math.cos(newTheta) * modifier;\n y = 0;\n z = r * Math.sin(newTheta) * modifier;\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n\n x = r * Math.cos(newTheta);\n y = 0;\n z = r * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n }else if(orbit === 'meo'){\n MAX_POINTS = 2000;\n positions = new Float32Array(MAX_POINTS * 3);\n\n if(path.geometry.getAttribute('position')){\n path.geometry.removeAttribute('position');\n }\n\n path.geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));\n\n pos = path.geometry.attributes.position.array;\n step = (2 * Math.PI) / (MAX_POINTS / 4);\n index = 0;\n takeoff = MAX_POINTS / 10;\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta),\n modifier = 1;\n\n if (theta < takeoff * step) {\n modifier = (Math.sqrt(theta) / Math.sqrt(takeoff * step)) * 0.2 + 0.8;\n }\n\n x = r * Math.cos(newTheta) * modifier;\n y = 0;\n z = r * Math.sin(newTheta) * modifier;\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n\n x = r * Math.cos(newTheta);\n y = 0;\n z = r * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n let ellipseModifier = 1;\n\n if(theta > 1.5 * Math.PI){\n ellipseModifier = 1.5;\n }\n\n x = r * ellipseModifier * Math.cos(newTheta);\n y = 0;\n z = r * 1.5 * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n\n x = r * 1.5 * Math.cos(newTheta);\n y = 0;\n z = r * 1.5 * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n }else if(orbit === 'heo'){\n MAX_POINTS = 2000;\n positions = new Float32Array(MAX_POINTS * 3);\n\n if(path.geometry.getAttribute('position')){\n path.geometry.removeAttribute('position');\n }\n\n path.geometry.addAttribute('position', new THREE.BufferAttribute(positions, 3));\n\n pos = path.geometry.attributes.position.array;\n step = (2 * Math.PI) / (MAX_POINTS / 4);\n index = 0;\n takeoff = MAX_POINTS / 10;\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta),\n modifier = 1;\n\n if (theta < takeoff * step) {\n modifier = (Math.sqrt(theta) / Math.sqrt(takeoff * step)) * 0.2 + 0.8;\n }\n\n x = r * Math.cos(newTheta) * modifier;\n y = 0;\n z = r * Math.sin(newTheta) * modifier;\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n\n x = r * Math.cos(newTheta);\n y = 0;\n z = r * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n let ellipseModifier = 1;\n\n if(theta > 1.5 * Math.PI){\n ellipseModifier = 2;\n }\n\n x = r * ellipseModifier * Math.cos(newTheta);\n y = 0;\n z = r * 2 * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n\n for (let theta = 0; theta < 2 * Math.PI; theta += step) {\n\n let newTheta = Math.abs(2 * Math.PI - theta);\n\n x = r * 2 * Math.cos(newTheta);\n y = 0;\n z = r * 2 * Math.sin(newTheta);\n\n pos[index++] = x;\n pos[index++] = y;\n pos[index++] = z;\n }\n }\n}", "function genHelix( \n\tisTorus, \n\tgui_width, \n\tgui_height, \n\tgui_depth, \n\tgui_radius, \n\tgui_revolutions, \n\tgui_segments, \n\tgui_pathRadius, \n\tgui_pathType, \n\tgui_pathSegments, \n\tgui_cornerRadius, \n\tgui_cornerSegments )\n{\n\t//-----------------\t\n\tgui_segments = Math.round( gui_segments ); \n\tgui_pathSegments = Math.round( gui_pathSegments );\n\tgui_cornerSegments = Math.round( gui_cornerSegments );\n\t//-----------------\t\n\n\tconst indices = [], vertices = [], normals = [], uvs = [], verticesCaps = [], normalsCaps = [], uvsCaps = [];\n\tlet pathCenter = new THREE.Vector3(), cornerCenter = new THREE.Vector3();\n\tlet v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3(); // auxiliary vectors\n\tlet a, b, c, d, x, y, z, ang, lastCoord = new THREE.Vector3();\n\tlet pathRadiusLine = new THREE.Vector3(), cornerRadiusLine = new THREE.Vector3(), pathRadiusNormal = new THREE.Vector3();\n\tlet abscissa = new THREE.Vector3(), ordinate = new THREE.Vector3(), pathAxis = new THREE.Vector3(); \n\n\tconst lockRadius = true; // the same radius for width and depth ?\n\tconst minimumRadius = Math.min( gui_width, gui_depth ) / 2; // gui_radius isn't used for now.\n\tconst radiusWidth = (lockRadius ? minimumRadius : gui_width / 2) - gui_pathRadius;\n\tconst radiusDepth = (lockRadius ? minimumRadius : gui_depth / 2) - gui_pathRadius;\n\n\tconst heightTotal = gui_height - 2 * gui_pathRadius + .001; // small value added to prevent heightTotal 0 (0 means won't be drawn)\n\tconst revolutionHeight = heightTotal / gui_revolutions;\n\tconst tubeSegments = Math.ceil( gui_segments * gui_revolutions );\n\tconst heightSegment = heightTotal / tubeSegments;\n\tconst baseHeight = -heightTotal / 2;\n\n\tconst pathSegmentArc = 2 * Math.PI / gui_pathSegments;\n\tconst cornerSegmentArc = Math.PI / 2 / gui_cornerSegments;\n\tconst cornerRadiusPercent = Math.min( (1 - gui_cornerRadius / 100) * gui_pathRadius, gui_pathRadius - .1 ); // sub .1 from pathRadius, otherwise cap's hidden.\n\tconst arcRadius = gui_pathRadius - cornerRadiusPercent; // to use absolute cornerRadius, just replace 'cornerRadiusPercent' with 'gui_cornerRadius'\n\n\tfunction setPathCenter( vec, numSeg )\n\t{\n\t\tconst startBottomAngle = Math.PI / 2;\n\t\t\n\t\ty = numSeg * heightSegment; // include \"+ baseHeight\" if want both sides to change simultaneously (and delete the line below, adding baseHeight)\n\t\tang = 2 * Math.PI * (y % revolutionHeight) / revolutionHeight + startBottomAngle;\n\t\ty += baseHeight;\n\t\tz = Math.sin( ang ) * radiusDepth;\n\t\tx = Math.cos( ang ) * radiusWidth; \n\t\t\n\t\tif( isTorus )\n\t\t\tvec.set( x, z, y );\n\t\telse\n\t\t\tvec.set( x, y, z );\n\t}\n\n\tsetPathCenter( v0, -1 ); \n\tsetPathCenter( v1, 0 );\n\n\tlastCoord.copy( v0 );\n\n\n\t// UVs\n\tconst segmentLength = v0.distanceTo( v1 );\n\tconst helixLength = segmentLength * tubeSegments + 2 * arcRadius;\n\tconst startBottomCaps = 0;\n\tconst startTopCaps = helixLength - arcRadius;\n\n\n\t// solucao para distorcao quando width != depth\n\t// os circulos dos segmentos apontam para o meio da helice, por isso o tubo da helice fica distorcido em qualguer angulo diferente das 4 posicoes onde forma angulo de 90 graus.\n\t// solucao eh pegar o vetor de 2 eixos consecutivos do tubo ( (pathCenter-lastCoord) - (proximo_pathCenter-proximo_lastCoord)) chamar de \"eixoTubo\"\n\t// depois fazer o cross desse eixoTubo com o UpVector, chamar de \"vectorToHelixCenter\" (atencao, nao eh o exato centro da helix, )\n\n\n\t// tube geometry with caps----------------------------------------------\n\tfor( let numSeg = 0; numSeg <= tubeSegments; numSeg++ ) \n\t{\n\t\tsetPathCenter( pathCenter, numSeg );\n\n\t\tpathAxis.subVectors( pathCenter, lastCoord ).normalize();\n\t\tlastCoord.copy( pathCenter );\n\n\t\tabscissa.copy( pathCenter ).setComponent( isTorus + 1, 0 ).normalize();\n\t\tordinate.crossVectors( pathAxis, abscissa ).normalize();\n\n\t\tconst startAngle = numSeg == 0 ? 3 * Math.PI / 2 : cornerSegmentArc;\n\t\tconst offsetUV = numSeg == 0 ? startBottomCaps : startTopCaps;\n\n\t\tfor( let i = 0, angPath = 0; i <= gui_pathSegments; i++, angPath = i * pathSegmentArc )\n\t\t{\n\t\t\tpathRadiusLine.addVectors( v0.copy( abscissa ).multiplyScalar( gui_pathRadius * Math.cos( angPath )), \n\t\t\t\t\t\t\t\t\t v1.copy( ordinate ).multiplyScalar( gui_pathRadius * Math.sin( angPath )));\n\t\t\tpathRadiusNormal.copy( pathRadiusLine ).normalize();\n\n\t\t\t// top and bottom caps\n\t\t\tif( numSeg == 0 || numSeg == tubeSegments )\n\t\t\t{\n\t\t\t\tv1.copy( pathRadiusNormal ).multiplyScalar( cornerRadiusPercent );\n\t\t\t\tcornerCenter.addVectors( pathCenter, v1 );\n\n\t\t\t\tfor( let j = 0, angCorner = startAngle; j < gui_cornerSegments; j++, angCorner = j * cornerSegmentArc + startAngle )\n\t\t\t\t{\n\t\t\t\t\tcornerRadiusLine.addVectors( v0.copy( pathAxis ).multiplyScalar( arcRadius * Math.sin( angCorner )), \n\t\t\t\t\t\t\t\t\t\t\t\t v1.copy( pathRadiusNormal ).multiplyScalar( arcRadius * Math.cos( angCorner )));\n\n\t\t\t\t\tv1.addVectors( cornerCenter, cornerRadiusLine );\n\n\t\t\t\t\tcornerRadiusLine.normalize();\n\n\t\t\t\t\tverticesCaps.push( v1.x, v1.y, v1.z );\n\t\t\t\t\tnormalsCaps.push( cornerRadiusLine.x, cornerRadiusLine.y, cornerRadiusLine.z );\n\t\t\t\t\tconst sinUV = (numSeg == 0) + Math.sin( angCorner );\n\t\t\t\t\tuvsCaps.push( ( offsetUV + arcRadius * sinUV ) / helixLength, i / gui_pathSegments, 0 ); // 3 coordinates instead of 2, for merging below\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\n\t\t\tv1.addVectors( pathCenter, pathRadiusLine );\n\n\t\t\tvertices.push( v1.x, v1.y, v1.z );\n\t\t\tnormals.push( pathRadiusNormal.x, pathRadiusNormal.y, pathRadiusNormal.z );\n\t\t\tuvs.push( ( arcRadius + numSeg * segmentLength ) / helixLength, i / gui_pathSegments ); \n\t\t}\n\t}\n\n\t// sort/merge caps vertices---------------------------------\n\tconst topCapsInd = verticesCaps.length / 2;\n\n\tfor( let i = 0; i < gui_cornerSegments; i++ )\n\t{\n\t\tfor( let j = 0; j <= gui_pathSegments; j++ )\n\t\t{\n\t\t\t// To Do: instead of dynamic allocating these vertices, just allocate all memory once then just assign values using the right array's indices.\n\t\t\tlet top = topCapsInd + (j * gui_cornerSegments + i) * 3;\n\t\t\tlet bottom = ((gui_pathSegments - j) * gui_cornerSegments + gui_cornerSegments - i - 1 ) * 3;\n\t\t\tvertices.push( ...verticesCaps.slice( top, top + 3 ) ); vertices.unshift( ...verticesCaps.slice( bottom, bottom + 3 ) );\n\t\t\tnormals.push( ...normalsCaps.slice( top, top + 3 ) ); normals.unshift( ...normalsCaps.slice( bottom, bottom + 3 ) );\n\t\t\tuvs.push( ...uvsCaps.slice( top, top + 2 ) ); uvs.unshift( ...uvsCaps.slice( bottom, bottom + 2 ) );\n\t\t}\n\t}\n\t\n\n\t// indices for the tube and corners ----------------------------------------\n\tconst ps1 = gui_pathSegments + 1;\n\n\tfor( let i = 0; i < tubeSegments + 2 * gui_cornerSegments; i++ ) \n\t{\n\t\tfor( let j = 0; j < ps1 - 1; j++ )\n\t\t{\n\t\t\ta = i * ps1 + j; b = a + 1; // a---b is each side of the circle from the current segment\n\t\t\tc = a + ps1 ; d = b + ps1; // c---d is each corresponding side from the next segment\n\t\t\tindices.push( a, b, c, b, d, c ); // two tris, CW winding.\n\t\t}\n\t}\n\n\t// indices for the two cap tops ---------------------------------------------\n\ta = vertices.length / 3 - gui_pathSegments - 1;\n\n\tfor( let i = 0; i < gui_pathSegments - 2; i++ ) \n\t{\n\t\t// fan triangulation\n\t\tindices.push( a, a + i + 1, a + i + 2 ); // top cap\n\t\tindices.push( 0, i + 2, i + 1 ); // bottom cap\n\t}\n\n\t// --------------------------------------------------------------\n\tlet geometry = new THREE.BufferGeometry();\n\tgeometry.setIndex( indices );\n\tgeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );\n\tgeometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );\n\tgeometry.setAttribute( 'uv', new THREE.Float32BufferAttribute( uvs, 2 ) );\n\t\n\treturn geometry;\n}", "function subdivide(complex) {\n var positions = complex.positions\n var cells = complex.cells\n\n var newCells = []\n var newPositions = []\n var midpoints = {}\n var f = [0, 1, 2]\n var l = 0\n\n for (var i = 0; i < cells.length; i++) {\n var cell = cells[i]\n var c0 = cell[0]\n var c1 = cell[1]\n var c2 = cell[2]\n var v0 = positions[c0]\n var v1 = positions[c1]\n var v2 = positions[c2]\n\n var a = getMidpoint(v0, v1)\n var b = getMidpoint(v1, v2)\n var c = getMidpoint(v2, v0)\n\n var ai = newPositions.indexOf(a)\n if (ai === -1) ai = l++, newPositions.push(a)\n var bi = newPositions.indexOf(b)\n if (bi === -1) bi = l++, newPositions.push(b)\n var ci = newPositions.indexOf(c)\n if (ci === -1) ci = l++, newPositions.push(c)\n\n var v0i = newPositions.indexOf(v0)\n if (v0i === -1) v0i = l++, newPositions.push(v0)\n var v1i = newPositions.indexOf(v1)\n if (v1i === -1) v1i = l++, newPositions.push(v1)\n var v2i = newPositions.indexOf(v2)\n if (v2i === -1) v2i = l++, newPositions.push(v2)\n\n newCells.push([v0i, ai, ci])\n newCells.push([v1i, bi, ai])\n newCells.push([v2i, ci, bi])\n newCells.push([ai, bi, ci])\n }\n\n return {\n cells: newCells\n , positions: newPositions\n }\n\n // reuse midpoint vertices between iterations.\n // Otherwise, there'll be duplicate vertices in the final\n // mesh, resulting in sharp edges.\n function getMidpoint(a, b) {\n var point = midpoint(a, b)\n var pointKey = pointToKey(point)\n var cachedPoint = midpoints[pointKey]\n if (cachedPoint) {\n return cachedPoint\n } else {\n return midpoints[pointKey] = point\n }\n }\n\n function pointToKey(point) {\n return point[0].toPrecision(6) + ','\n + point[1].toPrecision(6) + ','\n + point[2].toPrecision(6)\n }\n\n function midpoint(a, b) {\n return [\n (a[0] + b[0]) / 2\n , (a[1] + b[1]) / 2\n , (a[2] + b[2]) / 2\n ]\n }\n}", "function cube (size) {\n var points = [[-size, -size], [size, -size], [size, size], [-size, size]]\n var complex = extrude(points, {bottom: -1.333, top: 1.333})\n var flattened = unindex(complex.positions, complex.cells)\n var complex = reindex(flattened)\n complex.barycentric = addBarycentricCoordinates(complex, true)\n\n // hack to fix barycentric coordinates\n complex.barycentric[24] = [0, 1, 0]\n complex.barycentric[25] = [0, 0, 1]\n complex.barycentric[26] = [1, 0, 1]\n complex.barycentric[27] = [1, 0, 1]\n complex.barycentric[28] = [0, 1, 0]\n complex.barycentric[29] = [1, 0, 1]\n\n complex.barycentric[30] = [1, 0, 1]\n complex.barycentric[31] = [0, 1, 0]\n complex.barycentric[32] = [1, 0, 1]\n complex.barycentric[33] = [0, 1, 0]\n complex.barycentric[34] = [0, 0, 1]\n complex.barycentric[35] = [1, 0, 1]\n\n return complex\n}", "buildPickTriangles(positions, indices, compressGeometry) {\n\n const numIndices = indices.length;\n const pickPositions = compressGeometry ? new Uint16Array(numIndices * 9) : new Float32Array(numIndices * 9);\n const pickColors = new Uint8Array(numIndices * 12);\n let primIndex = 0;\n let vi;// Positions array index\n let pvi = 0;// Picking positions array index\n let pci = 0; // Picking color array index\n\n // Triangle indices\n let i;\n let r;\n let g;\n let b;\n let a;\n\n for (let location = 0; location < numIndices; location += 3) {\n\n // Primitive-indexed triangle pick color\n\n a = (primIndex >> 24 & 0xFF);\n b = (primIndex >> 16 & 0xFF);\n g = (primIndex >> 8 & 0xFF);\n r = (primIndex & 0xFF);\n\n // A\n\n i = indices[location];\n vi = i * 3;\n\n pickPositions[pvi++] = positions[vi];\n pickPositions[pvi++] = positions[vi + 1];\n pickPositions[pvi++] = positions[vi + 2];\n\n pickColors[pci++] = r;\n pickColors[pci++] = g;\n pickColors[pci++] = b;\n pickColors[pci++] = a;\n\n // B\n\n i = indices[location + 1];\n vi = i * 3;\n\n pickPositions[pvi++] = positions[vi];\n pickPositions[pvi++] = positions[vi + 1];\n pickPositions[pvi++] = positions[vi + 2];\n\n pickColors[pci++] = r;\n pickColors[pci++] = g;\n pickColors[pci++] = b;\n pickColors[pci++] = a;\n\n // C\n\n i = indices[location + 2];\n vi = i * 3;\n\n pickPositions[pvi++] = positions[vi];\n pickPositions[pvi++] = positions[vi + 1];\n pickPositions[pvi++] = positions[vi + 2];\n\n pickColors[pci++] = r;\n pickColors[pci++] = g;\n pickColors[pci++] = b;\n pickColors[pci++] = a;\n\n primIndex++;\n }\n\n return {\n positions: pickPositions,\n colors: pickColors\n };\n }", "addShapeVertices(shape, vertices, indices, normals) {\n var indexOffset = vertices.length / 3;\n let i, l, shapeHole, curveSegments;\n if (this.parameters.curveSegments === undefined) {\n console.warn(\n \"If you don't specify curveSegments explicitly, you'll have to keep \" +\n \"the default synchronized with upstream.\"\n );\n curveSegments = 12;\n } else {\n curveSegments = this.parameters.curveSegments;\n }\n\n let points = shape.extractPoints(curveSegments);\n let shapeVertices = points.shape;\n let shapeHoles = points.holes;\n\n // Ensure correct ordering of vertices.\n if (!THREE.ShapeUtils.isClockWise(shapeVertices)) {\n shapeVertices = shapeVertices.reverse();\n }\n for (i = 0, l = shapeHoles.length; i < l; i++) {\n shapeHole = shapeHoles[i];\n if (THREE.ShapeUtils.isClockWise(shapeHole)) {\n shapeHoles[i] = shapeHole.reverse();\n }\n }\n var faces = THREE.ShapeUtils.triangulateShape(shapeVertices, shapeHoles);\n\n // Join vertices of inner and outer paths to a single array.\n for (i = 0, l = shapeHoles.length; i < l; i++) {\n shapeHole = shapeHoles[i];\n shapeVertices = shapeVertices.concat(shapeHole);\n }\n\n // Append to vertices.\n for (i = 0, l = shapeVertices.length; i < l; i++) {\n var vertex = shapeVertices[i];\n vertices.push(vertex.x, vertex.y, 0);\n normals.push(0, 0, 1);\n }\n\n // incides\n for (i = 0, l = faces.length; i < l; i++) {\n var face = faces[i];\n var a = face[0] + indexOffset;\n var b = face[1] + indexOffset;\n var c = face[2] + indexOffset;\n indices.push(a, b, c);\n }\n }", "function PathMap() {\n\n /**\n * Contains a map of path elements\n *\n * <h1>Path definition</h1>\n * A parameterized path is defined like this:\n * <pre>\n * 'GATEWAY_PARALLEL': {\n * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n * height: 17.5,\n * width: 17.5,\n * heightElements: [2.5, 7.5],\n * widthElements: [2.5, 7.5]\n * }\n * </pre>\n * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling\n * is based on the ratio between the specified height and width in this object and the\n * height and width that is set as scale target (Note x,y coordinates will be scaled with\n * individual ratios).</p>\n * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.\n * The scaling is based on the computed ratios.\n * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using\n * the computed ratio coefficient.\n * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.\n * <ul>\n * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>\n * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>\n * </ul>\n * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.\n * </p>\n */\n this.pathMap = {\n 'EVENT_MESSAGE': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 36,\n width: 36,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'EVENT_SIGNAL': {\n d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x1},0 Z',\n height: 36,\n width: 36,\n heightElements: [18],\n widthElements: [10, 20]\n },\n 'EVENT_ESCALATION': {\n d: 'm {mx},{my} c -{e.x1},{e.y0} -{e.x3},{e.y1} -{e.x5},{e.y4} {e.x1},-{e.y3} {e.x3},-{e.y5} {e.x5},-{e.y6} ' +\n '{e.x0},{e.y3} {e.x2},{e.y5} {e.x4},{e.y6} -{e.x0},-{e.y0} -{e.x2},-{e.y1} -{e.x4},-{e.y4} z',\n height: 36,\n width: 36,\n heightElements: [2.382, 4.764, 4.926, 6.589333, 7.146, 13.178667, 19.768],\n widthElements: [2.463, 2.808, 4.926, 5.616, 7.389, 8.424]\n },\n 'EVENT_CONDITIONAL': {\n d: 'M {e.x0},{e.y0} l {e.x1},0 l 0,{e.y2} l -{e.x1},0 Z ' +\n 'M {e.x2},{e.y3} l {e.x0},0 ' +\n 'M {e.x2},{e.y4} l {e.x0},0 ' +\n 'M {e.x2},{e.y5} l {e.x0},0 ' +\n 'M {e.x2},{e.y6} l {e.x0},0 ' +\n 'M {e.x2},{e.y7} l {e.x0},0 ' +\n 'M {e.x2},{e.y8} l {e.x0},0 ',\n height: 36,\n width: 36,\n heightElements: [8.5, 14.5, 18, 11.5, 14.5, 17.5, 20.5, 23.5, 26.5],\n widthElements: [10.5, 14.5, 12.5]\n },\n 'EVENT_LINK': {\n d: 'm {mx},{my} 0,{e.y0} -{e.x1},0 0,{e.y1} {e.x1},0 0,{e.y0} {e.x0},-{e.y2} -{e.x0},-{e.y2} z',\n height: 36,\n width: 36,\n heightElements: [4.4375, 6.75, 7.8125],\n widthElements: [9.84375, 13.5]\n },\n 'EVENT_ERROR': {\n d: 'm {mx},{my} {e.x0},-{e.y0} {e.x1},-{e.y1} {e.x2},{e.y2} {e.x3},-{e.y3} -{e.x4},{e.y4} -{e.x5},-{e.y5} z',\n height: 36,\n width: 36,\n heightElements: [0.023, 8.737, 8.151, 16.564, 10.591, 8.714],\n widthElements: [0.085, 6.672, 6.97, 4.273, 5.337, 6.636]\n },\n 'EVENT_CANCEL_45': {\n d: 'm {mx},{my} -{e.x1},0 0,{e.x0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 36,\n width: 36,\n heightElements: [4.75, 8.5],\n widthElements: [4.75, 8.5]\n },\n 'EVENT_COMPENSATION': {\n d: 'm {mx},{my} {e.x0},-{e.y0} 0,{e.y1} z m {e.x0},0 {e.x0},-{e.y0} 0,{e.y1} z',\n height: 36,\n width: 36,\n heightElements: [5, 10],\n widthElements: [10]\n },\n 'EVENT_TIMER_WH': {\n d: 'M {mx},{my} l {e.x0},-{e.y0} m -{e.x0},{e.y0} l {e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 2],\n widthElements: [3, 7]\n },\n 'EVENT_TIMER_LINE': {\n d: 'M {mx},{my} ' +\n 'm {e.x0},{e.y0} l -{e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 3],\n widthElements: [0, 0]\n },\n 'EVENT_MULTIPLE': {\n d:'m {mx},{my} {e.x1},-{e.y0} {e.x1},{e.y0} -{e.x0},{e.y1} -{e.x2},0 z',\n height: 36,\n width: 36,\n heightElements: [6.28099, 12.56199],\n widthElements: [3.1405, 9.42149, 12.56198]\n },\n 'EVENT_PARALLEL_MULTIPLE': {\n d:'m {mx},{my} {e.x0},0 0,{e.y1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n height: 36,\n width: 36,\n heightElements: [2.56228, 7.68683],\n widthElements: [2.56228, 7.68683]\n },\n 'GATEWAY_EXCLUSIVE': {\n d:'m {mx},{my} {e.x0},{e.y0} {e.x1},{e.y0} {e.x2},0 {e.x4},{e.y2} ' +\n '{e.x4},{e.y1} {e.x2},0 {e.x1},{e.y3} {e.x0},{e.y3} ' +\n '{e.x3},0 {e.x5},{e.y1} {e.x5},{e.y2} {e.x3},0 z',\n height: 17.5,\n width: 17.5,\n heightElements: [8.5, 6.5312, -6.5312, -8.5],\n widthElements: [6.5, -6.5, 3, -3, 5, -5]\n },\n 'GATEWAY_PARALLEL': {\n d:'m {mx},{my} 0,{e.y1} -{e.x1},0 0,{e.y0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 30,\n width: 30,\n heightElements: [5, 12.5],\n widthElements: [5, 12.5]\n },\n 'GATEWAY_EVENT_BASED': {\n d:'m {mx},{my} {e.x0},{e.y0} {e.x0},{e.y1} {e.x1},{e.y2} {e.x2},0 z',\n height: 11,\n width: 11,\n heightElements: [-6, 6, 12, -12],\n widthElements: [9, -3, -12]\n },\n 'GATEWAY_COMPLEX': {\n d:'m {mx},{my} 0,{e.y0} -{e.x0},-{e.y1} -{e.x1},{e.y2} {e.x0},{e.y1} -{e.x2},0 0,{e.y3} ' +\n '{e.x2},0 -{e.x0},{e.y1} l {e.x1},{e.y2} {e.x0},-{e.y1} 0,{e.y0} {e.x3},0 0,-{e.y0} {e.x0},{e.y1} ' +\n '{e.x1},-{e.y2} -{e.x0},-{e.y1} {e.x2},0 0,-{e.y3} -{e.x2},0 {e.x0},-{e.y1} -{e.x1},-{e.y2} ' +\n '-{e.x0},{e.y1} 0,-{e.y0} -{e.x3},0 z',\n height: 17.125,\n width: 17.125,\n heightElements: [4.875, 3.4375, 2.125, 3],\n widthElements: [3.4375, 2.125, 4.875, 3]\n },\n 'DATA_OBJECT_PATH': {\n d:'m 0,0 {e.x1},0 {e.x0},{e.y0} 0,{e.y1} -{e.x2},0 0,-{e.y2} {e.x1},0 0,{e.y0} {e.x0},0',\n height: 61,\n width: 51,\n heightElements: [10, 50, 60],\n widthElements: [10, 40, 50, 60]\n },\n 'DATA_OBJECT_COLLECTION_PATH': {\n d:'m {mx}, {my} ' +\n 'm 0 15 l 0 -15 ' +\n 'm 4 15 l 0 -15 ' +\n 'm 4 15 l 0 -15 ',\n height: 61,\n width: 51,\n heightElements: [12],\n widthElements: [1, 6, 12, 15]\n },\n 'DATA_ARROW': {\n d:'m 5,9 9,0 0,-3 5,5 -5,5 0,-3 -9,0 z',\n height: 61,\n width: 51,\n heightElements: [],\n widthElements: []\n },\n 'DATA_STORE': {\n d:'m {mx},{my} ' +\n 'l 0,{e.y2} ' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'l 0,-{e.y2} ' +\n 'c -{e.x0},-{e.y1} -{e.x1},-{e.y1} -{e.x2},0' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0',\n height: 61,\n width: 61,\n heightElements: [7, 10, 45],\n widthElements: [2, 58, 60]\n },\n 'TEXT_ANNOTATION': {\n d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',\n height: 30,\n width: 10,\n heightElements: [30],\n widthElements: [10]\n },\n 'MARKER_SUB_PROCESS': {\n d: 'm{mx},{my} m 7,2 l 0,10 m -5,-5 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_PARALLEL': {\n d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_SEQUENTIAL': {\n d: 'm{mx},{my} m 0,3 l 10,0 m -10,3 l 10,0 m -10,3 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_COMPENSATION': {\n d: 'm {mx},{my} 8,-5 0,10 z m 9,0 8,-5 0,10 z',\n height: 10,\n width: 21,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_LOOP': {\n d: 'm {mx},{my} c 3.526979,0 6.386161,-2.829858 6.386161,-6.320661 0,-3.490806 -2.859182,-6.320661 ' +\n '-6.386161,-6.320661 -3.526978,0 -6.38616,2.829855 -6.38616,6.320661 0,1.745402 ' +\n '0.714797,3.325567 1.870463,4.469381 0.577834,0.571908 1.265885,1.034728 2.029916,1.35457 ' +\n 'l -0.718163,-3.909793 m 0.718163,3.909793 -3.885211,0.802902',\n height: 13.9,\n width: 13.7,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_ADHOC': {\n d: 'm {mx},{my} m 0.84461,2.64411 c 1.05533,-1.23780996 2.64337,-2.07882 4.29653,-1.97997996 2.05163,0.0805 ' +\n '3.85579,1.15803 5.76082,1.79107 1.06385,0.34139996 2.24454,0.1438 3.18759,-0.43767 0.61743,-0.33642 ' +\n '1.2775,-0.64078 1.7542,-1.17511 0,0.56023 0,1.12046 0,1.6807 -0.98706,0.96237996 -2.29792,1.62393996 ' +\n '-3.6918,1.66181996 -1.24459,0.0927 -2.46671,-0.2491 -3.59505,-0.74812 -1.35789,-0.55965 ' +\n '-2.75133,-1.33436996 -4.27027,-1.18121996 -1.37741,0.14601 -2.41842,1.13685996 -3.44288,1.96782996 z',\n height: 4,\n width: 15,\n heightElements: [],\n widthElements: []\n },\n 'TASK_TYPE_SEND': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 14,\n width: 21,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_SCRIPT': {\n d: 'm {mx},{my} c 9.966553,-6.27276 -8.000926,-7.91932 2.968968,-14.938 l -8.802728,0 ' +\n 'c -10.969894,7.01868 6.997585,8.66524 -2.968967,14.938 z ' +\n 'm -7,-12 l 5,0 ' +\n 'm -4.5,3 l 4.5,0 ' +\n 'm -3,3 l 5,0' +\n 'm -4,3 l 5,0',\n height: 15,\n width: 12.6,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_USER_1': {\n d: 'm {mx},{my} c 0.909,-0.845 1.594,-2.049 1.594,-3.385 0,-2.554 -1.805,-4.62199999 ' +\n '-4.357,-4.62199999 -2.55199998,0 -4.28799998,2.06799999 -4.28799998,4.62199999 0,1.348 ' +\n '0.974,2.562 1.89599998,3.405 -0.52899998,0.187 -5.669,2.097 -5.794,4.7560005 v 6.718 ' +\n 'h 17 v -6.718 c 0,-2.2980005 -5.5279996,-4.5950005 -6.0509996,-4.7760005 z' +\n 'm -8,6 l 0,5.5 m 11,0 l 0,-5'\n },\n 'TASK_TYPE_USER_2': {\n d: 'm {mx},{my} m 2.162,1.009 c 0,2.4470005 -2.158,4.4310005 -4.821,4.4310005 ' +\n '-2.66499998,0 -4.822,-1.981 -4.822,-4.4310005 '\n },\n 'TASK_TYPE_USER_3': {\n d: 'm {mx},{my} m -6.9,-3.80 c 0,0 2.25099998,-2.358 4.27399998,-1.177 2.024,1.181 4.221,1.537 ' +\n '4.124,0.965 -0.098,-0.57 -0.117,-3.79099999 -4.191,-4.13599999 -3.57499998,0.001 ' +\n '-4.20799998,3.36699999 -4.20699998,4.34799999 z'\n },\n 'TASK_TYPE_MANUAL': {\n d: 'm {mx},{my} c 0.234,-0.01 5.604,0.008 8.029,0.004 0.808,0 1.271,-0.172 1.417,-0.752 0.227,-0.898 ' +\n '-0.334,-1.314 -1.338,-1.316 -2.467,-0.01 -7.886,-0.004 -8.108,-0.004 -0.014,-0.079 0.016,-0.533 0,-0.61 ' +\n '0.195,-0.042 8.507,0.006 9.616,0.002 0.877,-0.007 1.35,-0.438 1.353,-1.208 0.003,-0.768 -0.479,-1.09 ' +\n '-1.35,-1.091 -2.968,-0.002 -9.619,-0.013 -9.619,-0.013 v -0.591 c 0,0 5.052,-0.016 7.225,-0.016 ' +\n '0.888,-0.002 1.354,-0.416 1.351,-1.193 -0.006,-0.761 -0.492,-1.196 -1.361,-1.196 -3.473,-0.005 ' +\n '-10.86,-0.003 -11.0829995,-0.003 -0.022,-0.047 -0.045,-0.094 -0.069,-0.139 0.3939995,-0.319 ' +\n '2.0409995,-1.626 2.4149995,-2.017 0.469,-0.4870005 0.519,-1.1650005 0.162,-1.6040005 -0.414,-0.511 ' +\n '-0.973,-0.5 -1.48,-0.236 -1.4609995,0.764 -6.5999995,3.6430005 -7.7329995,4.2710005 -0.9,0.499 ' +\n '-1.516,1.253 -1.882,2.19 -0.37000002,0.95 -0.17,2.01 -0.166,2.979 0.004,0.718 -0.27300002,1.345 ' +\n '-0.055,2.063 0.629,2.087 2.425,3.312 4.859,3.318 4.6179995,0.014 9.2379995,-0.139 13.8569995,-0.158 ' +\n '0.755,-0.004 1.171,-0.301 1.182,-1.033 0.012,-0.754 -0.423,-0.969 -1.183,-0.973 -1.778,-0.01 ' +\n '-5.824,-0.004 -6.04,-0.004 10e-4,-0.084 0.003,-0.586 10e-4,-0.67 z'\n },\n 'TASK_TYPE_INSTANTIATING_SEND': {\n d: 'm {mx},{my} l 0,8.4 l 12.6,0 l 0,-8.4 z l 6.3,3.6 l 6.3,-3.6'\n },\n 'TASK_TYPE_SERVICE': {\n d: 'm {mx},{my} v -1.71335 c 0.352326,-0.0705 0.703932,-0.17838 1.047628,-0.32133 ' +\n '0.344416,-0.14465 0.665822,-0.32133 0.966377,-0.52145 l 1.19431,1.18005 1.567487,-1.57688 ' +\n '-1.195028,-1.18014 c 0.403376,-0.61394 0.683079,-1.29908 0.825447,-2.01824 l 1.622133,-0.01 ' +\n 'v -2.2196 l -1.636514,0.01 c -0.07333,-0.35153 -0.178319,-0.70024 -0.323564,-1.04372 ' +\n '-0.145244,-0.34406 -0.321407,-0.6644 -0.522735,-0.96217 l 1.131035,-1.13631 -1.583305,-1.56293 ' +\n '-1.129598,1.13589 c -0.614052,-0.40108 -1.302883,-0.68093 -2.022633,-0.82247 l 0.0093,-1.61852 ' +\n 'h -2.241173 l 0.0042,1.63124 c -0.353763,0.0736 -0.705369,0.17977 -1.049785,0.32371 -0.344415,0.14437 ' +\n '-0.665102,0.32092 -0.9635006,0.52046 l -1.1698628,-1.15823 -1.5667691,1.5792 1.1684265,1.15669 ' +\n 'c -0.4026573,0.61283 -0.68308,1.29797 -0.8247287,2.01713 l -1.6588041,0.003 v 2.22174 ' +\n 'l 1.6724648,-0.006 c 0.073327,0.35077 0.1797598,0.70243 0.3242851,1.04472 0.1452428,0.34448 ' +\n '0.3214064,0.6644 0.5227339,0.96066 l -1.1993431,1.19723 1.5840256,1.56011 1.1964668,-1.19348 ' +\n 'c 0.6140517,0.40346 1.3028827,0.68232 2.0233517,0.82331 l 7.19e-4,1.69892 h 2.226848 z ' +\n 'm 0.221462,-3.9957 c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_SERVICE_FILL': {\n d: 'm {mx},{my} c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_HEADER': {\n d: 'm {mx},{my} 0,4 20,0 0,-4 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_MAIN': {\n d: 'm {mx},{my} 0,12 20,0 0,-12 z' +\n 'm 0,8 l 20,0 ' +\n 'm -13,-4 l 0,8'\n },\n 'MESSAGE_FLOW_MARKER': {\n d: 'm {mx},{my} m -10.5 ,-7 l 0,14 l 21,0 l 0,-14 z l 10.5,6 l 10.5,-6'\n }\n };\n\n this.getRawPath = function getRawPath(pathId) {\n return this.pathMap[pathId].d;\n };\n\n /**\n * Scales the path to the given height and width.\n * <h1>Use case</h1>\n * <p>Use case is to scale the content of elements (event, gateways) based\n * on the element bounding box's size.\n * </p>\n * <h1>Why not transform</h1>\n * <p>Scaling a path with transform() will also scale the stroke and IE does not support\n * the option 'non-scaling-stroke' to prevent this.\n * Also there are use cases where only some parts of a path should be\n * scaled.</p>\n *\n * @param {String} pathId The ID of the path.\n * @param {Object} param <p>\n * Example param object scales the path to 60% size of the container (data.width, data.height).\n * <pre>\n * {\n * xScaleFactor: 0.6,\n * yScaleFactor:0.6,\n * containerWidth: data.width,\n * containerHeight: data.height,\n * position: {\n * mx: 0.46,\n * my: 0.2,\n * }\n * }\n * </pre>\n * <ul>\n * <li>targetpathwidth = xScaleFactor * containerWidth</li>\n * <li>targetpathheight = yScaleFactor * containerHeight</li>\n * <li>Position is used to set the starting coordinate of the path. M is computed:\n * <ul>\n * <li>position.x * containerWidth</li>\n * <li>position.y * containerHeight</li>\n * </ul>\n * Center of the container <pre> position: {\n * mx: 0.5,\n * my: 0.5,\n * }</pre>\n * Upper left corner of the container\n * <pre> position: {\n * mx: 0.0,\n * my: 0.0,\n * }</pre>\n * </li>\n * </ul>\n * </p>\n *\n */\n this.getScaledPath = function getScaledPath(pathId, param) {\n var rawPath = this.pathMap[pathId];\n\n // positioning\n // compute the start point of the path\n var mx, my;\n\n if(!!param.abspos) {\n mx = param.abspos.x;\n my = param.abspos.y;\n } else {\n mx = param.containerWidth * param.position.mx;\n my = param.containerHeight * param.position.my;\n }\n\n var coordinates = {}; //map for the scaled coordinates\n if(param.position) {\n\n // path\n var heightRatio = (param.containerHeight / rawPath.height) * param.yScaleFactor;\n var widthRatio = (param.containerWidth / rawPath.width) * param.xScaleFactor;\n\n\n //Apply height ratio\n for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {\n coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;\n }\n\n //Apply width ratio\n for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {\n coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;\n }\n }\n\n //Apply value to raw path\n var path = Snap.format(\n rawPath.d, {\n mx: mx,\n my: my,\n e: coordinates\n }\n );\n return path;\n };\n}", "function PathMap() {\n\n /**\n * Contains a map of path elements\n *\n * <h1>Path definition</h1>\n * A parameterized path is defined like this:\n * <pre>\n * 'GATEWAY_PARALLEL': {\n * d: 'm {mx},{my} {e.x0},0 0,{e.x1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n * height: 17.5,\n * width: 17.5,\n * heightElements: [2.5, 7.5],\n * widthElements: [2.5, 7.5]\n * }\n * </pre>\n * <p>It's important to specify a correct <b>height and width</b> for the path as the scaling\n * is based on the ratio between the specified height and width in this object and the\n * height and width that is set as scale target (Note x,y coordinates will be scaled with\n * individual ratios).</p>\n * <p>The '<b>heightElements</b>' and '<b>widthElements</b>' array must contain the values that will be scaled.\n * The scaling is based on the computed ratios.\n * Coordinates on the y axis should be in the <b>heightElement</b>'s array, they will be scaled using\n * the computed ratio coefficient.\n * In the parameterized path the scaled values can be accessed through the 'e' object in {} brackets.\n * <ul>\n * <li>The values for the y axis can be accessed in the path string using {e.y0}, {e.y1}, ....</li>\n * <li>The values for the x axis can be accessed in the path string using {e.x0}, {e.x1}, ....</li>\n * </ul>\n * The numbers x0, x1 respectively y0, y1, ... map to the corresponding array index.\n * </p>\n */\n this.pathMap = {\n 'EVENT_MESSAGE': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 36,\n width: 36,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'EVENT_SIGNAL': {\n d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x1},0 Z',\n height: 36,\n width: 36,\n heightElements: [18],\n widthElements: [10, 20]\n },\n 'EVENT_ESCALATION': {\n d: 'M {mx},{my} l {e.x0},{e.y0} l -{e.x0},-{e.y1} l -{e.x0},{e.y1} Z',\n height: 36,\n width: 36,\n heightElements: [20, 7],\n widthElements: [8]\n },\n 'EVENT_CONDITIONAL': {\n d: 'M {e.x0},{e.y0} l {e.x1},0 l 0,{e.y2} l -{e.x1},0 Z ' +\n 'M {e.x2},{e.y3} l {e.x0},0 ' +\n 'M {e.x2},{e.y4} l {e.x0},0 ' +\n 'M {e.x2},{e.y5} l {e.x0},0 ' +\n 'M {e.x2},{e.y6} l {e.x0},0 ' +\n 'M {e.x2},{e.y7} l {e.x0},0 ' +\n 'M {e.x2},{e.y8} l {e.x0},0 ',\n height: 36,\n width: 36,\n heightElements: [8.5, 14.5, 18, 11.5, 14.5, 17.5, 20.5, 23.5, 26.5],\n widthElements: [10.5, 14.5, 12.5]\n },\n 'EVENT_LINK': {\n d: 'm {mx},{my} 0,{e.y0} -{e.x1},0 0,{e.y1} {e.x1},0 0,{e.y0} {e.x0},-{e.y2} -{e.x0},-{e.y2} z',\n height: 36,\n width: 36,\n heightElements: [4.4375, 6.75, 7.8125],\n widthElements: [9.84375, 13.5]\n },\n 'EVENT_ERROR': {\n d: 'm {mx},{my} {e.x0},-{e.y0} {e.x1},-{e.y1} {e.x2},{e.y2} {e.x3},-{e.y3} -{e.x4},{e.y4} -{e.x5},-{e.y5} z',\n height: 36,\n width: 36,\n heightElements: [0.023, 8.737, 8.151, 16.564, 10.591, 8.714],\n widthElements: [0.085, 6.672, 6.97, 4.273, 5.337, 6.636]\n },\n 'EVENT_CANCEL_45': {\n d: 'm {mx},{my} -{e.x1},0 0,{e.x0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 36,\n width: 36,\n heightElements: [4.75, 8.5],\n widthElements: [4.75, 8.5]\n },\n 'EVENT_COMPENSATION': {\n d: 'm {mx},{my} {e.x0},-{e.y0} 0,{e.y1} z m {e.x1},-{e.y2} {e.x2},-{e.y3} 0,{e.y1} -{e.x2},-{e.y3} z',\n height: 36,\n width: 36,\n heightElements: [6.5, 13, 0.4, 6.1],\n widthElements: [9, 9.3, 8.7]\n },\n 'EVENT_TIMER_WH': {\n d: 'M {mx},{my} l {e.x0},-{e.y0} m -{e.x0},{e.y0} l {e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 2],\n widthElements: [3, 7]\n },\n 'EVENT_TIMER_LINE': {\n d: 'M {mx},{my} ' +\n 'm {e.x0},{e.y0} l -{e.x1},{e.y1} ',\n height: 36,\n width: 36,\n heightElements: [10, 3],\n widthElements: [0, 0]\n },\n 'EVENT_MULTIPLE': {\n d:'m {mx},{my} {e.x1},-{e.y0} {e.x1},{e.y0} -{e.x0},{e.y1} -{e.x2},0 z',\n height: 36,\n width: 36,\n heightElements: [6.28099, 12.56199],\n widthElements: [3.1405, 9.42149, 12.56198]\n },\n 'EVENT_PARALLEL_MULTIPLE': {\n d:'m {mx},{my} {e.x0},0 0,{e.y1} {e.x1},0 0,{e.y0} -{e.x1},0 0,{e.y1} ' +\n '-{e.x0},0 0,-{e.y1} -{e.x1},0 0,-{e.y0} {e.x1},0 z',\n height: 36,\n width: 36,\n heightElements: [2.56228, 7.68683],\n widthElements: [2.56228, 7.68683]\n },\n 'GATEWAY_EXCLUSIVE': {\n d:'m {mx},{my} {e.x0},{e.y0} {e.x1},{e.y0} {e.x2},0 {e.x4},{e.y2} ' +\n '{e.x4},{e.y1} {e.x2},0 {e.x1},{e.y3} {e.x0},{e.y3} ' +\n '{e.x3},0 {e.x5},{e.y1} {e.x5},{e.y2} {e.x3},0 z',\n height: 17.5,\n width: 17.5,\n heightElements: [8.5, 6.5312, -6.5312, -8.5],\n widthElements: [6.5, -6.5, 3, -3, 5, -5]\n },\n 'GATEWAY_PARALLEL': {\n d:'m {mx},{my} 0,{e.y1} -{e.x1},0 0,{e.y0} {e.x1},0 0,{e.y1} {e.x0},0 ' +\n '0,-{e.y1} {e.x1},0 0,-{e.y0} -{e.x1},0 0,-{e.y1} -{e.x0},0 z',\n height: 30,\n width: 30,\n heightElements: [5, 12.5],\n widthElements: [5, 12.5]\n },\n 'GATEWAY_EVENT_BASED': {\n d:'m {mx},{my} {e.x0},{e.y0} {e.x0},{e.y1} {e.x1},{e.y2} {e.x2},0 z',\n height: 11,\n width: 11,\n heightElements: [-6, 6, 12, -12],\n widthElements: [9, -3, -12]\n },\n 'GATEWAY_COMPLEX': {\n d:'m {mx},{my} 0,{e.y0} -{e.x0},-{e.y1} -{e.x1},{e.y2} {e.x0},{e.y1} -{e.x2},0 0,{e.y3} ' +\n '{e.x2},0 -{e.x0},{e.y1} l {e.x1},{e.y2} {e.x0},-{e.y1} 0,{e.y0} {e.x3},0 0,-{e.y0} {e.x0},{e.y1} ' +\n '{e.x1},-{e.y2} -{e.x0},-{e.y1} {e.x2},0 0,-{e.y3} -{e.x2},0 {e.x0},-{e.y1} -{e.x1},-{e.y2} ' +\n '-{e.x0},{e.y1} 0,-{e.y0} -{e.x3},0 z',\n height: 17.125,\n width: 17.125,\n heightElements: [4.875, 3.4375, 2.125, 3],\n widthElements: [3.4375, 2.125, 4.875, 3]\n },\n 'DATA_OBJECT_PATH': {\n d:'m 0,0 {e.x1},0 {e.x0},{e.y0} 0,{e.y1} -{e.x2},0 0,-{e.y2} {e.x1},0 0,{e.y0} {e.x0},0',\n height: 61,\n width: 51,\n heightElements: [10, 50, 60],\n widthElements: [10, 40, 50, 60]\n },\n 'DATA_OBJECT_COLLECTION_PATH': {\n d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'DATA_ARROW': {\n d:'m 5,9 9,0 0,-3 5,5 -5,5 0,-3 -9,0 z',\n height: 61,\n width: 51,\n heightElements: [],\n widthElements: []\n },\n 'DATA_STORE': {\n d:'m {mx},{my} ' +\n 'l 0,{e.y2} ' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'l 0,-{e.y2} ' +\n 'c -{e.x0},-{e.y1} -{e.x1},-{e.y1} -{e.x2},0' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0 ' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0' +\n 'm -{e.x2},{e.y0}' +\n 'c {e.x0},{e.y1} {e.x1},{e.y1} {e.x2},0',\n height: 61,\n width: 61,\n heightElements: [7, 10, 45],\n widthElements: [2, 58, 60]\n },\n 'TEXT_ANNOTATION': {\n d: 'm {mx}, {my} m 10,0 l -10,0 l 0,{e.y0} l 10,0',\n height: 30,\n width: 10,\n heightElements: [30],\n widthElements: [10]\n },\n 'MARKER_SUB_PROCESS': {\n d: 'm{mx},{my} m 7,2 l 0,10 m -5,-5 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_PARALLEL': {\n d: 'm{mx},{my} m 3,2 l 0,10 m 3,-10 l 0,10 m 3,-10 l 0,10',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_SEQUENTIAL': {\n d: 'm{mx},{my} m 0,3 l 10,0 m -10,3 l 10,0 m -10,3 l 10,0',\n height: 10,\n width: 10,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_COMPENSATION': {\n d: 'm {mx},{my} 7,-5 0,10 z m 7.1,-0.3 6.9,-4.7 0,10 -6.9,-4.7 z',\n height: 10,\n width: 21,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_LOOP': {\n d: 'm {mx},{my} c 3.526979,0 6.386161,-2.829858 6.386161,-6.320661 0,-3.490806 -2.859182,-6.320661 ' +\n '-6.386161,-6.320661 -3.526978,0 -6.38616,2.829855 -6.38616,6.320661 0,1.745402 ' +\n '0.714797,3.325567 1.870463,4.469381 0.577834,0.571908 1.265885,1.034728 2.029916,1.35457 ' +\n 'l -0.718163,-3.909793 m 0.718163,3.909793 -3.885211,0.802902',\n height: 13.9,\n width: 13.7,\n heightElements: [],\n widthElements: []\n },\n 'MARKER_ADHOC': {\n d: 'm {mx},{my} m 0.84461,2.64411 c 1.05533,-1.23780996 2.64337,-2.07882 4.29653,-1.97997996 2.05163,0.0805 ' +\n '3.85579,1.15803 5.76082,1.79107 1.06385,0.34139996 2.24454,0.1438 3.18759,-0.43767 0.61743,-0.33642 ' +\n '1.2775,-0.64078 1.7542,-1.17511 0,0.56023 0,1.12046 0,1.6807 -0.98706,0.96237996 -2.29792,1.62393996 ' +\n '-3.6918,1.66181996 -1.24459,0.0927 -2.46671,-0.2491 -3.59505,-0.74812 -1.35789,-0.55965 ' +\n '-2.75133,-1.33436996 -4.27027,-1.18121996 -1.37741,0.14601 -2.41842,1.13685996 -3.44288,1.96782996 z',\n height: 4,\n width: 15,\n heightElements: [],\n widthElements: []\n },\n 'TASK_TYPE_SEND': {\n d: 'm {mx},{my} l 0,{e.y1} l {e.x1},0 l 0,-{e.y1} z l {e.x0},{e.y0} l {e.x0},-{e.y0}',\n height: 14,\n width: 21,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_SCRIPT': {\n d: 'm {mx},{my} c 9.966553,-6.27276 -8.000926,-7.91932 2.968968,-14.938 l -8.802728,0 ' +\n 'c -10.969894,7.01868 6.997585,8.66524 -2.968967,14.938 z ' +\n 'm -7,-12 l 5,0 ' +\n 'm -4.5,3 l 4.5,0 ' +\n 'm -3,3 l 5,0' +\n 'm -4,3 l 5,0',\n height: 15,\n width: 12.6,\n heightElements: [6, 14],\n widthElements: [10.5, 21]\n },\n 'TASK_TYPE_USER_1': {\n d: 'm {mx},{my} c 0.909,-0.845 1.594,-2.049 1.594,-3.385 0,-2.554 -1.805,-4.62199999 ' +\n '-4.357,-4.62199999 -2.55199998,0 -4.28799998,2.06799999 -4.28799998,4.62199999 0,1.348 ' +\n '0.974,2.562 1.89599998,3.405 -0.52899998,0.187 -5.669,2.097 -5.794,4.7560005 v 6.718 ' +\n 'h 17 v -6.718 c 0,-2.2980005 -5.5279996,-4.5950005 -6.0509996,-4.7760005 z' +\n 'm -8,6 l 0,5.5 m 11,0 l 0,-5'\n },\n 'TASK_TYPE_USER_2': {\n d: 'm {mx},{my} m 2.162,1.009 c 0,2.4470005 -2.158,4.4310005 -4.821,4.4310005 ' +\n '-2.66499998,0 -4.822,-1.981 -4.822,-4.4310005 '\n },\n 'TASK_TYPE_USER_3': {\n d: 'm {mx},{my} m -6.9,-3.80 c 0,0 2.25099998,-2.358 4.27399998,-1.177 2.024,1.181 4.221,1.537 ' +\n '4.124,0.965 -0.098,-0.57 -0.117,-3.79099999 -4.191,-4.13599999 -3.57499998,0.001 ' +\n '-4.20799998,3.36699999 -4.20699998,4.34799999 z'\n },\n 'TASK_TYPE_MANUAL': {\n d: 'm {mx},{my} c 0.234,-0.01 5.604,0.008 8.029,0.004 0.808,0 1.271,-0.172 1.417,-0.752 0.227,-0.898 ' +\n '-0.334,-1.314 -1.338,-1.316 -2.467,-0.01 -7.886,-0.004 -8.108,-0.004 -0.014,-0.079 0.016,-0.533 0,-0.61 ' +\n '0.195,-0.042 8.507,0.006 9.616,0.002 0.877,-0.007 1.35,-0.438 1.353,-1.208 0.003,-0.768 -0.479,-1.09 ' +\n '-1.35,-1.091 -2.968,-0.002 -9.619,-0.013 -9.619,-0.013 v -0.591 c 0,0 5.052,-0.016 7.225,-0.016 ' +\n '0.888,-0.002 1.354,-0.416 1.351,-1.193 -0.006,-0.761 -0.492,-1.196 -1.361,-1.196 -3.473,-0.005 ' +\n '-10.86,-0.003 -11.0829995,-0.003 -0.022,-0.047 -0.045,-0.094 -0.069,-0.139 0.3939995,-0.319 ' +\n '2.0409995,-1.626 2.4149995,-2.017 0.469,-0.4870005 0.519,-1.1650005 0.162,-1.6040005 -0.414,-0.511 ' +\n '-0.973,-0.5 -1.48,-0.236 -1.4609995,0.764 -6.5999995,3.6430005 -7.7329995,4.2710005 -0.9,0.499 ' +\n '-1.516,1.253 -1.882,2.19 -0.37000002,0.95 -0.17,2.01 -0.166,2.979 0.004,0.718 -0.27300002,1.345 ' +\n '-0.055,2.063 0.629,2.087 2.425,3.312 4.859,3.318 4.6179995,0.014 9.2379995,-0.139 13.8569995,-0.158 ' +\n '0.755,-0.004 1.171,-0.301 1.182,-1.033 0.012,-0.754 -0.423,-0.969 -1.183,-0.973 -1.778,-0.01 ' +\n '-5.824,-0.004 -6.04,-0.004 10e-4,-0.084 0.003,-0.586 10e-4,-0.67 z'\n },\n 'TASK_TYPE_INSTANTIATING_SEND': {\n d: 'm {mx},{my} l 0,8.4 l 12.6,0 l 0,-8.4 z l 6.3,3.6 l 6.3,-3.6'\n },\n 'TASK_TYPE_SERVICE': {\n d: 'm {mx},{my} v -1.71335 c 0.352326,-0.0705 0.703932,-0.17838 1.047628,-0.32133 ' +\n '0.344416,-0.14465 0.665822,-0.32133 0.966377,-0.52145 l 1.19431,1.18005 1.567487,-1.57688 ' +\n '-1.195028,-1.18014 c 0.403376,-0.61394 0.683079,-1.29908 0.825447,-2.01824 l 1.622133,-0.01 ' +\n 'v -2.2196 l -1.636514,0.01 c -0.07333,-0.35153 -0.178319,-0.70024 -0.323564,-1.04372 ' +\n '-0.145244,-0.34406 -0.321407,-0.6644 -0.522735,-0.96217 l 1.131035,-1.13631 -1.583305,-1.56293 ' +\n '-1.129598,1.13589 c -0.614052,-0.40108 -1.302883,-0.68093 -2.022633,-0.82247 l 0.0093,-1.61852 ' +\n 'h -2.241173 l 0.0042,1.63124 c -0.353763,0.0736 -0.705369,0.17977 -1.049785,0.32371 -0.344415,0.14437 ' +\n '-0.665102,0.32092 -0.9635006,0.52046 l -1.1698628,-1.15823 -1.5667691,1.5792 1.1684265,1.15669 ' +\n 'c -0.4026573,0.61283 -0.68308,1.29797 -0.8247287,2.01713 l -1.6588041,0.003 v 2.22174 ' +\n 'l 1.6724648,-0.006 c 0.073327,0.35077 0.1797598,0.70243 0.3242851,1.04472 0.1452428,0.34448 ' +\n '0.3214064,0.6644 0.5227339,0.96066 l -1.1993431,1.19723 1.5840256,1.56011 1.1964668,-1.19348 ' +\n 'c 0.6140517,0.40346 1.3028827,0.68232 2.0233517,0.82331 l 7.19e-4,1.69892 h 2.226848 z ' +\n 'm 0.221462,-3.9957 c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_SERVICE_FILL': {\n d: 'm {mx},{my} c -1.788948,0.7502 -3.8576,-0.0928 -4.6097055,-1.87438 -0.7521065,-1.78321 ' +\n '0.090598,-3.84627 1.8802645,-4.59604 1.78823,-0.74936 3.856881,0.0929 4.608987,1.87437 ' +\n '0.752106,1.78165 -0.0906,3.84612 -1.879546,4.59605 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_HEADER': {\n d: 'm {mx},{my} 0,4 20,0 0,-4 z'\n },\n 'TASK_TYPE_BUSINESS_RULE_MAIN': {\n d: 'm {mx},{my} 0,12 20,0 0,-12 z' +\n 'm 0,8 l 20,0 ' +\n 'm -13,-4 l 0,8'\n },\n 'MESSAGE_FLOW_MARKER': {\n d: 'm {mx},{my} m -10.5 ,-7 l 0,14 l 21,0 l 0,-14 z l 10.5,6 l 10.5,-6'\n }\n };\n\n this.getRawPath = function getRawPath(pathId) {\n return this.pathMap[pathId].d;\n };\n\n /**\n * Scales the path to the given height and width.\n * <h1>Use case</h1>\n * <p>Use case is to scale the content of elements (event, gateways) based\n * on the element bounding box's size.\n * </p>\n * <h1>Why not transform</h1>\n * <p>Scaling a path with transform() will also scale the stroke and IE does not support\n * the option 'non-scaling-stroke' to prevent this.\n * Also there are use cases where only some parts of a path should be\n * scaled.</p>\n *\n * @param {string} pathId The ID of the path.\n * @param {Object} param <p>\n * Example param object scales the path to 60% size of the container (data.width, data.height).\n * <pre>\n * {\n * xScaleFactor: 0.6,\n * yScaleFactor:0.6,\n * containerWidth: data.width,\n * containerHeight: data.height,\n * position: {\n * mx: 0.46,\n * my: 0.2,\n * }\n * }\n * </pre>\n * <ul>\n * <li>targetpathwidth = xScaleFactor * containerWidth</li>\n * <li>targetpathheight = yScaleFactor * containerHeight</li>\n * <li>Position is used to set the starting coordinate of the path. M is computed:\n * <ul>\n * <li>position.x * containerWidth</li>\n * <li>position.y * containerHeight</li>\n * </ul>\n * Center of the container <pre> position: {\n * mx: 0.5,\n * my: 0.5,\n * }</pre>\n * Upper left corner of the container\n * <pre> position: {\n * mx: 0.0,\n * my: 0.0,\n * }</pre>\n * </li>\n * </ul>\n * </p>\n *\n */\n this.getScaledPath = function getScaledPath(pathId, param) {\n var rawPath = this.pathMap[pathId];\n\n // positioning\n // compute the start point of the path\n var mx, my;\n\n if (param.abspos) {\n mx = param.abspos.x;\n my = param.abspos.y;\n } else {\n mx = param.containerWidth * param.position.mx;\n my = param.containerHeight * param.position.my;\n }\n\n var coordinates = {}; // map for the scaled coordinates\n if (param.position) {\n\n // path\n var heightRatio = (param.containerHeight / rawPath.height) * param.yScaleFactor;\n var widthRatio = (param.containerWidth / rawPath.width) * param.xScaleFactor;\n\n\n // Apply height ratio\n for (var heightIndex = 0; heightIndex < rawPath.heightElements.length; heightIndex++) {\n coordinates['y' + heightIndex] = rawPath.heightElements[heightIndex] * heightRatio;\n }\n\n // Apply width ratio\n for (var widthIndex = 0; widthIndex < rawPath.widthElements.length; widthIndex++) {\n coordinates['x' + widthIndex] = rawPath.widthElements[widthIndex] * widthRatio;\n }\n }\n\n // Apply value to raw path\n var path = format$1(\n rawPath.d, {\n mx: mx,\n my: my,\n e: coordinates\n }\n );\n return path;\n };\n}", "generateTriangles()\r\n{\r\n //Your code here\r\n var deltaX = (this.maxX - this.minX)/this.div;\r\n var deltaY = (this.maxY - this.minY)/this.div;\r\n \r\n // Populate vertex buffer and normal buffer\r\n for(var i = 0; i <= this.div; i++){\r\n for(var j = 0; j <= this.div; j++){\r\n this.vBuffer.push(this.minX + deltaX * j); //Start from bottom left, to the right \r\n this.vBuffer.push(this.minY + deltaY * i); // i is constant, Y is constant\r\n this.vBuffer.push(0);\r\n \r\n this.nBuffer.push(0);\r\n this.nBuffer.push(0);\r\n this.nBuffer.push(0);\r\n\r\n }\r\n }\r\n \r\n // Populate face buffer (index into vertex buffer)\r\n for(var i = 0; i < this.div; i++){\r\n for(var j = 0; j < this.div; j++){\r\n var locBuffer = i * (this.div + 1) + j;\r\n // First triangle in a square\r\n this.fBuffer.push(locBuffer);\r\n this.fBuffer.push(locBuffer + 1);\r\n this.fBuffer.push(locBuffer + this.div + 1);\r\n \r\n // Second triangle in a square\r\n this.fBuffer.push(locBuffer + 1);\r\n this.fBuffer.push(locBuffer + this.div + 1 + 1);\r\n this.fBuffer.push(locBuffer + this.div + 1);\r\n }\r\n }\r\n \r\n //(Div + 1) is the size of the grid\r\n this.numVertices = this.vBuffer.length/3;\r\n this.numFaces = this.fBuffer.length/3;\r\n this.diamondSquare(this.div + 1);\r\n this.setNormal();\r\n}", "smooth(mesh, factor) {\n factor = factor === undefined ? 1.0 : factor;\n\n let cos = []\n let i = 0;\n\n for (let v of mesh.verts) {\n cos.push(new Vector3(v));\n v.index = i;\n\n i++;\n }\n\n let tmp = new Vector3();\n\n for (let v of mesh.verts) {\n if (v.edges.length != 2) {\n continue;\n }\n\n let tot = 0;\n v.zero();\n\n for (let e of v.edges) {\n let v2 = e.otherVertex(v);\n\n tot++;\n v.add(cos[v2.index]);\n }\n\n v.divScalar(tot);\n\n tmp.load(cos[v.index]).interp(v, factor);\n v.load(tmp);\n }\n }", "function processPathData(data) {\n let collection = [];\n let j;\n let arrayCollection = parsePathData(data);\n if (arrayCollection.length > 0) {\n for (let i = 0; i < arrayCollection.length; i++) {\n let ob = arrayCollection[i];\n let char = '';\n char = ob[0];\n switch (char.toLowerCase()) {\n case 'm':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, x: ob[j], y: ob[j + 1] });\n j = j + 1;\n if (char === 'm') {\n char = 'l';\n }\n else if (char === 'M') {\n char = 'L';\n }\n }\n break;\n case 'l':\n case 't':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, x: ob[j], y: ob[j + 1] });\n j = j + 1;\n }\n break;\n case 'h':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, x: ob[j] });\n }\n break;\n case 'v':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, y: ob[j] });\n }\n break;\n case 'z':\n collection.push({ command: char });\n break;\n case 'c':\n for (j = 1; j < ob.length; j++) {\n collection.push({\n command: char, x1: ob[j], y1: ob[j + 1], x2: ob[j + 2], y2: ob[j + 3], x: ob[j + 4], y: ob[j + 5]\n });\n j = j + 5;\n }\n break;\n case 's':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, x2: ob[j], y2: ob[j + 1], x: ob[j + 2], y: ob[j + 3] });\n j = j + 3;\n }\n break;\n case 'q':\n for (j = 1; j < ob.length; j++) {\n collection.push({ command: char, x1: ob[j], y1: ob[j + 1], x: ob[j + 2], y: ob[j + 3] });\n j = j + 3;\n }\n break;\n case 'a':\n for (j = 1; j < ob.length; j++) {\n collection.push({\n command: char, r1: ob[j], r2: ob[j + 1], angle: ob[j + 2], largeArc: ob[j + 3],\n sweep: ob[j + 4], x: ob[j + 5], y: ob[j + 6]\n });\n j = j + 6;\n }\n break;\n }\n }\n }\n return collection;\n}", "function prepare(vector){var vertex=vector.normalize().clone();vertex.index=that.vertices.push(vertex)-1;// Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.\nvar u=azimuth(vector)/2/Math.PI+0.5;var v=inclination(vector)/Math.PI+0.5;vertex.uv=new THREE.Vector2(u,1-v);return vertex;}// Approximate a curved face with recursively sub-divided triangles.", "function sheetMesh(response) {\r\n graphData = JSON.parse(response);\r\n var data = [\r\n {\r\n x: graphData.x,\r\n y: graphData.y,\r\n z: graphData.z,\r\n type: 'mesh3d',\r\n opacity: 0.8,\r\n color: 'rgb(171,154,164)'\r\n }\r\n ];\r\n\r\n var layout = {\r\n title: \"Mesh\",\r\n };\r\n\r\n Plotly.newPlot(\"meshPlot\", data, layout);\r\n}", "hPath(num, x, y){\n for(let p = 0; p < num; p++){\n path = paths.create(TILE_WIDTH * x + (TILE_WIDTH * p), TILE_HEIGHT * y, 'path');\n path.body.immovable = true;\n }\n }", "constructor(shape) {\n this.id = shape.id;\n this.type = shape.type;\n this.path = [];\n for (let i = 0; i < shape.path.length; i++) {\n this.path[i] = []\n for (let j = 0; j < 2; j++) {\n this.path[i][j] = shape.path[i][j];\n }\n }\n }", "constructor(using_flat_shading) {\n super(\"position\", \"normal\", \"texture_coord\");\n var a = 1 / Math.sqrt(3);\n if (!using_flat_shading) {\n // Method 1: A tetrahedron with shared vertices. Compact, performs better,\n // but can't produce flat shading or discontinuous seams in textures.\n this.arrays.position = Vec.cast(\n [0, 0, 0],\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]\n );\n this.arrays.normal = Vec.cast(\n [-a, -a, -a],\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 1]\n );\n this.arrays.texture_coord = Vec.cast([0, 0], [1, 0], [0, 1], [1, 1]);\n // Notice the repeats in the index list. Vertices are shared\n // and appear in multiple triangles with this method.\n this.indices.push(0, 1, 2, 0, 1, 3, 0, 2, 3, 1, 2, 3);\n } else {\n // Method 2: A tetrahedron with four independent triangles.\n this.arrays.position = Vec.cast(\n [0, 0, 0],\n [1, 0, 0],\n [0, 1, 0],\n [0, 0, 0],\n [1, 0, 0],\n [0, 0, 1],\n [0, 0, 0],\n [0, 1, 0],\n [0, 0, 1],\n [0, 0, 1],\n [1, 0, 0],\n [0, 1, 0]\n );\n\n // The essence of flat shading: This time, values of normal vectors can\n // be constant per whole triangle. Repeat them for all three vertices.\n this.arrays.normal = Vec.cast(\n [0, 0, -1],\n [0, 0, -1],\n [0, 0, -1],\n [0, -1, 0],\n [0, -1, 0],\n [0, -1, 0],\n [-1, 0, 0],\n [-1, 0, 0],\n [-1, 0, 0],\n [a, a, a],\n [a, a, a],\n [a, a, a]\n );\n\n // Each face in Method 2 also gets its own set of texture coords (half the\n // image is mapped onto each face). We couldn't do this with shared\n // vertices since this features abrupt transitions when approaching the\n // same point from different directions.\n this.arrays.texture_coord = Vec.cast(\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 0],\n [1, 0],\n [1, 1],\n [0, 0],\n [1, 0],\n [1, 1]\n );\n // Notice all vertices are unique this time.\n this.indices.push(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11);\n }\n }", "function face_vertices(bz, nface) {\n const n = bz.map(x => x.slice(0, 3))\n const d = bz.map(x => x[3])\n const vz = d[nface]\n \n // find a more suitable coordinate system\n const R = construct_basis_mat(n[nface])\n const RT = m3_transpose(R) // transpose==inverse since orthogonal matrix\n const np = n.map(ni => m3_mulv(RT, ni))\n\n let ps = []\n let rhs = [0.0, 0.0]\n for(let i = 0; i < bz.length; ++i) {\n\tfor(let j = i+1; j < bz.length; ++j) {\n\t if(i == nface || j == nface) continue\n\n\t // avoid creating a new array every time\n\t rhs[0] = d[i] - vz * np[i][2]\n\t rhs[1] = d[j] - vz * np[j][2]\n\t // np's are 3D but its faster to not slice them\n\t p = solve_system2(np[i], np[j], rhs)\n\t // check the solution is valid\n\t if(p == undefined) continue\n\t // and inside the BZ (change to usual coords first)\n\t const realp = m3_mulv(R, [...p, vz])\n\t if(! is_inside_half_space(realp, bz[nface]))\n\t\tconsole.error('should be at least part of its own half space')\n\t if(! is_inside_bz(realp, bz)) continue\n\n\t // now push it only if it is not too close from previously found vertices\n\t let duplicate = false\n\t for(let k = 0; k < ps.length; ++k) {\n\t\tif(v3_norm(v3_sub(ps[k], realp)) < 1e-8) {\n\t\t duplicate = true\n\t\t break\n\t\t}\n\t }\n\t if(! duplicate) ps.push(realp)\n\t}\n }\n\n return ps\n}", "function updateMeshesFromServerData() {\r\n //per ogni utente aggiunge la mano\r\n for (var userId in serverData) {\r\n if (!handMeshes[userId] && serverData[userId].hands.length) {\r\n handMeshes[userId] = [];\r\n var id = handMeshes[userId]\r\n console.log(id)\r\n \r\n \r\n for (var i = 0; i < 21; i++) {\r\n // 21 keypoints\r\n var { isPalm, next } = getLandmarkProperty(i);\r\n\r\n var obj = new THREE.Object3D(); // oggetto null che permette di ruotare e scalare tutto insieme\r\n\r\n // ad ogni articolazione viene associato un cilindro\r\n //var geometry = new THREE.CylinderGeometry( isPalm?5:10, 5, 1);\r\n var geometry = new THREE.BoxGeometry(5, 1, 5);\r\n //var material = new THREE.MeshNormalMaterial();\r\n var material = new THREE.MeshPhongMaterial({ color: 0xffffff });\r\n var mesh = new THREE.Mesh(geometry, material);\r\n\r\n mesh.rotation.x = Math.PI / 2;\r\n\r\n obj.add(mesh);\r\n scene.add(obj);\r\n handMeshes[userId].push(obj);\r\n \r\n }\r\n }\r\n }\r\n\r\n\r\n // se un utente esce dal server, la sua mano viene rimossa\r\n for (var userId in handMeshes) {\r\n if (!serverData[userId] || !serverData[userId].hands.length) {\r\n for (var i = 0; i < handMeshes[userId].length; i++) {\r\n scene.remove(handMeshes[userId][i]);\r\n }\r\n delete handMeshes[userId];\r\n }\r\n }\r\n \r\n \r\n xindex = handMeshes[userId][8].position.x\r\n yindex = handMeshes[userId][8].position.y\r\n xthumb = handMeshes[userId][4].position.x\r\n ythumb = handMeshes[userId][4].position.y\r\n \r\n \r\n \r\n\r\n // muove e orienta le mesh\r\n for (var userId in handMeshes) {\r\n if (!serverData[userId] || !serverData[userId].hands.length) {\r\n continue;\r\n }\r\n for (var i = 0; i < handMeshes[userId].length; i++) {\r\n var { isPalm, next } = getLandmarkProperty(i);\r\n\r\n var p0 = webcam2space(...serverData[userId].hands[0].landmarks[i]); // one end of the bone\r\n var p1 = webcam2space(...serverData[userId].hands[0].landmarks[next]); // the other end of the bone\r\n\r\n // punto medio\r\n var mid = p0.clone().lerp(p1, 0.5);\r\n handMeshes[userId][i].position.set(mid.x, mid.y, mid.z);\r\n //console.log( handMeshes[userId][8].position)\r\n \r\n // lunghezza\r\n handMeshes[userId][i].scale.z = p0.distanceTo(p1);\r\n // orientamento\r\n handMeshes[userId][i].lookAt(p1);\r\n }\r\n }\r\n}", "function PolyMesh() {\n this.vertices = [];\n this.edges = [];\n this.faces = [];\n this.components = [];\n this.needsDisplayUpdate = true;\n this.needsIndexDisplayUpdate = true;\n this.vertexBuffer = null;\n this.normalBuffer = null;\n this.indexBuffer = null;\n this.colorBuffer = null;\n this.drawer = null;\n \n /////////////////////////////////////////////////////////////\n //// ADD/REMOVE METHODS /////\n ///////////////////////////////////////////////////////////// \n \n this.addVertex = function(P, color) {\n vertex = new MeshVertex(P, this.vertices.length);\n vertex.color = (typeof color !== 'undefined' ? color : null);\n this.vertices.push(vertex);\n return vertex;\n }\n \n //Create an edge between v1 and v2 and return it\n //This function assumes v1 and v2 are valid vertices in the mesh\n this.addEdge = function(v1, v2) {\n edge = new MeshEdge(v1, v2, this.edges.length);\n this.edges.push(edge);\n v1.edges.push(edge);\n v2.edges.push(edge);\n return edge;\n }\n \n //Given a list of pointers to mesh vertices in CCW order\n //create a face object from them\n this.addFace = function(meshVerts) {\n var vertsPos = Array(meshVerts.length);\n for (var i = 0; i < vertsPos.length; i++) {\n vertsPos[i] = meshVerts[i].pos;\n }\n if (!arePlanar(vertsPos)) {\n console.log(\"Error (PolyMesh.addFace): Trying to add mesh face that is not planar\\n\")\n for (var i = 0; i < vertsPos.length; i++) {\n console.log(vecStr(vertsPos[i]) + \", \");\n }\n return null;\n }\n if (!are2DConvex(vertsPos)) {\n console.log(\"Error (PolyMesh.addFace): Trying to add mesh face that is not convex\\n\");\n for (var i = 0; i < vertsPos.length; i++) {\n console.log(vecStr(vertsPos[i]) + \", \");\n }\n return null;\n }\n var face = new MeshFace(this.faces.length);\n face.startV = meshVerts[0];\n for (var i = 0; i < meshVerts.length; i++) {\n var v1 = meshVerts[i];\n var v2 = meshVerts[(i+1)%meshVerts.length];\n var edge = getEdgeInCommon(v1, v2);\n if (edge === null) {\n edge = this.addEdge(v1, v2);\n }\n face.edges.push(edge);\n edge.addFace(face, v1); //Add pointer to face from edge\n }\n this.faces.push(face);\n return face;\n }\n \n //Remove the face from the list of faces and remove the pointers\n //from all edges to this face\n this.removeFace = function(face) {\n //Swap the face to remove with the last face (O(1) removal)\n this.faces[face.ID] = this.faces[this.faces.length-1];\n this.faces[face.ID].ID = face.ID //Update ID of swapped face\n face.ID = -1;\n this.faces.pop();\n //Remove pointers from all of the face's edges\n for (var i = 0; i < faces.edges.length; i++) {\n edge.removeFace(faces[i]);\n }\n }\n \n //Remove this edge from the list of edges and remove \n //references to the edge from both of its vertices\n //(NOTE: This function is not responsible for cleaning up\n //faces that may have used this edge; that is up to the client)\n this.removeEdge = function(edge) {\n //Swap the edge to remove with the last edge\n this.edges[edge.ID] = this.edges[this.edges.length-1];\n this.edges[edge.ID].ID = edge.ID; //Update ID of swapped face\n edge.ID = -1;\n this.edges.pop();\n //Remove pointers from the two vertices that make up this edge\n var i = edge.v1.edges.indexOf(edge);\n edge.v1.edges[i] = edge.v1.edges[edge.v1.edges.length-1];\n edge.v1.edges.pop();\n i = edge.v2.edges.indexOf(edge);\n edge.v2.edges[i] = edge.v2.edges[edge.v2.edges.length-1];\n edge.v2.edges.pop();\n }\n \n //Remove this vertex from the list of vertices\n //NOTE: This function is not responsible for cleaning up any of\n //the edges or faces that may have used this vertex\n this.removeVertex = function(vertex) {\n this.vertices[vertex.ID] = this.vertices[this.vertices.length-1];\n this.vertices[vertex.ID].ID = vertex.ID;\n vertex.ID = -1;\n this.vertices.pop();\n }\n \n //Make a clone of this mesh in memory\n this.Clone = function() {\n newMesh = new PolyMesh();\n for (var i = 0; i < this.vertices.length; i++) {\n newMesh.addVertex(this.vertices[i].pos, this.vertices[i].color);\n }\n for (var i = 0; i < this.faces.length; i++) {\n vertices = this.faces[i].getVertices();\n for (var j = 0; j < vertices.length; j++) {\n vertices[j] = newMesh.vertices[vertices[j].ID];\n }\n newMesh.addFace(vertices);\n }\n return newMesh;\n }\n \n \n /////////////////////////////////////////////////////////////\n //// GEOMETRY METHODS /////\n /////////////////////////////////////////////////////////////\n\n //Transformations are simple because geometry information is only\n //stored in the vertices\n this.Transform = function(matrix) {\n for (var i = 0; i < this.vertices.length; i++) {\n vec3.transformMat4(this.vertices[i].pos, this.vertices[i].pos, matrix);\n }\n this.needsDisplayUpdate = true;\n this.needsIndexDisplayUpdate = true;\n }\n \n this.Translate = function(dV) {\n for (var i = 0; i < this.vertices.length; i++) {\n vec3.add(this.vertices[i].pos, this.vertices[i].pos, dV);\n }\n this.needsDisplayUpdate = true;\n this.needsIndexDisplayUpdate = true;\n }\n \n this.Scale = function(dx, dy, dz) {\n for (var i = 0; i < this.vertices.length; i++) {\n this.vertices[i].pos[0] *= dx;\n this.vertices[i].pos[1] *= dy;\n this.vertices[i].pos[2] *= dz;\n }\n }\n\n this.getCentroid = function() {\n center = vec3.fromValues();\n for (var i = 0; i < this.vertices.length; i++) {\n vec3.add(center, center, vertices[i].pos);\n }\n vec3.scale(center, center, 1.0/this.vertices.length);\n return center;\n }\n \n this.getBBox = function() {\n if (this.vertices.length == 0) {\n return AABox3D(0, 0, 0, 0, 0, 0);\n }\n var P0 = this.vertices[0].pos;\n var bbox = new AABox3D(P0[0], P0[0], P0[1], P0[1], P0[2], P0[2]);\n for (var i = 0; i < this.vertices.length; i++) {\n bbox.addPoint(this.vertices[i].pos);\n }\n return bbox;\n } \n \n /////////////////////////////////////////////////////////////\n //// LAPLACIAN MESH METHODS /////\n /////////////////////////////////////////////////////////////\n function LaplaceBeltramiWeightFunc(v1, v2, v3, v4) {\n var w = 0.0;\n if (!(v3 === null)) {\n w = w + getCotangent(v1.pos, v2.pos, v3.pos);\n }\n if (!(v4 === null)) {\n w = w + getCotangent(v1.pos, v2.pos, v4.pos);\n }\n //TODO: Fix area scaling\n //return (3.0/(2.0*v1.getOneRingArea()))*w;\n return w;\n }\n \n function UmbrellaWeightFunc(v1, v2, v3, v4) {\n //Very simple function that returns just 1 for the umbrella weights\n return 1;\n }\n \n //Helper function for Laplacian mesh that figures out the vertex on the \n //other side of an edge on a triangle\n function getVertexAcross(v1, v2, f) {\n var Vs = f.getVertices();\n if (Vs.length != 3) {\n console.log(\"Warning(getLaplacianSparseMatrix): Expecting 3 vertices per face\");\n return null;\n }\n var idx = 0;\n if ( (v1.ID != Vs[1].ID) && (v2.ID != Vs[1].ID) ) {\n idx = 1;\n }\n else if ( (v1.ID != Vs[2].ID) && (v2.ID != Vs[2].ID) ) {\n idx = 2;\n }\n return Vs[idx];\n }\n \n //Note: This function assumes a triangle mesh \n this.getLaplacianSparseMatrix = function(weightFunction) {\n var N = this.vertices.length;\n var cols = Array(N); //Store index of row for each element in each column\n var colsv = Array(N); //Store value of each element in each column\n for (var i = 0; i < N; i++) {\n cols[i] = [];\n colsv[i] = [];\n }\n //Loop through all vertices and add a row for each\n for (var i = 0; i < N; i++) {\n var v1 = this.vertices[i];\n //Precompute 1-ring area\n //var oneRingArea = this.vertices[i].getOneRingArea();\n for (var ei = 0; ei < v1.edges.length; ei++) {\n var e = v1.edges[ei];\n var v2 = e.vertexAcross(v1);\n var j = v2.ID;\n var v3 = null;\n var v4 = null;\n if (!(e.f1 === null)) {\n v3 = getVertexAcross(v1, v2, e.f1);\n }\n if (!(e.f2 === null)) {\n v4 = getVertexAcross(v1, v2, e.f2);\n }\n var wij = weightFunction(v1, v2, v3, v4);\n totalWeight += wij;\n cols[j].push(i);\n colsv[j].push(-wij);\n }\n cols[i].push(i);\n colsv[i].push(totalWeight)\n }\n //TODO: Parallel sort cols, colsv by the indices in cols, then setup\n //NumericJS sparse matrix\n }\n \n /////////////////////////////////////////////////////////////\n //// INPUT/OUTPUT METHODS /////\n /////////////////////////////////////////////////////////////\n this.loadFile = function(filename) {\n var textdata = \"\";\n $.ajax({\n async: false,\n url: filename,\n success: function (data) {\n textdata = data;\n },\n dataType: 'text'\n });\n this.loadFileFromLines(textdata.split(\"\\n\"));\n }\n \n this.loadFileFromLines = function(lines) {\n if (lines.length == 0) {\n return;\n }\n var fields = lines[0].match(/\\S+/g);\n if (fields[0].toUpperCase() == \"OFF\" || fields[0].toUpperCase() == \"COFF\") {\n this.loadOffFile(lines);\n }\n else {\n console.log(\"Unsupported file type \" + fields[0] + \" for loading mesh\");\n }\n this.needsDisplayUpdate = true;\n this.needsIndexDisplayUpdate = true;\n } \n \n this.loadOffFile = function(lines) {\n this.vertices = [];\n this.edges = [];\n this.faces = [];\n this.components = [];\n var nVertices = 0;\n var nFaces = 0;\n var nEdges = 0;\n var face = 0;\n var vertex = 0;\n var divideColor = false;\n var fieldNum = 0;\n for (var line = 0; line < lines.length; line++) {\n //http://blog.tompawlak.org/split-string-into-tokens-javascript\n var fields = lines[line].match(/\\S+/g);\n if (fields === null) { //Blank line\n continue;\n }\n if (fields[0].length == 0) {\n continue;\n }\n if (fields[0][0] == \"#\" || fields[0][0] == \"\\0\" || fields[0][0] == \" \") {\n continue;\n }\n //Reading header\n if (nVertices == 0) {\n if (fields[0] == \"OFF\" || fields[0] == \"COFF\") {\n if (fields.length > 2) {\n nVertices = parseInt(fields[1]);\n nFaces = parseInt(fields[2]);\n nEdges = parseInt(fields[3]);\n }\n }\n else {\n if (fields.length >= 3) {\n nVertices = parseInt(fields[0]);\n nFaces = parseInt(fields[1]);\n nEdges = parseInt(fields[2]); \n }\n else if (nVertices == 0) {\n console.log(\"Error parsing OFF file: Not enough fields for nVertices, nFaces, nEdges\");\n }\n }\n }\n //Reading vertices\n else if (vertex < nVertices) {\n if (fields.length < 3) {\n console.log(\"Error parsing OFF File: Too few fields on a vertex line\");\n continue;\n }\n P = vec3.fromValues(parseFloat(fields[0]), parseFloat(fields[1]), parseFloat(fields[2]));\n color = null;\n if (fields.length >= 6) {\n //There is color information\n var color;\n if (divideColor) {\n color = vec3.fromValues(parseFloat(fields[3])/255.0, parseFloat(fields[4])/255.0, parseFloat(fields[5])/255.0);\n }\n else {\n color = vec3.fromValues(parseFloat(fields[3]), parseFloat(fields[4]), parseFloat(fields[5]));\n }\n }\n this.addVertex(P, color);\n vertex++;\n }\n //Reading faces\n else if (face < nFaces) {\n if (fields.length == 0) {\n continue;\n }\n //Assume the vertices are specified in CCW order\n var NVertices = parseInt(fields[0]);\n if (fields.length < NVertices+1) {\n console.log(\"Error parsing OFF File: Not enough vertex indices specified for a face of length \" + NVertices);\n }\n var verts = Array(NVertices);\n for (var i = 0; i < NVertices; i++) {\n verts[i] = this.vertices[parseInt(fields[i+1])];\n }\n this.addFace(verts);\n face++;\n }\n }\n for (var i = 0; i < this.vertices.length; i++) {\n if (!(this.vertices[i].color === null)) {\n if (this.vertices[i].color[0] > 1) {\n //Rescale colors\n for (var k = 0; k < this.vertices.length; k++) {\n vec3.scale(this.vertices[i].color, this.vertices[i].color, 1.0/255.0);\n }\n break;\n }\n }\n }\n console.log(\"Succesfully loaded OFF File with \" + this.vertices.length + \" vertices and \" + this.faces.length + \" faces\");\n }\n \n \n /////////////////////////////////////////////////////////////\n //// RENDERING /////\n ///////////////////////////////////////////////////////////// \n \n //Copy over vertex and triangle information to the GPU\n this.updateBuffers = function(gl) {\n //Check to see if buffers need to be initialized\n if (this.vertexBuffer === null) {\n this.vertexBuffer = gl.createBuffer();\n //console.log(\"New vertex buffer: \" + this.vertexBuffer);\n }\n if (this.normalBuffer === null) {\n this.normalBuffer = gl.createBuffer();\n //console.log(\"New normal buffer: \" + this.normalBuffer);\n }\n if (this.indexBuffer === null) {\n this.indexBuffer = gl.createBuffer();\n //console.log(\"New index buffer: \" + this.indexBuffer);\n }\n if (this.colorBuffer === null) {\n this.colorBuffer = gl.createBuffer();\n //console.log(\"New color buffer: \" + this.colorBuffer);\n }\n //Vertex Buffer\n var V = new Float32Array(this.vertices.length*3);\n for (var i = 0; i < this.vertices.length; i++) {\n V[i*3] = this.vertices[i].pos[0];\n V[i*3+1] = this.vertices[i].pos[1];\n V[i*3+2] = this.vertices[i].pos[2];\n }\n gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, V, gl.STATIC_DRAW);\n this.vertexBuffer.itemSize = 3;\n this.vertexBuffer.numItems = this.vertices.length;\n \n //Normal buffer\n //TODO: NaNs in normals\n var N = new Float32Array(this.vertices.length*3);\n for (var i = 0; i < this.vertices.length; i++) {\n var n = this.vertices[i].getNormal();\n N[i*3] = n[0];\n N[i*3+1] = n[1];\n N[i*3+2] = n[2];\n }\n gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, N, gl.STATIC_DRAW);\n this.normalBuffer.itemSize = 3;\n this.normalBuffer.numItems = this.vertices.length;\n \n //Color buffer\n var C = new Float32Array(this.vertices.length*3);\n for (var i = 0; i < this.vertices.length; i++) {\n if (!(this.vertices[i].color === null)) {\n C[i*3] = this.vertices[i].color[0];\n C[i*3+1] = this.vertices[i].color[1];\n C[i*3+2] = this.vertices[i].color[2];\n }\n else {\n //Default color is greenish gray\n C[i*3] = 0.5;\n C[i*3+1] = 0.55;\n C[i*3+2] = 0.5;\n } \n }\n gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, C, gl.STATIC_DRAW);\n this.colorBuffer.itemSize = 3;\n this.colorBuffer.numItems = this.vertices.length;\n \n //Index Buffer\n //First figure out how many triangles need to be used\n var NumTris = 0;\n for (var i = 0; i < this.faces.length; i++) {\n NumTris += this.faces[i].edges.length - 2;\n }\n var I = new Uint16Array(NumTris*3);\n var i = 0;\n var faceIdx = 0;\n //Now copy over the triangle indices\n while (i < NumTris) {\n var verts = this.faces[faceIdx].getVertices();\n for (var t = 0; t < verts.length - 2; t++) {\n I[i*3] = verts[0].ID;\n I[i*3+1] = verts[t+1].ID;\n I[i*3+2] = verts[t+2].ID;\n i++;\n }\n faceIdx++;\n }\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, I, gl.STATIC_DRAW);\n this.indexBuffer.itemSize = 1;\n this.indexBuffer.numItems = 3*NumTris;\n }\n \n //Draw the surface normals as a bunch of blue line segments\n //PMatrix: The projection matrix\n //mvMatrix: The modelview matrix\n //This assumes the upper left 3x3 matrix of the modelview matrix is orthogonal,\n //which it will be if mvMatrix is describing the camera\n this.drawNormals = function(gl, shaders, pMatrix, mvMatrix) {\n if (this.needsDisplayUpdate) {\n //Figure out scale of normals; make 1/20th of the bounding box diagonal\n var dR = 0.05*this.getBBox().getDiagLength();\n for (var i = 0; i < this.vertices.length; i++) {\n var P1 = this.vertices[i].pos;\n var P2 = this.vertices[i].getNormal();\n vec3.scaleAndAdd(P2, P1, P2, dR);\n this.drawer.drawLine(P1, P2, [0.0, 0.0, 1.0]); \n }\n }\n this.drawer.repaint(pMatrix, mvMatrix);\n }\n\n //Draw the surface edges as a bunch of blue line segments\n //PMatrix: The projection matrix\n //mvMatrix: The modelview matrix\n this.drawEdges = function(gl, shaders, pMatrix, mvMatrix) {\n if (this.needsDisplayUpdate) {\n for (var i = 0; i < this.edges.length; i++) {\n var P1 = this.edges[i].v1.pos;\n var P2 = this.edges[i].v2.pos;\n this.drawer.drawLine(P1, P2, [0.0, 0.0, 1.0]); \n }\n }\n this.drawer.repaint(pMatrix, mvMatrix);\n }\n\n\n //Draw the surface points as a red scatterplot\n //PMatrix: The projection matrix\n //mvMatrix: The modelview matrix\n this.drawPoints = function(gl, shaders, pMatrix, mvMatrix) {\n if (this.needsDisplayUpdate) {\n for (var i = 0; i < this.vertices.length; i++) {\n this.drawer.drawPoint(this.vertices[i].pos, [1.0, 0.0, 0.0]); \n }\n }\n this.drawer.repaint(pMatrix, mvMatrix);\n }\n \n //shaders: Shader programs, pMatrix: Perspective projection matrix, mvMatrix: Modelview matrix\n //ambientColor, light1Pos, light2Pos, lightColor are all vec3s\n //drawNormals: Whether or not to draw blue line segments for the vertex normals\n //shaderType: The type of shading to use\n FLAT_SHADING = 0;\n COLOR_SHADING = 1;\n this.render = function(gl, shaders, pMatrix, mvMatrix, ambientColor, light1Pos, light2Pos, lightColor, doDrawNormals, doDrawEdges, doDrawPoints, shaderType) {\n /*console.log(\"this.vertexBuffer = \" + this.vertexBuffer);\n console.log(\"this.normalBuffer = \" + this.normalBuffer);\n console.log(\"this.indexBuffer = \" + this.indexBuffer);\n console.log(\"this.colorBuffer = \" + this.colorBuffer);*/\n if (this.vertices.length == 0) {\n return;\n }\n if (this.needsDisplayUpdate) {\n this.updateBuffers(gl);\n }\n if (this.vertexBuffer === null) {\n console.log(\"Warning: Trying to render when buffers have not been initialized\");\n return;\n }\n \n //Figure out which shader to use\n var sProg; \n if (shaderType == FLAT_SHADING) {\n sProg = shaders.flatColorShader;\n }\n else if (shaderType == COLOR_SHADING) {\n sProg = shaders.colorShader;\n }\n else {\n console.log(\"ERROR: Incorrect shader specified for mesh rendering\");\n return;\n }\n gl.useProgram(sProg);\n \n //Step 1: Bind all buffers\n //Vertex position buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);\n gl.vertexAttribPointer(sProg.vPosAttrib, this.vertexBuffer.itemSize, gl.FLOAT, false, 0, 0);\n if (shaderType == COLOR_SHADING) {\n //Normal buffer (only relevant if lighting)\n gl.bindBuffer(gl.ARRAY_BUFFER, this.normalBuffer);\n gl.vertexAttribPointer(sProg.vNormalAttrib, this.normalBuffer.itemSize, gl.FLOAT, false, 0, 0);\n //Color buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);\n gl.vertexAttribPointer(sProg.vColorAttrib, this.colorBuffer.itemSize, gl.FLOAT, false, 0, 0);\n }\n //Index buffer\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);\n \n //Step 2: Scale, translate, and rotate the mesh appropriately on top of whatever \n //world transformation has already been passed along in mvMatrix, by sending over\n //the matrices to the GPU as uniforms. Also send over lighting variables as uniforms\n gl.uniformMatrix4fv(sProg.pMatrixUniform, false, pMatrix);\n gl.uniformMatrix4fv(sProg.mvMatrixUniform, false, mvMatrix);\n \n if (shaderType == COLOR_SHADING) {\n //Compute normal transformation matrix from world modelview matrix\n //(transpose of inverse of upper 3x3 part)\n nMatrix = mat3.create();\n mat3.normalFromMat4(nMatrix, mvMatrix);\n gl.uniformMatrix3fv(sProg.nMatrixUniform, false, nMatrix);\n \n gl.uniform3fv(sProg.ambientColorUniform, ambientColor);\n gl.uniform3fv(sProg.light1PosUniform, light1Pos);\n gl.uniform3fv(sProg.light2PosUniform, light2Pos);\n gl.uniform3fv(sProg.lightColorUniform, lightColor);\n }\n else if (shaderType == FLAT_SHADING) {\n gl.uniform4fv(sProg.vColorUniform, vec4.fromValues(1, 0.5, 0.5, 1));\n }\n \n //Step 3: Render the mesh\n gl.drawElements(gl.TRIANGLES, this.indexBuffer.numItems, gl.UNSIGNED_SHORT, 0);\n \n //Step 4: Draw lines and points for vertices, edges, and normals if requested\n if (this.needsDisplayUpdate) {\n if (this.drawer === null) {\n this.drawer = new SimpleDrawer(gl, shaders);\n }\n this.drawer.reset();\n }\n if (doDrawNormals) {\n this.drawNormals(gl, shaders, pMatrix, mvMatrix);\n }\n if (doDrawEdges) {\n this.drawEdges(gl, shaders, pMatrix, mvMatrix);\n }\n if (doDrawPoints) {\n this.drawPoints(gl, shaders, pMatrix, mvMatrix);\n }\n \n if (this.needsDisplayUpdate) {\n //By the time rendering is done, there should not be a need to update\n //the display unless this flag is changed again externally\n this.needsDisplayUpdate = false;\n }\n }\n}", "function reconstructProjectOnNormalDirection(p,points){\n //p to 3D on the floor plane\n var p3=Position3D(p);\n var dir=p3.add(DirectionalVector);\n var dir2D=threeDToScreenSpace(dir);\n dir2D.sub(p);\n dir2D.normalize();\n var n=points.length;\n var vertices=[];\n for(var i=0;i<n;i++){\n var toproject=points[i].clone().sub(p);\n var displacement=dir2D.clone().multiplyScalar(toproject.dot(dir2D));\n var v2d=p.clone().add(displacement);\n vertices.push(project2DToPlane(v2d,p3,new THREE.Vector3(0,1,0)));\n }\n var geometry=new THREE.Geometry();\n for(var i=0;i<vertices.length-1;i++){\n geometry.vertices.push(vertices[i],vertices[i+1]);\n }\n return [geometry,vertices];\n}", "function makeCube(x, y, z) {\n return [\n { x: x - 1, y: y, z: z + 1 }, // FRONT TOP LEFT\n { x: x - 1, y: 0, z: z + 1 }, // FRONT BOTTOM LEFT\n { x: x + 1, y: 0, z: z + 1 }, // FRONT BOTTOM RIGHT\n { x: x + 1, y: y, z: z + 1 }, // FRONT TOP RIGHT\n { x: x - 1, y: y, z: z - 1 }, // BACK TOP LEFT\n { x: x - 1, y: 0, z: z - 1 }, // BACK BOTTOM LEFT\n { x: x + 1, y: 0, z: z - 1 }, // BACK BOTTOM RIGHT\n { x: x + 1, y: y, z: z - 1 }, // BACK TOP RIGHT\n ];\n }", "function voxToGeometry(vox, mesher=stupid){\n\t// create vertices and faces\n\tlet data = mesher(\n\t\tvox.flat(2),\n\t\t[vox[0][0].length, vox[0].length, vox.length]\n\t)\n\t// create THREE.JS mesh\n\tlet geometry = new THREE.Geometry();\n\tdata.vertices.forEach(e => geometry.vertices.push(\n\t\tnew THREE.Vector3(...e)\n\t))\n\tlet vertexLength = (v,w) => Math.hypot(...[v,w]\n\t\t.map(e => data.vertices[e])\n\t\t.reduce((a,b) => a.map((_,i) => a[i]-b[i]))\n\t)\n\tdata.faces.forEach((e,i) =>{\n\t\t// find orthodognal vector to this face\n\t\t// let v = data.vertices[e[0]]\n\t\tlet f = [\n\t\t\tnew THREE.Face3(e[2],e[3],e[0]),\n\t\t\tnew THREE.Face3(e[1],e[2],e[0]),\n\t\t]\n\t\tlet len = {\n\t\t\twidth: vertexLength(e[0],e[1]),\n\t\t\theight: vertexLength(e[0],e[3])\n\t\t}\n\t\tgeometry.faces.push(...f)\n\t\tlet w = len.width;\n\t\tlet h = len.height;\n\t\tgeometry.faceVertexUvs[ 0 ].push(\n\t\t\t[\n\t\t\t\tnew THREE.Vector2( w, h ),\n\t\t\t\tnew THREE.Vector2( 0, h ),\n\t\t\t\tnew THREE.Vector2( 0, 0 ),\n\t\t\t],\n\t\t\t[\n\t\t\t\tnew THREE.Vector2( w, 0 ),\n\t\t\t\tnew THREE.Vector2( w, h ),\n\t\t\t\tnew THREE.Vector2( 0, 0 ),\n\t\t\t]\n\t\t);\n\t})\n\tgeometry.verticesNeedUpdate = true;\n\tgeometry.elementsNeedUpdate = true;\n\tgeometry.normalsNeedUpdate = true;\n\tgeometry.computeBoundingBox();\n\tgeometry.computeBoundingSphere();\n\treturn geometry\n}" ]
[ "0.5992161", "0.58979166", "0.5884936", "0.58274984", "0.5763738", "0.56672543", "0.56551665", "0.55506104", "0.54741466", "0.5468343", "0.54658914", "0.54273283", "0.5415273", "0.5412148", "0.53630483", "0.53531784", "0.53108186", "0.527755", "0.5251173", "0.52357954", "0.5221285", "0.5182322", "0.5175012", "0.5166614", "0.513855", "0.5127578", "0.5107844", "0.51053876", "0.51053876", "0.51043636", "0.50969654", "0.5074173", "0.5055783", "0.50502247", "0.5045243", "0.5043781", "0.5042083", "0.5027652", "0.5027652", "0.50168777", "0.50161946", "0.50046015", "0.49892664", "0.4982331", "0.49738586", "0.49609807", "0.49595198", "0.49440986", "0.4941922", "0.4941298", "0.49342358", "0.49151435", "0.49144605", "0.49144605", "0.4897907", "0.48969737", "0.48860276", "0.4883647", "0.48759067", "0.48742425", "0.4832414", "0.4827651", "0.4825978", "0.48254517", "0.4824519", "0.48219928", "0.4812312", "0.48069334", "0.48047575", "0.47959474", "0.4791216", "0.47881848", "0.47844785", "0.47755882", "0.47729236", "0.47716588", "0.47712722", "0.47635725", "0.47566184", "0.4738591", "0.47371456", "0.47313422", "0.473077", "0.47303486", "0.4726341", "0.4726341", "0.4715569", "0.47146022", "0.4704964", "0.47023237", "0.47006932", "0.4699703", "0.46996176", "0.46957022", "0.46956313", "0.469519", "0.46948403", "0.4693579", "0.46903914", "0.46899658" ]
0.74383754
0
$("a[title='Show details']").css( "border", "3px double red" );
function createLink(label,link){ var newLink=$("<a>", { title: label, href: link, class: "toolbox_button" }).append( label ); return newLink; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function highlightCorrect(elem)\n{\n $(elem).css(\"border-color\", \"green\");\n}", "function BorderClick(){\n \tjQuery (\".boxes\").css(\"border-bottom\", \"6px solid black\")\n }", "function highlightMissing(elem)\n{\n $(elem).css(\"border-color\", \"red\");\n}", "function questionSixAction() {\r\n $('input[name^=\"txt\"]').css(\"border\", \"solid green\");\r\n}", "function select() {\n $(this).parent().css('border', '2px solid blue');\n }", "function addBorder(element) {\n element.style.border = \"2px dashed #F76300\";\n}", "function redBorder(element){\n element.style.borderColor = 'red';\n}", "function addSpecialCss(){ \n $(this).bind(\"focus\",function(){\n $(this).css(\"border-color\",\"orange\");\n });\n $(this).bind(\"blur\",function(){\n $(this).css(\"border-color\",\"\");\n });\n}", "function setCompOrange() {\n $(\".ePic\").css({ \"border-color\": \"orange\" });\n}", "function letsJQuery(){ \r\n\top = $('A[class=bigusername]:first').html();\r\n\t$('A[class=bigusername]').each(function(i){\r\n\t\tif($(this).html()==op){\r\n\t\t\t$(this).parents('table:first')\r\n\t\t\t.css(\r\n\t\t\t\t{\r\n\t\t\t\t\t'background-color' : 'rgb(128, 128, 128)'\r\n\t\t\t\t}\r\n\t\t\t);\r\n\t\t\t\r\n\t\t\t$(this).parents('TD[nowrap=nowrap]')\r\n\t\t\t.css(\r\n\t\t\t\t{\r\n\t\t\t\t\t'background-color' : 'black'\r\n\t\t\t\t}\r\n\t\t\t);\r\n\t\t}\r\n\t});\r\n}", "function questionFiveAction() {\r\n $('#myDiv').find('input[type=\"text\"]').css(\"border\", \"solid red\");\r\n}", "function main() {\r\n$(\".md a\").each(function(){\r\n\tif($(this).attr(\"title\")!=\"\")\r\n\t{\r\n\t\t$(this).wrap(\"<span'></span>\");\r\n\t\t$(this).parent().html($(this).parent().html() + \"<span style='background-color:skyblue;border:1px solid black;font-weight:bold;padding:0 4px 0 4px;'>\" + $(this).attr(\"title\") + \"</span>\");\r\n\t}\r\n})\r\n}", "function showTab() {\n var url = window.location.href;\n if(url.indexOf('/get_started/why_mxnet') != -1) return;\n for(var i = 0; i < TITLE.length; ++i) {\n if(url.indexOf(TITLE[i]) != -1) {\n var tab = $($('#main-nav').children().eq(i));\n if(!tab.is('a')) tab = tab.find('a').first();\n tab.css('border-bottom', '3px solid');\n }\n }\n}", "get summaryCheckoutButton () { return $(\"div[id='center_column']\").$(\"a[title='Proceed to checkout']\")}", "function setActiveStyleSheet(title) {\n\t\tvar i, a, main;\n\t\t// mengambil setiap elemen link\n\t\tfor(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n\t\t\t// jika terdapat atribut rel dari elemen yang berisi string style\n\t\t\t// dan punya atribut title maka \n\t\t\tif(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\n\t\t\t\ta.disabled = true; // elemen akan disable\n\t\t\t\t//jika atribut elemen link sama dengan title css maka disable untuk \n\t\t\t\t// stylesheet tersebut adalah false\n\t\t\t\tif(a.getAttribute(\"title\") == title) a.disabled = false;\n\t \t}\n\t\t}\n\t}", "function setUserBlue() {\n $(\".hPic\").css({ \"border-color\": \"blue\" });\n}", "function colorDefault(dato){\n $('#' + dato).css({\n border: \"1px solid #999\"\n });\n}", "function mouseOverlink(){\n // Changed the color and background color in this function\n $(this).css('color', 'lime').css('background-color','blue');\n}", "function highlight(id)\n{\n\t$(\".auto_option\").css({'padding':'5px','border':'0px','color':'#000'});\n\tvar sel = $(\"#\"+id);\n\tif(sel)\n\t{\n\t\tsel.css({'padding':'4px','border':'1px solid #333','color':'#333'});\n\t\treturn true;\t\n\t}\n\telse return false;\n}", "function setActiveStyleSheet(title) {\r\n var i, a, main;\r\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\r\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1\r\n && a.getAttribute(\"title\")) {\r\n a.disabled = true;\r\n if(a.getAttribute(\"title\") == title) a.disabled = false;\r\n }\r\n }\r\n}", "function errorRedBorder(element) {\n element.style.borderColor = \"rgb(217,83,79)\";\n element.style.borderWidth = \"2px\";\n}", "function highlight(ctl, msg) {\r\n ctl.css('border', '2px solid red')\r\n .parent()\r\n .append('<span id=\"' + ctl.attr('id') + prefix + '\" style=\"color:red;\">' + msg + '</span>');\r\n }", "function setActiveStyleSheet(title) {\r\n var i, a, main;\r\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\r\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\r\n a.disabled = true;\r\n if(a.getAttribute(\"title\") == title) a.disabled = false;\r\n }\r\n }\r\n}", "function visibleSelect(current){\r\n\tcurrent.style.border = \"2px solid\";\r\n}", "function letsJQuery() {\r\n alert(\"Loaded!\");\r\n $(\"a[id*='.editLink']\").alert(\"Editing an event!\");\r\n}", "function cambiarColor(dato){\n $('#' + dato).css({\n border: \"3px solid #dd5144\"\n });\n}", "function setActiveStyleSheet(title) {\n var i, a, main;\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\n a.disabled = true;\n if(a.getAttribute(\"title\") == title) a.disabled = false;\n }\n }\n}", "function validateRankingQuestion(dis, err_msg){\n var id = dis.id.split('[')[0];\n $('div.ranking-question-box-left#'+id).css('border', '1px solid red');\n console.log(err_msg + ' ' +id);\n}", "function setCompGray() {\n $(\".ePic\").css({ \"border-color\": \"darkgray\" });\n}", "function highlightClickedOption(clickedSquareIdCookie){\n //console.log('clickedSquareIdCookie: ', clickedSquareIdCookie);\n $('#'+clickedSquareIdCookie).css(\"border-color\", \"#e12522\");\n $('#'+clickedSquareIdCookie).html('<i class=\"fa fa-check\" aria-hidden=\"true\"></i>').css(\n { 'display' : 'table-cell', \n 'text-align' : 'center', \n 'padding-top': '10px' , \n 'font-size': '20px' , \n 'padding-top': '10px',\n 'color': '#e12522'\n });\n}", "function operatorHighlight(value){\n\t\tvalue.css({\"border\": \"2px solid black\"});\n\t}", "function leNav(ihref){\n $(\".detailContent .leftNav li a[href^='\"+ihref+\"']\").addClass(\"on\");\n}", "function showBiblio() {\n $(this).children(\"#full_biblio\").css('position', 'absolute').css('text-decoration', 'underline')\n $(this).children(\"#full_biblio\").css('background', 'LightGray')\n $(this).children(\"#full_biblio\").css('box-shadow', '5px 5px 15px #C0C0C0')\n $(this).children(\"#full_biblio\").css('display', 'inline')\n}", "_titleColorToDark(){\n\t\tjQuery('#'+this.rank).css(\"color\", 'rgb(13, 87, 107)');\n\t}", "function inputBorderStyling() {\n $('.tagInputOverview').css({\n 'border-color': 'red',\n 'outline': '0'\n });\n}", "function questionTenAction() {\r\n $('div#myDiv span.info').css(\"color\", \"violet\");\r\n}", "function setTabActive(tab_id) {\r\n\r\n $(\"#\" + tab_id).css(\"color\", '#CC6600');\r\n $(\"#\" + tab_id).css(\"background-color\", '#f1ede3');\r\n $(\"#\" + tab_id).css(\"text-decoration\", 'underline');\r\n $(\"#\" + tab_id).parent().css(\"background-color\", '#f1ede3');\r\n $(\"#\" + tab_id).parent().css(\"border-left\", '1px solid #888888');\r\n $(\"#\" + tab_id).parent().css(\"border-right\", '1px solid #888888');\r\n $(\"#\" + tab_id).parent().css(\"border-top\", '1px solid #888888');\r\n $(\"#\" + tab_id).parent().css(\"border-bottom\", '1px solid #888888');\r\n}", "function green (){\n $('h2').css('color','green')\n}", "get hyperLink() { return $(\"//a[contains(text(),'Site Map')]\") }", "function HandleMouseEnter(tag, event) {\n $(tag).css(\"border\", \"3px solid #967259\");\n}", "function changeTitle(){\r\n $(\"h1\").css({\r\n \"color\":\"white\",\r\n \"font-size\":\"8rem\",\r\n \"font-family\":\"Edwardian Script ITC\"\r\n });\r\n $(\"h2\").css({\r\n \"color\":\"yellow\",\r\n \"font-size\":\"6rem\",\r\n \"font-family\":\"Edwardian Script ITC\"\r\n });\r\n}", "function mouseOverH3None() {\n document.getElementById('h3').style.borderLeftColor = 'initial';\n document.getElementById('h3').style.borderRightColor = 'initial';\n}", "function changeBorderColor (element, color){\r\n\t\r\n\telement.style.border = \"1px solid \" + color;\r\n}", "function changeTitle(color) {\n _$('h1').style.color = color\n}", "function set_default_color_menu_border()\n {\n $(\"#black\").css({\"border\":\"2px solid #1c1f21\"});\n $(\"#orange\").css({\"border\":\"2px solid #ff9875\"});\n $(\"#sky_blue\").css({\"border\":\"2px solid #67b5e6\"});\n $(\"#green\").css({\"border\":\"2px solid #6eb711\"});\n $(\"#yellow\").css({\"border\":\"2px solid #fcac33\"});\n $(\"#peach\").css({\"border\":\"2px solid #ef665c\"});\n $(\"#gray\").css({\"border\":\"2px solid #6a6b7e\"});\n }", "function set_default_color_menu_border()\n {\n $(\"#black\").css({\"border\":\"2px solid #1c1f21\"});\n $(\"#orange\").css({\"border\":\"2px solid #ff9875\"});\n $(\"#sky_blue\").css({\"border\":\"2px solid #67b5e6\"});\n $(\"#green\").css({\"border\":\"2px solid #6eb711\"});\n $(\"#yellow\").css({\"border\":\"2px solid #fcac33\"});\n $(\"#peach\").css({\"border\":\"2px solid #ef665c\"});\n $(\"#gray\").css({\"border\":\"2px solid #6a6b7e\"});\n }", "function hover2(event){\n\n$(\"img\").hover(\n \n function(){\n \n $(this).css(\"border\", \"5px solid #FF0000\");\n }, \n \n function(){\n \n $(this).css(\"border\", \"none\");\n});\n}", "function alertRed(itemId, tabId)\n{\n document.getElementById(itemId + '-lbl').style.color='red';\n document.getElementById(itemId + '-lbl').style.fontWeight='bold';\n document.getElementById(itemId).style.fontWeight='bold';\n document.getElementById(itemId).style.borderColor='#fa5858';\n //document.getElementById(itemId + '_chzn').style.borderColor='red';\n\n //Check if a tab should be show.\n if(tabId) {\n showTab(tabId);\n }\n\n return;\n}", "function borderThicken(current,next) {\n\tcurrent.style.border = '1px solid gray';\n\tnext.style.border = '2px solid black';\n}", "function Themes_SetWhiteBorder(theHTML, interfaceLook)\n{\n\t//for now we hardcode this\n\ttheHTML.style.border = \"1px solid white\";\n}", "function questionOneAction() {\r\n $('span.message').css(\"color\",\"yellow\");\r\n}", "function questionFourAction() {\r\n $('img[alt=\"hello\"]').css(\"color\", \"red\");\r\n}", "function Button202(){\n $('h2').css('color','green');\n}", "function colorFormError(id) {\n document.getElementById(id).style.border = \"2px solid red\";\n}", "function anchorHover(strAnchorId)\n{\n\tvar objAnchor = document.getElementById(strAnchorId);\n\twith(objAnchor.style)\n\t{\n\t\tcolor=\"#4B0000\";\n\t\ttextDecoration=\"overline\";\n\t}\n\n}", "function changeAppearance()\n {\n this.style.color = \"blue\";\n this.style.border = \"2px solid blue\";\n }", "function isValid (element) {\n element.style.borderColor = '#173e43';\n}", "function BlueBoxClick() {\n \tjQuery (\"p\").css(\"color\", \"black\");\n \tjQuery (\"p.hipsterSpeak\").css(\"color\", \"white\");\n \tjQuery (\"p.hipsterSpeak\").css(\"background\", \"blue\");\n\n\n \t}", "function markElementAsAdded(html) {\n $(html).addClass('recentAdded');\n $('.recentAdded').css('border', '2px solid red');\n}", "function style_target() {\n\t\t\t\ttarget.css({\"background\": \"black\",\"border\": \"1px solid black\",\n\t\t\t\t\"border-radius\": \"2px\",\t\"padding\": \"0\",\t\"margin-left\": \"30%\",\"cursor\": \"pointer\"});\n\t\t\t}", "function mouseOver_2(){\n document.getElementById(\"book-button\").style.backgroundColor = \"#FFFC92\";\n document.getElementById(\"book-button\").style.color = \"#6000CE\";\n document.getElementById(\"book-button\").style.border = \"solid 2px #6000CE\";\n}", "function validateCustomMCQuestion(dis, err_msg){\n $(dis).parent().css('border', '1px solid red');\n console.log(err_msg);\n}", "function selectQuery(id)\n{\n\t\n\t$(\".fa fa-question-circle\").css(\"color\",\"red\");\n\t$(\"#query\"+id).css(\"color\",\"#00cc11\");\n}", "function setActiveStyleSheet(link, title) {\r\n var i, a, main;\r\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\r\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\r\n a.disabled = true;\r\n if(a.getAttribute(\"title\") == title) a.disabled = false;\r\n }\r\n }\r\n if (oldLink) oldLink.style.fontWeight = 'normal';\r\n oldLink = link;\r\n link.style.fontWeight = 'bold';\r\n return false;\r\n}", "function pragrav(){\n $('p').css('color','blue');\n }", "function changeImageBorder () {\n $ ('#selected-character-id').click (function () {\n $ (this).css ('border', 'solid 5px greenyellow');\n });\n }", "function setActiveStyleSheet(link, title) {\n var i, a, main;\n for(i=0; (a = document.getElementsByTagName(\"link\")[i]); i++) {\n if(a.getAttribute(\"rel\").indexOf(\"style\") != -1 && a.getAttribute(\"title\")) {\n a.disabled = true;\n if(a.getAttribute(\"title\") == title) a.disabled = false;\n }\n }\n if (oldLink) oldLink.style.fontWeight = 'normal';\n oldLink = link;\n link.style.fontWeight = 'bold';\n return false;\n}", "function setStyleJQ () {\n\n\tlet div = $(\"div\");\n\tdiv.css (\"background\", \"blue\");\n\tdiv.css (\"color\", \"white\");;\n\tdiv.css (\"cursor\", \"pointer\");\n}", "function HighlightLinkInHeader() {\n\tlet element = document.querySelector(\"ul.highlight\");\n\tif (!element) {\n\t\treturn;\n\t}\n\n\tlet list = element.querySelectorAll(\"li a\");\n\tlet target = window.location.pathname.replace(/\\/$/, \"\");\n\tfor (let i=0; i<list.length; i++) {\n\t\tlet location = list[i].pathname.replace(/\\/$/, \"\");\n\t\tif (location === target) {\n\t\t\tlist[i].style.borderBottom = \"2px solid #8c1515\";\n\t\t} else {\n\t\t\tlist[i].style.borderBottom = \"2px solid #f2f1eb\";\n\t\t}\n\t\tif (list[i].textContent.match(/About/)) {\n\t\t\tlist[i].style.borderBottom = \"2px solid #f2f1eb\";\n\t\t}\n\t}\n}", "function showalertemail(){\n $(\"#usernamealert\").css(\"display\",\"block\");\n $(\"#exampleInputEmail1\").css({\"border-color\": \"#EBEDF3\", \"border-size\": \"2px\"});\n}", "get supportLink() {return $(\"//a[text()='Support']\")}", "function HandleMouseLeave(tag, event) {\n $(tag).css(\"border\", \"3px solid #ece0d1\");\n}", "function republicanPresidents() {\n $(\".Republican\").addClass(\"red\");\n}", "function highlightByAttr(a) {\n var preserve = document.getElementById('preserve-previous-highlights').checked;\n var lock = document.getElementById('lock-highlights').checked;\n\n scObj.interactions.highlightRibbonByAttribute(a, preserve, lock);\n}", "function checkEditProfileFields() {\n $(\".profileField\").each(function (i) { \n if ($(this).val() === \"\" ) {\n $(this).css(\"border\", \"solid\");\n $(this).css(\"border-width\", \"thin\");\n $(this).css(\"border-color\", \"red\");\n }\n else {\n $(this).css(\"border-color\", \"\");\n }\n });\n}", "function questionTwoAction() {\r\n $('div.box:first').css(\"background-color\", \"green\");\r\n}", "function setToolTipColors() {\n // console.log(\"ss\");\n $(\".has-tip\").each(function(){\n if($(this).data(\"match-bg\")) {\n var color = $(this).children(\".fa\").css(\"color\");\n var target = $(this).data(\"toggle\");\n $(\"#\" + target).css({\"background-color\" : color});\n overrideTripStylesheet.insertRule('#' + target + '::before{border-color: transparent transparent ' + color + ';}', 0);\n }\n });\n }", "function republicanPresidents() {\n\t$(\".Republican*\").addClass(\"red\");\n}", "function roosterClicked() {\n alert(\"Ouch!!\");\n //change the color of a <p> of the index page\n //worst way to search paragraph\n //var p = document.children[1].children[0].children[2];\n\n //this one is a better way\n var p = document.getElementById(\"subtitle\");\n p.style = \"color: red\";\n\n //jquery will be another way (better) to modify\n}", "function Themes_SetStaticBorder(theHTML, interfaceLook)\n{\n\t//for now we hardcode this\n\ttheHTML.style.border = \"1px inset black\";\n}", "function questionSevenAction() {\r\n $('p:not(.box)').css(\"color\", \"orange\");\r\n}", "function changeGreen() {\n $('h2').css('color', 'green');\n }", "function removeHighlights() {\n $(\".edit-box, .edit-box > p\").css({\n \"border\": \"\"\n });\n}", "function addRedBorder(event){\n\tevent.target.style.border = \"5px solid red\";\n\tvar newParagraph = document.createElement('p');\n\tvar paraText = document.createTextNode(\"Suprise! Summer is here!\");\n\tnewParagraph.appendChild(paraText);\n\tvar heading = document.getElementById(\"myHeader\");\n\theading.appendChild(newParagraph);\n}", "constructor(){\n cy.xpath(\"(.//*[normalize-space(text()) and normalize-space(.)='Create'])[1]/following::a[1]\").should('be.visible');\n }", "function addBorder()\n{\n this.className = 'border';\n \n}", "function blue_to_red(){\n $('.mycontainblue').hide();\n $('.mycontent').css('visibility','visible');\n $('.title').css('visibility','visible');\n}", "function getBorderStyle(isEditable){\n if (isEditable) {\n return 'style=\"border: 1px solid pink\"';\n }\n else {\n return 'style=\"border: none\"';\n }\n \n }", "function ShowTab(name,id,title,defaultValue)\n{\n\t$(\"a[id^=mitem]\").removeClass();\n\tvar tag=name+\"_\"+id;\n\tdocument.getElementById(tag).style.display = \"block\"; \n}", "function Themes_SetRectBorder(theHTML, interfaceLook)\n{\n\t//for now we hardcode this\n\ttheHTML.style.border = \"1px outset black\";\n}", "function test(element) {\n\telement.setAttribute('style','background-color:#ff8888');\n}", "function questionEightAction() {\r\n $('div.box, div.correct').css(\"background-color\", \"gray\");\r\n}", "function showEditCl(editableObjCl) {\n $(editableObjCl).css(\"background\",\"#FFF\");\n }", "function changeColor (){\n\t\t$(this).css('background-color', 'red');\t\n\t}", "function clickColor(event) {\n var heads = document.getElementsByClassName('headers');\n // headOne = heads[0]\n // headTwo = heads[1]\n event.target.style.border = \"5px dotted purple\";\n // headTwo.style.border = \"5px dotted purple\";\n}", "function css(selector, propery, value) {\n //$(document).ready(function () {\n $(selector).css(propery, value);\n //});\n}", "function colorFormValid(id) {\n document.getElementById(id).style.border = \"2px solid green\";\n}", "function royalBorder1x( selector, direction, args ) {\n\t\tselector.css( 'border-'+ direction, args[0] +'px '+ args[1] +' '+ args[2] );\n\t}", "function PushButton_OnMouseOver(theObject)\n{\n\t//force its border\n\ttheObject.HTML.style.border = \"1px solid #73716b\";\n}", "function setValidOnBox(input){\n\tinput.css(\"border\",\"\");\n}", "function addBackgroundToLink(){\n var x = document.getElementsByTagName('a');\n for (var i = 0; i < x.length; i++) {\n x[i].style.color = 'red';\n }\n cl(document.querySelectorAll('a').style.color);\n}" ]
[ "0.6178891", "0.59507513", "0.588144", "0.5837314", "0.55046815", "0.54362494", "0.5434831", "0.5361209", "0.5326422", "0.5293821", "0.52601355", "0.5210352", "0.51999545", "0.51972544", "0.5179408", "0.5177637", "0.51709926", "0.51616627", "0.51509416", "0.5146306", "0.5134717", "0.51206934", "0.5090787", "0.5090664", "0.50902164", "0.50669813", "0.5056749", "0.5041868", "0.5040246", "0.5020261", "0.49967867", "0.49941325", "0.4988869", "0.49870467", "0.49798322", "0.49786064", "0.49774262", "0.49691206", "0.49526635", "0.4943355", "0.4938284", "0.49311224", "0.49286586", "0.49237445", "0.49190304", "0.49190304", "0.49171868", "0.4913715", "0.49111658", "0.48976701", "0.48936656", "0.48896366", "0.4889575", "0.48835272", "0.48728895", "0.4869522", "0.48622155", "0.48497733", "0.48447782", "0.4840387", "0.48400137", "0.48126113", "0.4807642", "0.48004037", "0.47920328", "0.4775872", "0.476732", "0.47507915", "0.47493684", "0.47243965", "0.47205344", "0.47114417", "0.47011518", "0.46999544", "0.46929944", "0.46919847", "0.46900815", "0.46814594", "0.46761945", "0.4638517", "0.46367735", "0.46293744", "0.46276873", "0.462758", "0.46261072", "0.46219403", "0.46157604", "0.46070066", "0.46066114", "0.4605676", "0.45940918", "0.45898303", "0.45894417", "0.45858186", "0.45821682", "0.4571572", "0.45663098", "0.45638853", "0.4547415", "0.4546759", "0.45440513" ]
0.0
-1
$("tr:has( > td > a[title='Show details'])").css( "border", "3px double green" );
function processFailureRow(row){ // $(row).css( "border", "3px double brown" ); var testLink=$(row).find("td:first-child a[href]"); var testInfo=createTestInfo(testLink.text()); var newLinks=[ createLink("L",relatedTicketsSearch(testInfo)), createLink("R",buildJobInvocationUri('hive-check',testInfo)), createLink("B",buildJobInvocationUri('hive-bisect',testInfo)), ]; newLinks.each(function (item) { item.insertBefore(testLink); }); // testLink.css( "border", "3px double blue" ); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function showHistory(){\n if ($('tbody').has(\"tr\").length) {\n $(\"#history-wrapper\").css(\"opacity\",\"1\");\n }\n}", "function letsJQuery(){ \r\n\top = $('A[class=bigusername]:first').html();\r\n\t$('A[class=bigusername]').each(function(i){\r\n\t\tif($(this).html()==op){\r\n\t\t\t$(this).parents('table:first')\r\n\t\t\t.css(\r\n\t\t\t\t{\r\n\t\t\t\t\t'background-color' : 'rgb(128, 128, 128)'\r\n\t\t\t\t}\r\n\t\t\t);\r\n\t\t\t\r\n\t\t\t$(this).parents('TD[nowrap=nowrap]')\r\n\t\t\t.css(\r\n\t\t\t\t{\r\n\t\t\t\t\t'background-color' : 'black'\r\n\t\t\t\t}\r\n\t\t\t);\r\n\t\t}\r\n\t});\r\n}", "function highlightMissing(elem)\n{\n $(elem).css(\"border-color\", \"red\");\n}", "function highlightCorrect(elem)\n{\n $(elem).css(\"border-color\", \"green\");\n}", "function BorderClick(){\n \tjQuery (\".boxes\").css(\"border-bottom\", \"6px solid black\")\n }", "function checkForAlreadySelectedContract()\n {\n $('#ContractTable tr').each(function(i, row)\n {\n if($(row).css(\"background-color\") === \"rgb(255, 0, 0)\")\n {\n\n $(row).css('background-color', 'rgb(0, 0, 0)');\n if(i%2 !== 0)\n {\n $(row).children().css({'background-color': '#dadada', 'color': '#332c28'}).find(\"a\").css({'color': 'blue'});\n }\n else\n {\n $(row).children().css({'background-color': '#cecece', 'color': '#332c28'}).find(\"a\").css({'color': 'blue'});\n }\n }\n });\n }", "function check_for_active_row(activelink, panedisp) {\n if ($(\".\" + String(activelink) + \".act\")[0]) {\n $(\".\" + String(panedisp) + \"nodisp\").css(\"display\", \"none\");\n $(\".\" + String(panedisp) + \"disp\").css(\"display\", \"block\");\n } else {\n $(\".\" + String(panedisp) + \"nodisp\").css(\"display\", \"block\");\n $(\".\" + String(panedisp) + \"disp\").css(\"display\", \"none\");\n }\n}", "get summaryCheckoutButton () { return $(\"div[id='center_column']\").$(\"a[title='Proceed to checkout']\")}", "function select() {\n $(this).parent().css('border', '2px solid blue');\n }", "function checkOut(){\n var table = document.getElementById('appointment-list');\n for(var i=0; i<table.rows.length;i++){\n var row = table.rows[i];\n if(row.hilite){\n row.style.backgroundColor=\"red\";\n }\n }\n}", "function zebraStripe() {\nif ($(\"table.zebra > tbody > tr\").eq(1).css(\"background-color\") == \"transparent\" && $(\"table.zebra > tbody > tr\").eq(2).css(\"background-color\") == \"transparent\") {\n$(\"table.zebra > tbody > tr:nth-child(2n+1)\").not(\".nozebra\").css(\"background-color\",\"#2c2c2c\");\n$(\".sortheader\").bind(\"click\", function() {\n$(\"table.zebra > tbody > tr\").not(\".nozebra\").css(\"background-color\",\"transparent\");\n$(\"table.zebra > tbody > tr:nth-child(2n+1)\").not(\".nozebra\").css(\"background-color\",\"#2c2c2c\");\n});\n}\n}", "function coloreTabela() {\n\t$('.Tabela01').each(function(index, element) {\n\t\t$('.Tabela01').find('tr:not(table.SubTabela01 tr):even').css('background-color','#FAFAFA');\n\t\t$('.Tabela01').find('tr:not(table.SubTabela01 tr):odd').css('background-color','#F3F3F3'); \n });\n}", "function checkIn(){\n var table = document.getElementById('appointment-list');\n for(var i=0; i<table.rows.length;i++){\n var row = table.rows[i];\n if(row.hilite){\n row.style.backgroundColor=\"green\";\n }\n }\n}", "function rowHover() {\r\n \r\n var tnbr = 0;\r\n if (/viewforum|IBDOF-authorlist|IBDOF-serieslist|IBDOF-genrelist/i.test(window.location.pathname))\r\n tnbr = 2;\r\n else if (/index/i.test(window.location.pathname))\r\n tnbr = 3;\r\n else if (/search|getdaily/i.test(window.location.pathname))\r\n tnbr = 4;\r\n \r\n if (tnbr > 0) {\r\n var dev = document.evaluate(\r\n \"//table[\"+tnbr+\"]/tbody/tr\", \r\n document, \r\n null, \r\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);\r\n \r\n for (i = 0; i < dev.snapshotLength; i++)\r\n dev.snapshotItem(i).className = 'row';\r\n }\r\n}", "get hyperLink() { return $(\"//a[contains(text(),'Site Map')]\") }", "function questionSixAction() {\r\n $('input[name^=\"txt\"]').css(\"border\", \"solid green\");\r\n}", "function toggle($element) {\n\tjQuery(document).ready(function ($) {\n\t\t// Toggles show and hide of the element\n \t$(\".\" + $element).toggle();\n \t// Sets and td children of the element to a certain background color\n \t$(\".\" + $element).children('td').css('background-color','#FFF');\n });\n}", "function rowOn(tr){\n\tif(document.getElementById||(document.all && !(document.getElementById))){\n\t\ttr.style.backgroundColor=\"#FFCC66\";\n\t}\n}", "function addRowHighlight() {\n $schedule.find('tbody tr:last-child *').addClass('adding');\n }", "function showIgnoreCheckBox(columnCountOnPage) {\n var $row = \"<th> Hide</th>\";\n var header = $(\".table tr:first\");\n\n if (header.children(\"th\").length < columnCountOnPage) {\n header.append($row);\n }\n\n var allPosts = $('.table tr').not(':first');\n\n allPosts.each(function (index, post) {\n if ($(this).children(\"td\").length < columnCountOnPage) {\n if (postId = $(this).find('a:first').attr('href')) {\n $(this).append(\"<td><div class='thread-hide eye-icon'></div></td>\");\n }\n\n }\n });\n}", "function isSecondColActive() {\n return $(\".MainRow\").first().children().eq(1).css(\"display\") != \"none\";\n}", "function visibleSelect(current){\r\n\tcurrent.style.border = \"2px solid\";\r\n}", "function show_details(event)\n{\n var target = $(event.target);\n var details = $( 'tr[ordernumber=\"'+target.attr('ordernumber')+'\"]')\n\n if( target.html().substr(0,6) !== 'Sakrij'){ // otrij detalje\n details.show();\n target.html('Sakrij detalje &#8595;');\n }\n else{ // sakrij detalje\n details.hide();\n target.html('Prikaži detalje &#8592;');\n }\n\n}", "function tableZebraEffect(table){\r\n $(table).find(\"tbody tr\").removeClass(\"alt\");\r\n $(table).find(\"tbody tr:even\").addClass(\"alt\");\r\n}", "function hideRows() { \r\n var topics = $(\".topictitle\")\r\n for (var i=0; i < topics.length; i++)\r\n { \r\n for (var j=0; j < hideUs.length; j++)\r\n {\r\n if (topics[i].href.search(\"t=\"+hideUs[j] ) != -1)\r\n {\r\n $(topics[i]).parent().parent().css(\"display\",\"none\");\r\n }\r\n }\r\n }\r\n}", "get createAnAccount () { return $(\"//h3[contains(text(),'Create an account')]\") }", "containsRow(row, tableCell) {\n if (row.childWidgets.indexOf(tableCell) !== -1) {\n return true;\n }\n while (tableCell.ownerTable.isInsideTable) {\n if (row.childWidgets.indexOf(tableCell) !== -1) {\n return true;\n }\n tableCell = tableCell.ownerTable.associatedCell;\n }\n return row.childWidgets.indexOf(tableCell) !== -1;\n }", "function letsJQuery() {\r\n var table = $('td > table').eq(60);\r\n var i = 60; \r\n while (!$('td',table).eq(0).html().match(/<b>#<\\/b>/))\r\n table = $('td > table').eq(i++);\r\n $('tr',table).each(function() \r\n {\r\n titre = $('td',this).eq(1);\r\n titre = $('a',titre).html();\r\n if (titre)\r\n titre = titre.replace(\"'\",\"\");\r\n else return;\r\n artist= $('td',this).eq(3).html();\r\n if (artist)\r\n artist = artist.replace(\"'\",\"\").replace(\"f./\",\"feat \");\r\n lien = \"<a href='http://fr.youtube.com/results?search_query=\"+artist+\"+\"+titre+\"&search_type=&aq=f' target=_blank>Youtube</a>\";\r\n lien2 = \"<a href='http://www.newzleech.com/?group=&minage=&age=&min=min&max=max&q=\"+artist+\"+\"+titre+\"&m=search&adv=' target=_blank>newzleech</a>\";\r\n lien3 = \"<a href='http://www.deezer.com/#music/result/all/\"+artist+\" \"+titre+\"' target=_blank>Deezer</a>\";\r\n lien4 = \"<a href='http://www.binsearch.info/?q=\"+artist.replace(' ','+')+\"+\"+titre.replace(' ','+')+\"&max=250&adv_age=700&server=' target=_blank>Binsearch</a>\";\r\n $('td',this).eq(0).html(lien+\" \"+lien2+\" \"+lien3+\" \"+lien4);\r\n })\r\n }", "function highlightTableRowOb(ob,event_time) {\r\n\tob.children('td').effect('highlight',{},event_time);\r\n}", "function createBorders() {\n let myElements = document.querySelectorAll(\"tr > td\");\n console.log(myElements);\n for (i = 0; i < myElements.length; i++) {\n myElements[i].style.border = \"2px solid black\";\n }\n}", "constructor(){\n cy.xpath(\"(.//*[normalize-space(text()) and normalize-space(.)='Create'])[1]/following::a[1]\").should('be.visible');\n }", "function IsOnBorder(tree) {\n\n return IsInLeftBorderColumn(tree) ||\n IsInTopBorderRow(tree) ||\n IsInRightBorderColumn(tree) ||\n IsInBottomBorderRow(tree);\n\n} // end function IsOnBorder(tree)", "rowProductShopCart() { return `#cart_summary > tbody > tr`}", "function highlightTableRow() {\n var upc = $('#lbl-itemAdded').html();\n location.href = '#' + upc;\n $('#' + upc).addClass('selected');\n $(\"#txtFldupc\").focus();\n }", "function comparePageRowHoverOver() {\n var $pageRow = $(this);\n $pageRow.children(\".leftCompareDetails\").children(\".detailText\").children(\".unchangedDetails\").addClass(\"unchangedDetailsVisible\");\n $pageRow.children(\".rightCompareDetails\").children(\".detailText\").children(\".unchangedDetails\").addClass(\"unchangedDetailsVisible\");\n $pageRow.children(\".pageRowChild\").children(\".leftCompareDetails\").children(\".detailText\").children(\".unchangedDetails\").addClass(\"unchangedDetailsVisible\");\n $pageRow.children(\".pageRowChild\").children(\".rightCompareDetails\").children(\".detailText\").children(\".unchangedDetails\").addClass(\"unchangedDetailsVisible\");\n }", "function highlightCard(card, cname)\n{\n\t$(card).find(\"td.col-name\").addClass(cname);\n\t$(card).find(\"td.col-cost\").addClass(cname);\t\t\n}", "function init() {\r\n $('tr:even').css(\"background-color\", \"gray\");\r\n}", "function trCss(el){\n\n var $this = el.parents('tr');\n $('#browse-datatables tbody').children('tr').removeClass('tables-hover');\n $this.addClass('tables-hover');\n\n }", "function IsInTopBorderRow(tree) {\n\n return +tree.getAttribute(\"data-y\") === 0;\n\n} // end function IsInTopBorderRow(tree)", "function init_2(){\n d3.select('table')\n .selectAll('td')\n .each(function(e) {\n if (this.innerText === \"42\")\n this.style.backgroundColor = \"red\";\n }\n );\n}", "function isExistRow() {\n\ttry {\n \tvar isEmpty = $('#table-internal-order tbody tr').length > 0;\n \treturn isEmpty;\n } catch (e) {\n alert('isExistRow: ' + e.message);\n }\n}", "function checkIfThereIsALink(table, row) {\n for(var j=0; j < table[row].length; j++) {\n if(table[row][j] != 0) {\n for(var i=0; i < table.length; i++) {\n if(table[i][j] != 0) {\n for(var k=0; k < table.length; k++) {\n if(k!=row && table[k][j] != 0) return true;\n }\n }\n }\n }\n }\n return false;\n }", "function highlight(id)\n{\n\t$(\".auto_option\").css({'padding':'5px','border':'0px','color':'#000'});\n\tvar sel = $(\"#\"+id);\n\tif(sel)\n\t{\n\t\tsel.css({'padding':'4px','border':'1px solid #333','color':'#333'});\n\t\treturn true;\t\n\t}\n\telse return false;\n}", "function letsJQuery() {\n $('tr').each(function (idx) {\n const td = $(this).find('td:eq(2)');\n if (td && (td.text().length === 0)) {\n td.text('nobody');\n }\n });\n}", "function highlightColumns() {\r\n $('table.newschart > tbody > tr.ndate > td.nval').hover(function () {\r\n var col = $(this).attr(\"col\");\r\n $('table.newschart > tbody > tr > td.nval').addClass(\"colgrey\");\r\n $('table.newschart > tbody > tr > td.nval.nval' + col).addClass(\"colhover\");\r\n }, function () {\r\n var col = $(this).attr(\"col\");\r\n $('table.newschart > tbody > tr > td.nval').removeClass(\"colgrey\");\r\n $('table.newschart > tbody > tr > td.nval.nval' + col).removeClass(\"colhover\");\r\n });\r\n}", "function checkSelectionBorders(hot, direction) {\n var atLeastOneHasBorder = false;\n (0, _array.arrayEach)(hot.getSelectedRange(), function (range) {\n range.forAll(function (r, c) {\n var metaBorders = hot.getCellMeta(r, c).borders;\n\n if (metaBorders) {\n if (direction) {\n if (!(0, _object.hasOwnProperty)(metaBorders[direction], 'hide') || metaBorders[direction].hide === false) {\n atLeastOneHasBorder = true;\n return false; // breaks forAll\n }\n } else {\n atLeastOneHasBorder = true;\n return false; // breaks forAll\n }\n }\n });\n });\n return atLeastOneHasBorder;\n}", "function k(e,t){return c(e,\"table\")&&c(11!==t.nodeType?t:t.firstChild,\"tr\")&&me(\">tbody\",e)[0]||e}", "function toggleCell(selector) {\n $(selector).css('background', selector.attr('data-circle-color'));\n}", "function highlightTableRow(rowid,event_time) {\r\n\t$('#'+rowid+' td').effect('highlight',{},event_time);\r\n}", "function find_matched_headfix_row(tr, hf_name)\n {\n while ((tr=tr.nextSibling))\n if (is_tr_el(tr))\n if (class_includes(tr,hf_name))\n return tr;\n\n return null;\n }", "function showData(prop, value) {\n value = value.replace(\"'\", \"`\");\n\n let element = \n \"<tr><td>\" + prop + \"</td><td><input type='text' value='\" + value + \n \"' disabled /></td></tr>\";\n\n $(\"#productBody\").append(element);\n\n if(value == \"true\") {\n $(\"tr:contains(Discontinued) input\").css({color : \"red\"});\n }\n}", "function showTab() {\n var url = window.location.href;\n if(url.indexOf('/get_started/why_mxnet') != -1) return;\n for(var i = 0; i < TITLE.length; ++i) {\n if(url.indexOf(TITLE[i]) != -1) {\n var tab = $($('#main-nav').children().eq(i));\n if(!tab.is('a')) tab = tab.find('a').first();\n tab.css('border-bottom', '3px solid');\n }\n }\n}", "function getSpoonBoxes(row)\n{\n return $(row.children().filter(\".spoon\"));\n}", "function tp_row_below(l, index)\n{\n\tvar s = parent_document(l).layerSets;\n\n\tif ('Col' == l.parent.name.substring(0, 3))\n\t\tif (index != 0)\n\t\t\treturn false;\n\n\tfor (var i = 0; i < s.length; i++)\n\t{\n\t\tif (s[i].name == l.parent.name)\n\t\t\tbreak;\n\n\t\tif ('Row' == s[i].name.substring(0, 3))\n\t\t\treturn true;\n\t}\n\n\treturn false;\n}", "function dimRow(row, dimmed) {\r\n for (var i = 0; i < matchTable.rows[row].cells.length; i++) {\r\n if (i != columnIndex(CLOSE)) {\r\n matchTable.rows[row].cells[i].style.opacity = dimmed ? 0.2 : 1;\r\n matchTable.rows[row].cells[i].style.textDecoration = dimmed ? 'line-through' : '';\r\n }\r\n } \r\n}", "function leNav(ihref){\n $(\".detailContent .leftNav li a[href^='\"+ihref+\"']\").addClass(\"on\");\n}", "function rowSelector() {\n var $auditTableRow = $('.js-row-selector tr'),\n activeClass = 'active-table-row';\n\n $auditTableRow.click(function() {\n $(this).siblings().removeClass(activeClass);\n $(this).find('td input[type=radio]').prop('checked', true);\n $(this).addClass(activeClass);\n });\n}", "function clickToday() {\n if (!$(\"tr.fc-week\").is(':visible')) {\n $('.fc-today-button').click();\n }\n}", "tdSituation(i){ return $ (`(//td[@class='status'])[${i}]`);}", "get supportLink() {return $(\"//a[text()='Support']\")}", "function checkSelectionBorders(hot, direction) {\n var atLeastOneHasBorder = false;\n Object(_helpers_array__WEBPACK_IMPORTED_MODULE_2__[\"arrayEach\"])(hot.getSelectedRange(), function (range) {\n range.forAll(function (r, c) {\n var metaBorders = hot.getCellMeta(r, c).borders;\n\n if (metaBorders) {\n if (direction) {\n if (!Object(_helpers_object__WEBPACK_IMPORTED_MODULE_1__[\"hasOwnProperty\"])(metaBorders[direction], 'hide') || metaBorders[direction].hide === false) {\n atLeastOneHasBorder = true;\n return false; // breaks forAll\n }\n } else {\n atLeastOneHasBorder = true;\n return false; // breaks forAll\n }\n }\n });\n });\n return atLeastOneHasBorder;\n}", "function highlightCheckedSelections() {\n $( \"tr[input]\" ).removeClass( \"highLightAdded\" );\n $( \"tr[input[@checked]]\" ).addClass( \"highLightAdded\" );\n}", "function xTableCellVisibility(bShow, sec, nRow, nCol)\r\n{\r\n sec = xGetElementById(sec);\r\n if (sec && nRow < sec.rows.length && nCol < sec.rows[nRow].cells.length) {\r\n sec.rows[nRow].cells[nCol].style.visibility = bShow ? 'visible' : 'hidden';\r\n }\r\n}", "function table_highlightSelectedRowForChild(obj, state)\r\n{\r\n if (state == null) state = true;\r\n\r\n var rowobj = obj;\r\n while (rowobj != null && rowobj.tagName != \"TR\")\r\n {\r\n if (rowobj.parentElement)\r\n {\r\n rowobj = rowobj.parentElement;\r\n }\r\n else\r\n {\r\n rowobj = rowobj.parentNode;\r\n }\r\n }\r\n if (rowobj != null)\r\n {\r\n if (state == true)\r\n {\r\n rowobj.originalClassName = rowobj.className;\r\n rowobj.className = \"rowHighlight\";\r\n rowobj.cells[0].childNodes[0].style.backgroundColor = \"\";\r\n }\r\n else\r\n {\r\n if (rowobj.originalClassName != null)\r\n rowobj.className = rowobj.originalClassName;\r\n }\r\n }\r\n\r\n\r\n}", "tdTitle(i){ return $ (`(//td[@class='subject'])[${i}]`);}", "function has_border(x, y){\n return PS.border(x, y, PS.CURRENT);\n}", "function r(a,b){return fa.nodeName(a,\"table\")&&fa.nodeName(11!==b.nodeType?b:b.firstChild,\"tr\")?a.getElementsByTagName(\"tbody\")[0]||a.appendChild(a.ownerDocument.createElement(\"tbody\")):a}", "function highlightShowButton(show_id,topic_item){\n $.each(topic_item.show,function(i,item){\n if (item.id === show_id.id){\n $('#'+item.id).addClass('active');\n } else {\n $('#'+item.id).removeClass('active');\n }\n })\n}", "get maritalStatusToggleMarried(){return $('[for=\"married\"]');}", "function cheked_row(id_table, id_tr) {\n //Se la riga cliccata è quella checked allora deve deselezionarla solo\n attr = document.getElementById(id_tr).getAttribute(\"checked\")\n if (attr != null) {\n $(\"#\" + id_table + \" tr[checked]\").removeAttr(\"style\")\n $(\"#\" + id_table + \" tr[checked]\").removeAttr('checked')\n return\n }\n\n $(\"#\" + id_table + \" tr[checked]\").removeAttr(\"style\")\n $(\"#\" + id_table + \" tr[checked]\").removeAttr('checked')\n\n $(\"#\" + id_tr).attr(\"checked\", \"checked\")\n $(\"#\" + id_tr).attr(\"style\", \"background:#c1e2b3;\")\n\n\n}", "function checkEditProfileFields() {\n $(\".profileField\").each(function (i) { \n if ($(this).val() === \"\" ) {\n $(this).css(\"border\", \"solid\");\n $(this).css(\"border-width\", \"thin\");\n $(this).css(\"border-color\", \"red\");\n }\n else {\n $(this).css(\"border-color\", \"\");\n }\n });\n}", "function highlightClickedOption(clickedSquareIdCookie){\n //console.log('clickedSquareIdCookie: ', clickedSquareIdCookie);\n $('#'+clickedSquareIdCookie).css(\"border-color\", \"#e12522\");\n $('#'+clickedSquareIdCookie).html('<i class=\"fa fa-check\" aria-hidden=\"true\"></i>').css(\n { 'display' : 'table-cell', \n 'text-align' : 'center', \n 'padding-top': '10px' , \n 'font-size': '20px' , \n 'padding-top': '10px',\n 'color': '#e12522'\n });\n}", "function showMunTable(){\n $('body').find('.stats-prov').css( \"opacity\", \"1\" );\n}", "function isDuplicate(row) {\n\t\tvar dup = false;\n\t\tvar title = $(':nth-child(2)',row).html();\n\t\tvar description = $(':nth-child(4)',row).html();\n\t\tvar date = $(':nth-child(5)',row).html();\n\t\tvar dt, ddes, dd;\n\t\t$(\"#displayTable\").find(\"tr\").each(function() {\n\t\t\tdt = $(':nth-child(2)',this).html();\n\t\t\tdd = $(':nth-child(5)',this).html();\n\t\t\tddes = $(':nth-child(4)',this).html();\n\t\t\tif(title == dt && description == ddes && date == dd){\n\t\t\t\tdup = true;\n\t\t\t}\n\t\t\t//$(this).children(\"td:first\").html(s);\n\t\t});\n\t\treturn dup;\n\t}", "function main() {\r\n test = true;\r\n $('tr.[class^=\"kb-table-row-\"][onclick]').each(\r\n function(){\r\n clicker = $(this).attr('onclick')+\"\";\r\n ref = clicker.replace(/[\\s\\S]*\\.href='(.*)';[\\s\\S]*/, \"$1\");\r\n $(this).children().each( function() {\r\n ship = $(this);\r\n linq = '<a href=\"' + ref + '\">' + ship.html() + '</a>';\r\n ship.html(linq);\r\n });\r\n });\r\n $('tr.[class^=kb-table-row-][onclick] a').css({'display' : 'block', 'color':'inherit', 'text-color':'inherit', 'background':'inherit', 'text-decoration':'none', 'height':'100%'});\r\n\r\n $('tr.[class^=kb-table-row-][onclick]').removeAttr('onclick');\r\n $('tr.[class^=kb-table-row-]').css('cursor', 'none');\r\n}", "function highlightEvents(rowNum){\n let tableTimes = $(`.${rowNum}`);\n if (currentHour === rowNum){\n tableTimes.addClass(\"present\");\n }\n if (currentHour > rowNum){\n tableTimes.addClass(\"past\");\n }\n if (currentHour < rowNum){\n tableTimes.addClass(\"future\");\n }\n}", "function validateRankingQuestion(dis, err_msg){\n var id = dis.id.split('[')[0];\n $('div.ranking-question-box-left#'+id).css('border', '1px solid red');\n console.log(err_msg + ' ' +id);\n}", "function reschedule(){\n var table = document.getElementById('appointment-list');\n for(var i=0; i<table.rows.length;i++){\n var row = table.rows[i];\n if(row.hilite){\n row.style.backgroundColor=\"yellow\";\n }\n }\n}", "function alterBorder() {\r\n var scrollTable = query(queryText)[0];\r\n if (scrollTable.offsetHeight >= visibleAreaHeight) { //scrollbar visible & active\r\n //dont want a border on final row, if an odd row\r\n var lastRow = query(\".odd-last-row\", scrollTable)[0];\r\n if (typeof lastRow != \"undefined\") {\r\n domClass.add(lastRow, \"no-bottom-border\");\r\n }\r\n }\r\n else if (scrollTable.offsetHeight < visibleAreaHeight) { //scrollbar visible & inactive\r\n //we want a border on final row, if an even row\r\n var lastRow = query(\".even-last-row\", scrollTable)[0];\r\n if (typeof lastRow != \"undefined\") {\r\n domClass.add(lastRow, \"add-bottom-border\");\r\n }\r\n }\r\n else {\r\n curam.debug.log(\"curam.util.alterScrollableListBottomBorder: \" \r\n + bundle.getProperty(\"curam.util.code\"));\r\n }\r\n }", "function highlightTable(tblid,event_time) {\r\n\tif (document.getElementById(tblid) == null) return;\t\r\n\t$('#'+tblid+' td').effect('highlight',{},event_time);\r\n}", "function tableWrapperHasClass( tableWrapper, className ) {\n\treturn $(tableWrapper).find( 'table' ).hasClass( className );\n}", "function selectFuzzyRow()\n{\n //TODO: for some reason this breaks without the timeout?\n setTimeout(function(){\n var tableRow = $('tr.error').first();\n expandRow(tableRow);\n }, 500);\n}", "function show_hide_row(row){\n\tif ( $(\"#\" + row).hasClass('table-active') ) {\n\t\t$(\"#expand\"+row).hide();\n\t\t$(\"#\" + row).removeClass(\"table-active\");\n\n\t}else{\n\t\t$(\"tr\").removeClass(\"table-active\"); \n\t\t$(\".hidden_row\").hide();\n\t\t$(\"#expand\"+row).show();\n\t\t$(\"#\" + row).toggleClass(\"table-active\");\n\t}\n}", "function checkResultsTableWidth()\r\n{\r\n\tvar w = $(\"#tbl_salida\").width();\r\n\tif(w < 700)\r\n\t\t$(\"#tbl_salida .expandable .detail, #tbl_regreso .expandable .detail\").removeClass(\"stretched\");\r\n\telse\r\n\t\t$(\"#tbl_salida .expandable .detail, #tbl_regreso .expandable .detail\").addClass(\"stretched\");\r\n}", "function setColorBgForMealPlanTable() {\n const dayOfToday = getDayofToday();\n const $trs = $(\"#mpTbody tr\");\n\n for (let $tr of $trs) {\n if ($tr.id === dayOfToday) {\n $($tr).addClass(\"table-info\");\n $($tr).removeClass(\"table-primary\");\n }\n else {\n $($tr).addClass(\"table-primary\");\n $($tr).removeClass(\"table-info\");\n }\n }\n }", "function userTableShowOthers() {\n\tvar tbl = document.getElementById('user-stats-table');\n\tvar row = tbl.rows[0];\n\tvar end = row.cells.length-1;\n\tvar idlast = row.cells[end].id;\n\tif (idlast == \"show_others\") return true;\n\treturn false;\n}", "function letsJQuery() {\r\n alert(\"Loaded!\");\r\n $(\"a[id*='.editLink']\").alert(\"Editing an event!\");\r\n}", "function IsInBottomBorderRow(tree) {\n\n return +tree.getAttribute(\"data-y\") === TREE_COUNT_Y - 1;\n\n}", "function open_quick_edit(tr_hide,tr_show){\r\n\tjQuery.noConflict();\r\n\tvar tr_hide = '.'+tr_hide;\r\n\tvar tr_show = '.'+tr_show;\r\n\tjQuery(tr_hide).css({'display':'none'});\r\n\tjQuery(tr_show).css({'display':'table-row'});\r\n}", "tableProductsShopCart() { return `#cart_summary > tbody`}", "function desktop_rowBgColor() {\r\n $('body.jg-page-shoppingcart #line-item-grid tr.line-item').each(function() {\r\n\r\n var order_type = $(this).find('td:nth-child(3)').find('input').val();\r\n console.log(order_type);\r\n\r\n if (order_type == 'Bonus') {\r\n $(this).css('background-color', '#eee');\r\n } else if (order_type == 'Comm') {\r\n $(this).css('background-color', '#fff');\r\n }\r\n\r\n\r\n });\r\n }", "function showCol(obj, col_id) {\n\tvar tb = document.getElementById(obj);\n\tvar trow = tb.rows;\n\tfor (var i = 0; i < trow.length; i++) {\n\t\ttrow[i].cells[col_id].style.display == 'block';\n\t}\n}", "function HighlightLinkInHeader() {\n\tlet element = document.querySelector(\"ul.highlight\");\n\tif (!element) {\n\t\treturn;\n\t}\n\n\tlet list = element.querySelectorAll(\"li a\");\n\tlet target = window.location.pathname.replace(/\\/$/, \"\");\n\tfor (let i=0; i<list.length; i++) {\n\t\tlet location = list[i].pathname.replace(/\\/$/, \"\");\n\t\tif (location === target) {\n\t\t\tlist[i].style.borderBottom = \"2px solid #8c1515\";\n\t\t} else {\n\t\t\tlist[i].style.borderBottom = \"2px solid #f2f1eb\";\n\t\t}\n\t\tif (list[i].textContent.match(/About/)) {\n\t\t\tlist[i].style.borderBottom = \"2px solid #f2f1eb\";\n\t\t}\n\t}\n}", "function questionFiveAction() {\r\n $('#myDiv').find('input[type=\"text\"]').css(\"border\", \"solid red\");\r\n}", "function renderList_search(data) {\n\n show_search_results_table(); // function\n \n empty_search_table_html(); // function\n\t\n$.each(data.client, function(i,user){\nvar tblRow =\n\"<tr>\"\n+\"<td>\"+user.ItemID+\"</td>\"\n+\"<td>\"+user.Name+\"</td>\"\n+\"<td>\"+user.CAT+\"</td>\"\n//+\"<td>\"+user.www+\"</td>\"\n//+ \"<th><img border=\\\"0\\\" src=\\\"\"+ imgLink + commodores_variable.pic +\"\\\" alt=\\\"Pulpit rock\\\" width=\\\"304\\\" height=\\\"228\\\"><\\/th>\"\n + \"<td><a href=\\\"http:\\/\\/\"+user.www+\"\\\" target=\\\"_blank\\\">\"+user.www+\"<\\/a></td>\"\n+\"</tr>\" ;\n// Specific client data on table\n$(tblRow).appendTo(\".userdata_search tbody\");\n});\n\n$(\".userdata_search tbody tr td\").css({ border: '1px solid #ff4141' });\n \t\n}", "function drawHatTable(tbody) {\r\n\tvar tr, td;\r\n\ttbody = document.getElementById(tbody);\r\n\t// remove existing rows, if any\r\n\tclearTable(tbody);\r\n\tvar oddEven = \"tableRowEven\";\r\n\tfor ( var i = 0; i < hatDetails.length; i++) {\r\n\t\ttr = tbody.insertRow(tbody.rows.length);\r\n\t\ttr.className = oddEven;\r\n\t\t// loop through data source\r\n\t\tfor ( var j = 0; j < hatDetails[i].length - 1; j++) {\r\n\t\t\ttd = tr.insertCell(tr.cells.length);\r\n\t\t\ttd.className = \"hatCol\";\r\n\t\t\tif (!hatDetails[i][j]) {\r\n\t\t\t\thatDetails[i][j] = \"\";\r\n\t\t\t}\r\n\t\t\tif (j == 0) {\r\n\t\t\t\tif (hatDetails[i][12] != null) {\r\n\t\t\t\t\ttd.id = hatDetails[i][j];\r\n\t\t\t\t\ttd.innerHTML = \"<a href='' id=\" + td.id + \">\" + hatDetails[i][j] + \"</a>\";\r\n\t\t\t\t\t$(\"#\" + td.id).click(function(event) {\r\n\t\t\t\t\t\tfindHatDetails(this.id, hatDetails);\r\n\t\t\t\t\t\tevent.preventDefault();\r\n\t\t\t\t\t});\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttd.innerHTML = hatDetails[i][j];\r\n\t\t\t\t}\r\n\t\t\t} else if (j == 5) {\r\n\t\t\t\tif (hatDetails[i][j] == \"G\") {\r\n\t\t\t\t\ttd.className = \"greenStatus\";\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttd.className = \"redStatus\";\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\ttd.innerHTML = hatDetails[i][j];\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (oddEven = \"tableRowEven\") {\r\n\t\t\toddEven = \"tableRowOdd\";\r\n\t\t} else {\r\n\t\t\toddEven = \"tableRowEven\";\r\n\t\t}\r\n\t}\r\n}", "unboldColumn(lastSlotNum) {\n for (let i = lastSlotNum; i >= 0; i -= 7) {\n if (this.getSlot(i).style.border != '4px solid red') {\n this.getSlot(i).style.border = '2px solid black';\n }\n }\n }", "function isInBorder(rowIdx, colIdx, line_length) {\n return (rowIdx >= 0 && rowIdx < line_length && colIdx >= 0 && colIdx < line_length);\n}", "function pb_sweapNodeDataRow(){\n\n var tableRow = $('.pbd_ul_child .pbd_rule_param');\n\n if( pb_isClassExist(tableRow,'state_text') ){\n\n //State text show 'text' hide 'field'\n tableRow.find('.pbd_rule_action span#pbd_rule_action_edit').show();\n tableRow.find('.pbd_rule_action span#pbd_rule_action_save').hide();\n tableRow.find('.pbd_rule_action span#pbd_rule_action_cancel').hide();\n tableRow.find('.pbd_rule_data .pbd_rule_text').show();\n tableRow.find('.pbd_rule_data .pbd_rule_field').hide();\n pb_trace('pb_sweapNodeDataRow > display Text');\n }else{\n\n tableRow.find('.pbd_rule_action span#pbd_rule_action_edit').hide();\n tableRow.find('.pbd_rule_action span#pbd_rule_action_save').show();\n tableRow.find('.pbd_rule_action span#pbd_rule_action_cancel').show();\n tableRow.find('.pbd_rule_data .pbd_rule_text').hide();\n tableRow.find('.pbd_rule_data .pbd_rule_field').show();\n pb_trace('pb_sweapNodeDataRow > display Field');\n }\n\n }", "function xTableRowDisplay(bShow, sec, nRow)\r\n{\r\n sec = xGetElementById(sec);\r\n if (sec && nRow < sec.rows.length) {\r\n sec.rows[nRow].style.display = bShow ? '' : 'none';\r\n }\r\n}" ]
[ "0.5757953", "0.5625711", "0.536601", "0.5303977", "0.5269391", "0.52478164", "0.522248", "0.51975113", "0.5172034", "0.5129417", "0.5095272", "0.50109905", "0.49764884", "0.49693224", "0.49129876", "0.49041867", "0.49019963", "0.48914182", "0.48213682", "0.48213416", "0.48033392", "0.47800416", "0.47760567", "0.47667855", "0.4762144", "0.4754261", "0.47482103", "0.47145513", "0.47125345", "0.4711905", "0.4704139", "0.4703711", "0.46901757", "0.46849003", "0.46836162", "0.46751186", "0.46720004", "0.4669181", "0.46634853", "0.4653819", "0.464767", "0.4646515", "0.46394065", "0.4636883", "0.463678", "0.46221754", "0.46189103", "0.46115473", "0.46065584", "0.46054596", "0.45969394", "0.45829096", "0.45777187", "0.45737877", "0.45567867", "0.4529572", "0.45295596", "0.4523576", "0.45138556", "0.45116436", "0.45071924", "0.44975963", "0.4491283", "0.4488119", "0.44880503", "0.44831863", "0.44797754", "0.44786778", "0.44785342", "0.4475713", "0.4450926", "0.44429147", "0.4442165", "0.44419447", "0.44371307", "0.4429018", "0.4419325", "0.4416512", "0.4414553", "0.44124106", "0.44109854", "0.44096515", "0.44079232", "0.44068307", "0.4406285", "0.43980187", "0.4397517", "0.43897304", "0.43814206", "0.43787247", "0.43764442", "0.43602216", "0.43515286", "0.43421343", "0.43290234", "0.4327954", "0.4316883", "0.4312654", "0.4311797", "0.4306139" ]
0.44212735
76
Retrieves chosen answers from the dom
_processDOMResult() { // retrieve the checked input qyuizify elements let res = document.querySelectorAll('input[name=quizify_answer_option]:checked').length > 0 ? document.querySelectorAll('input[name=quizify_answer_option]:checked') : document.querySelectorAll('input[name=quizify_answer_option]'); // for jest testing... // get the selection of the user let chosenOptions = []; for (let i = 0; i < res.length; i++) if (res[i].checked === true) chosenOptions.push(res[i].value); if (chosenOptions.length <= 0) throw new Exceptions.QuizNoAnswerSelectedException(); // pass it to the processing function this.processUserAnswer(chosenOptions); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getAnswers() {\n const answers = [];\n const items = document.querySelectorAll('#ballot .object_item');\n for (const item of items) {\n const q = item.querySelector('.object_question').innerText;\n const a = item.querySelector('.ballotChoiceBox').innerText;\n answers.push({q: q, a: a});\n }\n return answers;\n }", "function pullQuestion() {\n askQuestion.textContent = questions[currentQuestion].question;\n for (j = 0; j < questions[currentQuestion].choices.length; j++) {\n options = document.querySelector(\"#choice\"+j);\n options.textContent = questions[currentQuestion].choices[j];\n }\n }", "function fetch_answers() {\n\n \n\n let answers = [];\n\n $(\".mcq-question\").each(function(){\n\n\n let option_id = $(this).find('.mcq-option[selected]').attr('data-id');\n \n if (option_id)\n answers.push(option_id)\n\n });\n\n\n return answers;\n\n}", "function getRandomAnswer() {\n\tvar possibleAnswers = [];\n\tArray.from(document.getElementsByClassName(\"answer\")).forEach(\n\t function(element) {\n\t\t\tif (element.parentElement.style.visibility != \"hidden\") {\n\t \t\tpossibleAnswers.push(element.previousElementSibling);\n\t \t}\n\t }\n\t);\n\tshuffle(possibleAnswers);\n\treturn possibleAnswers[0].textContent;\n}", "function getAnswers() {\n let questionAnswers = document.querySelectorAll('.answer');\n for (let i = 0; i < questionAnswers.length; i++) {\n answerSelection(questionAnswers[i]);\n }\n localStorage.setItem(\"userAnswers\", JSON.stringify(masterProfileObject))\n}", "function getAnswers() {\n let answerArray = [0, 1, 2, 3];\n answerArray = answerArray.sort(() => Math.random() - 0.5);\n answerA.innerText = \"\";\n answerA.innerText = questionArray[indexFinder].answers[answerArray[0]];\n answerB.innerText = \"\";\n answerB.innerText = questionArray[indexFinder].answers[answerArray[1]];\n answerC.innerText = \"\";\n answerC.innerText = questionArray[indexFinder].answers[answerArray[2]];\n answerD.innerText = \"\";\n answerD.innerText = questionArray[indexFinder].answers[answerArray[3]];\n \n \n//Hide any empty answer boxes for T/F questions \n if(answerA.innerText === \"undefined\"){\n answerA.style.display = \"none\"\n }\n else{answerA.style.display = \"block\"};\n\n if(answerB.innerText === \"undefined\"){\n answerB.style.display = \"none\"\n }\n else{answerB.style.display = \"block\"};\n\n if (answerC.innerText === \"undefined\") {\n answerC.style.display = \"none\";\n } \n else {answerC.style.display = \"block\";};\n\n if (answerD.innerText === \"undefined\"){\n answerD.style.display = \"none\"\n }\n else{answerD.style.display = \"block\"};\n}", "function getAnswer() {\n\n\tvar answer = document.getElementById('answer'); //melanie needs to create this html element\n\n\treturn answer\n}", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n pref.push(questions[questionCounter].choices[$('input[name=\"answer\"]:checked').val()][1])\n\n }", "function loadAnswers(answers) {\n // create variable result and set it to an empty string\n var result = \"\";\n // for loop to loop through the answers and create new <p> tags to add to the screen\n for (var i = 0; i < answers.length; i++) {\n /* for each item in answers, create <p> tag with a class of \"userPick\" and an attribute\n data-answer of the current answer the loop is on. then display the answers in those <p> tags*/\n result += `<p class=\"userPick\" data-answer=\"${answers[i]}\">${answers[i]}</p>`;\n }\n\n // return the result variable\n return result;\n }", "function getResults(){\n\n // question 1, option 1\n if (selections[0] === \"0\"){\n\n if (selections[1] === \"1\"){\n return 3;\n }\n if (selections[1] === \"2\"){\n return 6;\n }\n if (selections[1] === \"3\"){\n return 8;\n }\n }\n //question 1, option 2\n if (selections[0] === \"1\"){\n\n if (selections[1] === \"0\"){\n return 2;\n }\n if (selections[1] === \"1\"){\n return 4;\n }\n if (selections[1] === \"2\"){\n return 9;\n }\n }\n //question 1, option 3\n if (selections[0] === \"2\"){\n\n if (selections[1] === \"0\"){\n return 1;\n }\n if (selections[1] === \"1\"){\n return 5;\n }\n if (selections[1] === \"2\"){\n return 7;\n }\n }\n}", "function getA() {\n $(\"#answer1\").html(questAns[questCount].answers[0].answer);\n $(\"#answer2\").html(questAns[questCount].answers[1].answer);\n $(\"#answer3\").html(questAns[questCount].answers[2].answer);\n $(\"#answer4\").html(questAns[questCount].answers[3].answer);\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n \n }", "function getQuestions(){\n var question = questions[questionNum]\n var questionInner = document.querySelector('#quizPage')\n \n questionInner.innerHTML = \n `<div class=\"alert\"><h3>${question.question}</h3>`\n \n for( var i=0; i < question.answers.length; i++ ){\n var answer = question.answers[i]\n questionInner.innerHTML += `\n <button onClick=\"selectAnswer('${answer}')\" class=\"col container m-2 btn btn-primary btn-group-vertical w-sm-75 role = 'group\">${answer}</button>\n `\n } \n console.log(answer)}", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function loadChoices (answerOne) {\n var result = '';\n for (var i = 0; i < 4; i++) {\n result += ('<p class=ans' + ' ' + 'data-answer=' + answerOne[i] + '> ' + answerOne[i] + ' ' + '</p>' + '<br>'); \n }\n return result;\n}", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function loadQuestion(){\n //hit the API to get items returned and set them as the inner HTML of the id's provided\n $.get(\"http://jservice.io/api/random\", function(data){\n $(\"#category\").html(data[0].category.title)\n $(\"#point-value\").html(data[0].value)\n $(\"#question\").html(data[0].question)\n answer = data[0].answer //set variable of answer\n console.log(answer)\n })//end of API get call\n } //end of loadQuestion function", "function choice(){\n var answer = document.getElementsByName('q');\n for(i = 0; i < answer.length; i++) {\n if (answer[i].checked) {\n friend.selections.push(parseInt(answer[i].value));\n } \n // else {\n // \treturn alert(\"Please choose\");\n // \tquestionNumber--;\n // }\n }\n }", "function choose() {\r\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\r\n }", "function choose() {\r\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\r\n }", "function choose() {\r\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\r\n }", "function choose() {\r\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\r\n }", "function choose() {\r\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\r\n }", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function loadQuestion(quesIndex)\n{\n \n var ques = question[quesIndex];\n \n questionElement.textContent =ques.question;;\n \n answer1.textContent = ques.possibleAnswers[0];\n answer2.textContent = ques.possibleAnswers[1];\n answer3.textContent = ques.possibleAnswers[2];\n answer4.textContent = ques.possibleAnswers[3];\n \n console.log(ques.possibleAnswers[0]);\n\n \n\n}", "function choose() {\n \tselections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n }", "function getChoices (question){\n\t$(\"#radioA\").html(question.a.caption);\n\t$(\"#radioB\").html(question.b.caption);\n\t$(\"#radioC\").html(question.c.caption);\n\t$(\"#radioD\").html(question.d.caption); \n\n\tconsole.log(\"a :\" + question.a.caption);\n\tconsole.log(\"b :\" + question.b.caption);\n\tconsole.log(\"c :\" + question.c.caption);\n\tconsole.log(\"d :\" + question.d.caption);\n} //fucntion getChoices", "function question(questionNum) {\n $(\"h2\").text(allQuestions[questionNum].question);\n\n $.each(allQuestions[questionNum].choices, function (i, answers) {\n $(\"#\" + i).html(answers);\n });\n}", "function showAnswers(){\n let answerA = theQuestions[questionIndex].answer[0].list\n let answerB = theQuestions[questionIndex].answer[1].list\n let answerC = theQuestions[questionIndex].answer[2].list\n let answerD = theQuestions[questionIndex].answer[3].list\n btnTextA.textContent = answerA\n btnTextB.textContent = answerB\n btnTextC.textContent = answerC\n btnTextD.textContent = answerD\n multChoiceA.appendChild(btnTextA)\n multChoiceB.appendChild(btnTextB)\n multChoiceC.appendChild(btnTextC)\n multChoiceD.appendChild(btnTextD)\n }", "function choose() {\n\tselections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n\t}", "function getQuestion() {\n indexFinder = Math.floor(Math.random() * questionArray.length);\n question.innerText = \"\";\n question.innerText = questionArray[indexFinder].q;\n currentCorrectAnswer = questionArray[indexFinder].correct;\n}", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n\n }", "function showQuestions() {\n DOMSelectors.quizQuestion.innerHTML = questions[index].question;\n DOMSelectors.choice1.innerHTML = questions[index].choices[0];\n DOMSelectors.choice2.innerHTML = questions[index].choices[1];\n DOMSelectors.choice3.innerHTML = questions[index].choices[2];\n DOMSelectors.choice4.innerHTML = questions[index].choices[3];\n}", "function populate() { \n if(quiz.isEnded()) { // has the quiz ended yet? If so, show the user's score\n showScores();\n }\n else { // if not, populate that question\n // show question\n var element = document.getElementById(\"question\"); // jQuery version of this? Look it up and revise\n element.innerHTML = quiz.getQuestionIndex().text; // same, can I use jQuery to make this a bit cleaner and simpler?\n\n // show choices\n var choices = quiz.getQuestionIndex().choices; // established variable to grab and store question answer choices for THIS specific index position\n for(var i = 0; i < choices.length; i++) { // then, loop over all choices for this question \n var element = document.getElementById(\"choice\" + i); // create var, pointing at choices, select all 4 by using the i variable since it loops over all\n element.innerHTML = choices[i]; // set the button text to all choices listed (i)\n guess (\"button\" + i, choices[i]);\n }\n showProgress();\n }\n}", "function choose() {\r\n selections[questionCounter] = +$('input.answer:checked').val();\r\n }", "function getInput(){\n const clicked = document.querySelectorAll('.answer');\n \n for(var x = 0; x < clicked.length; x++){\n if(clicked[x].checked){\n return clicked[x].value;\n }\n }\n }", "function answers() {\n // for loop through answerlist\n for (var i = 0; i < triviaQuestions[currentQuestion].answerList.length; i++) {\n var choice = $(\"<input>\")\n choice.attr(\"type\", \"radio\")\n choice.attr(\"id\", triviaQuestions[currentQuestion].answerList[i])\n choice.attr(\"name\", triviaQuestions[currentQuestion].answerList)\n choice.attr(\"value\", triviaQuestions[currentQuestion].answerList[i])\n var label = $(\"<label>\")\n label.attr(\"for\", triviaQuestions[currentQuestion].answerList[i])\n label.html(triviaQuestions[currentQuestion].answerList[i])\n $(\".answers\").append(choice, label);\n }\n }", "function getQuestions() {\n var currentQuestion = quizQuestions[index];\n questions.textContent = currentQuestion.question\n answers.innerHTML = \"answers\"\n currentQuestion.answers.forEach(function(choice, i){\n var choiceBtn = document.createElement(\"button\")\n choiceBtn.setAttribute(\"class\", \"answers\")\n choiceBtn.setAttribute(\"value\", choice)\n choiceBtn.textContent = i + 1 + \": \" + choice \n answers.appendChild(choiceBtn)\n choiceBtn.onclick = verifyAnswer;\n })\n}", "function populate() {\n if(quiz.isEnded()) {\n showScores();\n }\n else {\n // show question\n var element = document.getElementById(\"question\");\n element.innerHTML = quiz.getQuestionIndex().text;\n\n // show options\n var choices = quiz.getQuestionIndex().choices;\n for(var i = 0; i < choices.length; i++) {\n var element = document.getElementById(\"choice\" + i);\n element.innerHTML = choices[i];\n guess(\"btn\" + i, choices[i]);\n } \n }\n}", "function getQuestion() {\n $(\".quiz\").show();\n\n //create var that references the questions array\n var currentQuestion = questions[currentQuestionIndex];\n //Display the current question\n questionEl.textContent = currentQuestion.title;\n\n //Creates a short hand variable for the forEach method that loops through each choice and change the text of the HTML buttons\n var allChoices = currentQuestion.choices;\n allChoices.forEach(function(choice, i) {\n document.querySelector(\".choice\" + i).innerHTML = \"<button class='btn'>\" + allChoices[i] + \"</button>\";\n });\n \n //Event listener that is used when the changed button is clicked\n buttons.addEventListener(\"click\", checkAnswer);\n}", "function FetchQuestionAnswers(){\n \n $('.Instructions').hide();\n $('#message').empty();\n $('#correctedAnswer').empty(); \n answered = true; \n $('.question').html('<h2>' + myQuestions[currentQuestion].question + '</h2>');\n for (var i=0;i<4;i++){\n var choices = $('<input>');\n var choicesLabel = $(\"<Label>\");\n choices.attr(\"type\",\"radio\");\n choices.attr(\"value\", letter[i]);\n choices.attr(\"id\",\"RadioAnswer\");\n choices.attr(\"Name\",\"answersRadio\");\n choices.addClass('option-input').addClass(\"radio\");\n choicesLabel.append(choices);\n choicesLabel.append(myQuestions[currentQuestion].answers[letter[i]]);\n $('.answerList').append(choicesLabel);\n }\n countdown();\n $(\"input[Name ='answersRadio']\").change(function() { \n //$('body').on('click', '#RadioAnswer', function(e) {\n console.log(\"radio button click event\"); \n userSelect = this.value;\n clearInterval(time);\n PopulateAllAnswers();\n });\n }", "function setQuestions(){\n\n\t//alert(\"I set questions\");\n\n\tif (whiteHouse == true){\n\n\t\tvar query_params = \"&keyword= White House\";\n\t\tvar endpoint = 'http://gravity.answers.com/endpoint/searches/questions?key=0365082c633528c9023c21eda59c909804d635b3';\n\n\t\t$(document).ready(function() {\n\t\t\t$.ajax({\n\t\t\t\ttype: \"GET\",\n\t\t\t\turl: endpoint,\n\t\t\t\tdata: query_params,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\tdocument.getElementById(\"questionOne\").innerHTML=(data.result[1].title + \" ?\"); //the index of result gets you the question. \n\t\t\t\tdocument.getElementById(\"questionTwo\").innerHTML=(data.result[2].title + \" ?\");\n\t\t\t\tdocument.getElementById(\"questionThree\").innerHTML=(data.result[3].title + \" ?\");\n\t\t\t\tdocument.getElementById(\"questionFour\").innerHTML=(data.result[4].title + \" ?\");\n\t\t\t\tdocument.getElementById(\"questionFive\").innerHTML=(data.result[5].title + \" ?\");\n\t\t\t\t\t//answer for answer \n\t\t\t\t\t//title for Question\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\telse if (lincolnMemorial == true){\n\n\t\tvar query_params = \"&keyword= Lincoln Memorial\";\n\t\tvar endpoint = 'http://gravity.answers.com/endpoint/searches/questions?key=0365082c633528c9023c21eda59c909804d635b3';\n\n\t\t$(document).ready(function() {\n\t\t\t$.ajax({\n\t\t\t\ttype: \"GET\",\n\t\t\t\turl: endpoint,\n\t\t\t\tdata: query_params,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\tdocument.getElementById(\"questionOne\").innerHTML=(data.result[1].title); //the index of result gets you the question. \n\t\t\t\tdocument.getElementById(\"questionTwo\").innerHTML=(data.result[2].title);\n\t\t\t\tdocument.getElementById(\"questionThree\").innerHTML=(data.result[3].title);\n\t\t\t\tdocument.getElementById(\"questionFour\").innerHTML=(data.result[4].title);\n\t\t\t\tdocument.getElementById(\"questionFive\").innerHTML=(data.result[5].title); //answer for answer , title for question\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\telse if (washingtonMonument == true){\n\n\t\tvar query_params = \"&keyword= washingtonMonument\";\n\t\tvar endpoint = 'http://gravity.answers.com/endpoint/searches/questions?key=0365082c633528c9023c21eda59c909804d635b3';\n\n\t\t$(document).ready(function() {\n\t\t\t$.ajax({\n\t\t\t\ttype: \"GET\",\n\t\t\t\turl: endpoint,\n\t\t\t\tdata: query_params,\n\t\t\t\tsuccess: function(data) {\n\t\t\t\tdocument.getElementById(\"questionOne\").innerHTML=(data.result[1].title);\n\t\t\t\tdocument.getElementById(\"questionTwo\").innerHTML=(data.result[2].title);\n\t\t\t\tdocument.getElementById(\"questionThree\").innerHTML=(data.result[3].title);\n\t\t\t\tdocument.getElementById(\"questionFour\").innerHTML=(data.result[4].title);\n\t\t\t\tdocument.getElementById(\"questionFive\").innerHTML=(data.result[5].title);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}\n\n\telse{\n\n\t\tdocument.getElementById(\"phrase\").innerHTML=\"Please walk within 100ft of the nearest landmark.\";\n\t\tdocument.getElementById(\"questionOne\").innerHTML=\"\"; //the index of result gets you the question. \n\t\tdocument.getElementById(\"questionTwo\").innerHTML=\"\";\n\t\tdocument.getElementById(\"questionThree\").innerHTML=\"\";\n\t\tdocument.getElementById(\"questionFour\").innerHTML=\"\";\n\t\tdocument.getElementById(\"questionFive\").innerHTML=\"\";\n\t}\n}", "function getAnswers() {\n\tlet data = document.querySelector('input[name=\"input\"]:checked').value;\n\tuserAnswers.push(data);\n\tconsole.log(userAnswers);\n}", "function choose() {\n selections[questionCounter] = +$('input[name=\"answer\"]:checked').val();\n}", "function generateResults(){\n //grabs answer user selected, current question number, and correct answer\n let selected = $('input[type=radio]:checked', '#question-form').val();\n let allQuestions = store.questions;\n let currentQuestionNumber = store.questionNumber;\n let correct = Object.values(allQuestions)[currentQuestionNumber].correctAnswer;\n \n //determines which view to generate based on if users selected the correct answer. if so, increments the score. determines\n if (correct === selected && currentQuestionNumber < store.questions.length) {\n store.score++;\n return generateCorrectPage();\n }\n else if (correct !== selected && currentQuestionNumber < store.questions.length) {\n return generateWrongPage();\n }\n}", "function getQuestions(answers) {\n \n // Generates a list of all question in the DOM\n generateQuestionList(answers);\n \n // Finds out if selected quiz has questionsPerPage option\n if (quiz.hasOwnProperty('questionsPerPage')) {\n \n // Generates questions per page option\n generateQuestionsPerPage();\n \n // Loads #questionPerPage page\n $( \":mobile-pagecontainer\" ).pagecontainer( \"change\", \"index.html#questionPerPage\", {\n role: \"page\",\n transition: \"slide\"\n });\n $(\".ui-content\").trigger(\"create\");\n \n } else {\n questions = 1;\n // Shows first question in #question page\n getFirstQuestion(questions);\n }\n}", "function askQuestion(i) {\n console.log(triviaGame[i]);\n//looping through the Array so it can appear on the div\n // for(let i=0;i<3;i++)\n //gameQuestion is the div for housing the trivia questions\n gameQuestion = $('#gameQuestion');\n gameQuestion.text(triviaGame[i].question);\n//the first choice from the array appears on the choice1 div\n$('#choice1').text(triviaGame[i].choices[0])\n //Needed to set the click event off first otherwise the alerts kept-->\n //--> on going\n $('#choice1').off()\n $('#choice1').on('click', () => {\n //this method is executed by evaluate and .html() sets the div on screen\n evaluate(triviaGame[i], $('#choice1').html())\n });\n //the process is repeated for the other two choices to choose from\n $('#choice2').text(triviaGame[i].choices[1])\n $('#choice2').off()\n $('#choice2').on('click', () => {\n evaluate(triviaGame[i], $('#choice2').html())\n });\n $('#choice3').text(triviaGame[i].choices[2])\n $('#choice3').off()\n $('#choice3').on('click', () => {\n evaluate(triviaGame[i], $('#choice3').html())\n });\n }", "function getUserAnswer() {\n var radios = document.getElementsByName(\"question\" + currentQuestion + \"Choices\");\n for (var i=0, len=radios.length; i<len; i++) { \n if ( radios[i].checked ) {\n return radios[i].value;\n }\n }\n return null\n }", "function getSelectedQuestion(questionId) { \n $.get(\"FAQ/GetEveryQuestion\", function (output) {\n answerElement = output.find(element => element.id == questionId);\n printSelectedAnswer(answerElement.answer);\n questionIdVar = questionId;\n enableVotes();\n printUpvotes(answerElement.upvote);\n printDownvotes(answerElement.downvote);\n });\n}", "function getResult(data) {\n $('#result-btn').on('click', function(e) {\n // gather all checked radio-button values\n var choices = $(\"input[type='radio']:checked\").map(function(i, radio) {\n return $(radio).val();\n }).toArray();\n\n // now you have an array of choices = [\"valueofradiobox1\", \"valueofradiobox2\", \"valueofradiobox2\"]\n // you'll need to do some calculations with this\n // a naive approachf would be to just choose the most common option - seems reasonable\n\n if (choices.length == data.questions.length){\n let outcome = (mode(choices));\n console.log(outcome);\n \n $(\"#full-phrase\").text(data.outcomes[outcome].text);\n $(\"#result-img\").attr(\"src\", data.outcomes[outcome].img);\n\n // from hardcoded html\n // $(\"#full-phrase\").text(getResultArray(mode(choices))[0]);\n // $(\"#result-img\").attr(\"src\", getResultArray(mode(choices))[1]);\n } else{\n console.log(\"?s answered: \" + choices.length);\n console.log(getResultArray(\"error\"));\n $(\"#full-phrase\").text(getResultArray(\"error\")[0]);\n }\n });\n}", "function loadQuestion() {\n randomQuestion = Math.floor(Math.random() * questions.length);\n document.getElementById('questions').innerHTML = questions[randomQuestion];\n\n// Create loop to generate random answer options of the questions array\n\n for (var i = 0; i < 4; i++) {\n document.getElementById('answer'+i).innerHTML = answers[randomQuestion][i];\n }\n}", "function getTextCompletionQuestions() {\n \n $.get(\"/api/textcompletionq\", function(data) {\n textcompletionquestions = data;\n textcompletionquestionsoriginal = data;\n \n //loop through questions to get the correct answers\n displayQuestions();\n getCorrectAnswers();\n });\n }", "async function getAnswer(answers) {\n\tlet result = '';\n\tif (answers.other_id) { // multiple choice (other + description)\n\t\t// const aux = {};\taux[answers[0].other_id] = `<outros>${answers[0].text}`;\n\t\tresult = `<outros>${answers.text}`; // add <outros> to signal user choosing outros option\n\t} else if (answers.text) { // text/comment box\n\t\tresult = answers.text;\n\t} else if (answers.choice_id) { // multiple choice (regular) / dropdown\n\t\tresult = answers.choice_id;\n\t} return result;\n}", "function getQuestion() {\n // Get current question\n let questionInfoEl = questions[questionNumEl];\n // If there are no questions left, stop time, end function\n if (questionInfoEl == undefined) {\n endGame();\n return;\n }\n\n // loop show choices\n for (let i = 0; i < responseOptionsEl.length; i++) {\n responseOptionsEl[i].textContent = i + 1 + \". \" + questionInfoEl.choices[i];\n responseOptionsEl[i].value = questionInfoEl.choices[i];\n responseOptionsEl[i].onclick = answerCheck;\n }\n\n document.getElementById(\"question-text\").textContent = questionInfoEl.title;\n // show the question\n questionContainerEl.classList.remove(\"hide\");\n}", "function getSelected() {\n let answer;\n\n //for each answer element, see which one is checked.\n answerEls.forEach(answerEl => {\n //if this particular answer element is checked, which gives us a true \n //or false, then answer is equal to the answer element dot ID.\n if(answerEl.checked) {\n answer = answerEl.id\n }\n })\n\n return answer;\n}", "function populate() {\n if (quiz.isOver()) {\n\n showScore();\n } else {\n //show question\n var element = document.getElementById(\"question\");\n element.innerHTML = quiz.getQuestionIndex().text;\n\n //show choices\n var choices = quiz.getQuestionIndex().choices;\n for (var i = 0; i < choices.length; i++) {\n var element = document.getElementById(\"choice\" + i);\n element.innerHTML = choices[i];\n guessAnswer(\"btn\" + i, choices[i]);\n }\n showProgress();\n }\n}", "function populate(){\r\n if(quiz.isEnded()){\r\n showScores();\r\n }\r\n else {\r\n //show questions\r\n var element = document.getElementById(\"question\");\r\n element.innerHTML = quiz.getQuestionIndex().text;\r\n\r\n //show options\r\n var choices = quiz.getQuestionIndex().choices;\r\n for(var i = 0; i < choices.length; i++){\r\n var element = document.getElementById(\"choice\" + i);\r\n element.innerHTML = choices[i];\r\n guess(\"btn\" + i, choices[i]);\r\n }\r\n\r\n showProgress();\r\n }\r\n}", "function getQuestions() {\n var questions = quizQuestions[currentQuest];\n questionsArray.innerHTML = \"<p>\" + questions.question + \"</p>\";\n choiceA.innerHTML = questions.choiceA;\n choiceB.innerHTML = questions.choiceB;\n choiceC.innerHTML = questions.choiceC;\n}", "function questionAnswers(){\r\n\t\t$(\"#question\").html(questions[i]);\r\n\t\t$(\"#answer1\").html(answers1[i]);\r\n\t\t$(\"#answer2\").html(answers2[i]);\r\n\t\t$(\"#answer3\").html(answers3[i]);\r\n\t\t$(\"#answer4\").html(answers4[i]);\r\n\t}", "function renderQuestAns(questions) {\n let showQuestion = $(`\n <form class=\"question-form\">\n <section class=\"quiz-bg\">\n <fieldset name=\"start-quiz\">\n <legend class=\"zzz\">zZz</legend>\n <h2 class=\"question-text\">${STORE[questions].question}</h2>\n </fieldset>\n </section>\n </form>\n `);\n\n let showChoices = $(showQuestion).find(\"fieldset\");\n STORE[questions].answers.forEach(function(ans, qindex) {\n $(`<span class=\"choices\"><input class=\"radio\" type=\"radio\" \n id=\"${qindex}\"\n value=\"${ans}\" \n name=\"answer\" required>${ans}</span>`).appendTo(showChoices);\n });\n $(`<button type=\"button\" class=\"submitButton\">Submit</button>`).appendTo(\n showChoices\n );\n $(\".display\").html(showQuestion);\n}", "function loadQuestion() { //Randomises what question is shown on quiz page.\r\n randQ = Math.floor(Math.random() * questions.length);\r\n document.getElementById('question').innerHTML = questions[randQ];\r\n\r\n for (var i = 0; i < 3; i++) { //Matches the options with the question.\r\n document.getElementById('otext' + i).innerHTML = options[randQ][i];\r\n }\r\n}", "function result(){\n \n const ansContainers = quizContainer.querySelectorAll('.answers');\n const resultsContainer = quizContainer.querySelectorAll('.results');\n mCQquestions.forEach( (crrQuestion, qNumber) => {\n if(currentSlide === qNumber) {\n const container = ansContainers[qNumber];\n const selector = `input[name=question${qNumber}]:checked`;\n const userAnswer = (container.querySelector(selector) || {}).value;\n if(userAnswer === crrQuestion.correctAnswer){\n ansContainers[qNumber].style.color = 'lightgreen';\n resultsContainer[qNumber].innerHTML = 'Congratulation!!! Your answer is correct.';\n } else if(userAnswer === undefined) {\n ansContainers[qNumber].style.color = 'red';\n resultsContainer[qNumber].innerHTML = 'Please select an option!';\n } else {\n ansContainers[qNumber].style.color = 'red';\n resultsContainer[qNumber].innerHTML = 'Your answer is wrong !! ';\n }\n }\n });\n }", "function quizQuestions() {\n currIndex = 0;\n var currQuest = questions[currIndex];\n\n // update the header\n questionHeader.textContent = currQuest.title;\n\n //loop through choices,\n currQuest.choices.forEach(function(choices) {\n // if (curreQuest <= (questions.choices.length - 1)) {\n //creating a button for each, assigning the data-attributes, and event listeners to save their answer\n var choiceButton = document.createElement(\"button\");\n choiceButton.setAttribute(\"class\", \"choice\");\n choiceButton.setAttribute(\"value\", choices);\n\n //saving choice as their answer...\n choiceButton.onclick = userAnswer;\n //displaying the choices\n choiceButton.textContent = choices;\n\n //hopefully displays on page\n chooseEl.appendChild(choiceButton);\n });\n}", "function getChoices(word) {\n startButton.style.display = \"none\";\n submitButton.style.display = \"block\";\n\n var answerRequest = new XMLHttpRequest();\n answerRequest.open(\"GET\", \"http://localhost:9292/questions/\" + currentQuestion + \"/choices\");\n answerRequest.addEventListener(\"load\", function(event) {\n var questionChoices = document.getElementById('questionChoices');\n var the_request = event.target;\n var choices = JSON.parse(the_request.responseText); //parses the objext returned by the server so that it can be processed as an array in javascript.\n \n for (var choice in choices){ \n var label = document.createElement(\"label\"); //creates a label tag element for choice\n var choiceQuestion = document.createElement(\"INPUT\"); //creates an input tag for choice\n choiceQuestion.setAttribute(\"type\", \"radio\"); // makes choiceQuestion a radio button\n choiceQuestion.name = \"question\" + currentQuestion + \"Choices\"; //sets the name of the button for future queries\n choiceQuestion.value = choices[choice]; //sets value for future queries when determining if selection was correct\n label.appendChild(choiceQuestion); //appends the radio button to the label (label wraps around radio button) \n label.appendChild(document.createTextNode(choices[choice])); //creates a text node for the label. sets element in choices array to the value\n questionChoices.appendChild(label); //appends the label to the div that is meant to store the choices\n questionChoices.appendChild(document.createElement('br')); //creates a line break and appends it to the div after each label has been appended. Stops each item from being listed on the same line.\n }\n });\n\n answerRequest.send();\n }", "function loadAnswers(){\n if (currentQuestion <= questions.length -1){\n answer1.textContent = questions[currentQuestion].answers.a;\n answer2.textContent = questions[currentQuestion].answers.b;\n answer3.textContent = questions[currentQuestion].answers.c;\n answer4.textContent = questions[currentQuestion].answers.d;\n } else {\n return;\n }\n}", "function getQuestion() {\n /*\n @TODO: write your function code here\n */\n // create question and buttons\n question_w = document.createElement(\"h2\");\n button1 = document.createElement(\"button\");\n button2 = document.createElement(\"button\");\n button3 = document.createElement(\"button\");\n button4 = document.createElement(\"button\");\n question_w.textContent = questions[currentQuestionIndex];\n // set namme of choices to each button\n button1.textContent = ansarray[currentQuestionIndex][0];\n button2.textContent = ansarray[currentQuestionIndex][1];\n button3.textContent = ansarray[currentQuestionIndex][2];\n button4.textContent = ansarray[currentQuestionIndex][3];\n // set data-index to each button\n question_w.setAttribute(\"style\",\"text-align:center\")\n button1.setAttribute(\"data-index\", 0 );\n button2.setAttribute(\"data-index\", 1 );\n button3.setAttribute(\"data-index\", 2 );\n button4.setAttribute(\"data-index\", 3 );\n // append question and button to html\n questionsEl.prepend(question_w);\n choicesEl.appendChild(button1);\n choicesEl.appendChild(button2);\n choicesEl.appendChild(button3);\n choicesEl.appendChild(button4);\n}", "function prepareAnswers (currentTour) {\n items = questions[currentTour].choices;\n correctAnswer = questions[currentTour].answer;\n console.log(items);\n console.log(correctAnswer);\n $(\"#answer-btn1\").html(questions[currentTour].choices[0]);\n $(\"#answer-btn2\").html(questions[currentTour].choices[1]);\n $(\"#answer-btn3\").html(questions[currentTour].choices[2]);\n $(\"#answer-btn4\").html(questions[currentTour].choices[3]);\n }", "function getQuestionContent(questionId) {\n let question = document.getElementById(\"q\" + questionId);\n let questionText = question.querySelector(\"#qi\" + questionId).value;\n let optionsElements = question.getElementsByClassName(\"options\");\n let optionsRadios = question.getElementsByClassName(\"radio-values\");\n let correctAnswer;\n let options = [];\n\n // make sure all necessary fields are filled out\n if (!questionText) {\n window.alert(\"Question cannot be blank.\")\n return;\n }\n\n for (let i = 0; i < optionsElements.length; i++) {\n if (!optionsElements[i].value) {\n window.alert(\"An option cannot be blank.\");\n return;\n } else {\n options.push(optionsElements[i].value);\n if (optionsRadios[i].checked) {\n correctAnswer = optionsElements[i].value;\n }\n }\n }\n\n if (!correctAnswer) {\n window.alert(\"You have not selected the correct answer.\")\n return;\n }\n\n // assemble object with acquired information\n let questionJSON = {\n \"questionId\" : questionId,\n \"questionText\": questionText,\n \"options\": options,\n \"correctAnswer\": correctAnswer\n }\n return questionJSON;\n}", "function choose(pageCounter) {\n if (questions[pageCounter].checkboxChoices != null) {\n var res = [];\n $(\"input[type=checkbox][name='answer']\")\n .filter(\":checked\")\n .each(function () {\n res.push($(this).val());\n });\n if (\n JSON.stringify(res) ==\n JSON.stringify(questions[pageCounter].correctAnswer)\n ) {\n //alert('correct');\n M.toast({ html: questions[pageCounter].correctResponse });\n } else {\n //alert('not correct');\n M.toast({ html: questions[pageCounter].incorrectResponse });\n }\n }\n\n if (questions[pageCounter].radioChoices != null) {\n var res = +$('input[name=\"answer\"]:checked').val();\n if (res === questions[pageCounter].correctAnswer) {\n //alert('correct');\n M.toast({ html: questions[pageCounter].correctResponse });\n } else {\n //alert('not correct');\n M.toast({ html: questions[pageCounter].incorrectResponse });\n }\n }\n\n /*\n\n if (questions[pageCounter].imageChoices != null) {\n var res = [];\n $(\"input[type=radio][name='answer']\")\n .filter(\":checked\")\n .each(function () {\n res.push($(this).val());\n });\n if (\n JSON.stringify(res) ==\n JSON.stringify(questions[pageCounter].correctAnswer)\n ) {\n //alert('correct');\n M.toast({ html: questions[pageCounter].correctResponse });\n } else {\n //alert('not correct');\n M.toast({ html: questions[pageCounter].incorrectResponse });\n }\n }*/\n //console.log(res);\n }", "function displayAnswers() {\n let question = STORE.questions[STORE.progress];\n for(let i=0; i < question.answers.length; i++) {\n $('.js-answers').append(`<input type = \"radio\" name = \"answers\" id = \"answer${i+1}\" value = \"${question.answers[i]}\" tabindex = \"${i+1}\">\n <label for = \"answer${i+1}\"> ${question.answers[i]} </label> <br/> <span id = \"js-r${i+1}\"> </span>`);\n }\n}", "function results() {\n // Answer variables.\n correct = 0;\n incorrect = 0;\n unanswered = 0;\n\n for (var i = 1; i < 11; i++) {\n\n if ($(\"input[name='q\" + i + \"']:checked\").val() == \"x\") {\n\n correct++;\n } else if ($(\"input[name='q\" + i + \"']:checked\").val() === undefined) {\n\n unanswered++;\n } else {\n\n incorrect++;\n }\n\n // Display results and hide unwanted elements.\n \n $(\"#quiz\").hide();\n $(\"#whichState\").hide();\n $(\"#validate\").hide();\n $(\"#score\").html(\"Correct: \" + correct + \"<br/>Incorrect: \" + incorrect + \"<br/>Unanswered: \" + unanswered);\n $(\"#timer\").hide();\n $(\"#tally\").show();\n $(\"#clear\").show();\n $(\"#jack\").show();\n }\n\n }", "function choose() {\n var checkBox = document.querySelectorAll('input[type=\"checkbox\"]:checked'),\n radioButton = document.querySelectorAll('input[type=\"radio\"]:checked');\n if (checkBox.length) {\n inputs = checkBox\n } else {\n inputs = radioButton\n }\n var names = [].map.call(inputs, function (input) {\n return input.value;\n }).join(','),\n input = JSON.parse(\"[\" + names + \"]\");\n selections[questionCounter] = input;\n }", "function displayQuestions() {\n // Show questions starting with question one\n var displayedQuestion = gameQuestionEl.innerHTML = questions[currentQuestion].question;\n // Console log displayed question\n console.log(\"Displayed question: \", displayedQuestion);\n // Display each answer choice for user to select from\n choiceA.innerHTML = questions[currentQuestion].choices[0];\n choiceB.innerHTML = questions[currentQuestion].choices[1];\n choiceC.innerHTML = questions[currentQuestion].choices[2];\n choiceD.innerHTML = questions[currentQuestion].choices[3];\n}", "function getquestions() {\n //section 1, question 1\n document.getElementById(\"favoritemovie\").innerHTML = quizjson.quiz.movies.q1.question;\n document.getElementById(\"movie1\").innerHTML = quizjson.quiz.movies.q1.options[0];\n document.getElementById(\"movie2\").innerHTML = quizjson.quiz.movies.q1.options[1];\n document.getElementById(\"movie3\").innerHTML = quizjson.quiz.movies.q1.options[2];\n document.getElementById(\"movie4\").innerHTML = quizjson.quiz.movies.q1.options[3];\n //section 1, question 2\n document.getElementById(\"mainstar1\").innerHTML = quizjson.quiz.movies.q2.question;\n document.getElementById(\"actor1\").innerHTML = quizjson.quiz.movies.q2.options[0];\n document.getElementById(\"actor2\").innerHTML = quizjson.quiz.movies.q2.options[1];\n document.getElementById(\"actor3\").innerHTML = quizjson.quiz.movies.q2.options[2];\n document.getElementById(\"actor4\").innerHTML = quizjson.quiz.movies.q2.options[3];\n //section 2, question 1\n document.getElementById(\"favoritetvshow\").innerHTML = quizjson.quiz.tv.q1.question;\n document.getElementById(\"show1\").innerHTML = quizjson.quiz.tv.q1.options[0];\n document.getElementById(\"show2\").innerHTML = quizjson.quiz.tv.q1.options[1];\n document.getElementById(\"show3\").innerHTML = quizjson.quiz.tv.q1.options[2];\n document.getElementById(\"show4\").innerHTML = quizjson.quiz.tv.q1.options[3];\n //section 2, question 2\n document.getElementById(\"mainstar2\").innerHTML = quizjson.quiz.tv.q2.question;\n document.getElementById(\"tvactor1\").innerHTML = quizjson.quiz.tv.q2.options[0];\n document.getElementById(\"tvactor2\").innerHTML = quizjson.quiz.tv.q2.options[1];\n document.getElementById(\"tvactor3\").innerHTML = quizjson.quiz.tv.q2.options[2];\n document.getElementById(\"tvactor4\").innerHTML = quizjson.quiz.tv.q2.options[3];\n}", "function getQuestion(ind)\n\t\t\t{\n\t\t\t\t//document.write(\"in question function\");\n\t\t\t\twindow.questions = [\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Grand Central Terminal, Park Avenue, New York is the world's\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"largest railway station\", \"highest railway station\",\"longest railway station\",\"None of the above\"], \n\t\t\t\t\t\tcorrectChoice: \"highest railway station\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Entomology is the science that studies\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"Behavior of human beings\", \"Insects\",\"history of technical and scientific terms\",\"The formation of rocks\"], \n\t\t\t\t\t\tcorrectChoice: \"Insects\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"For which of the following disciplines is Nobel Prize awarded?\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"Physics and Chemistry\", \"Physiology or Medicine\",\"Literature, Peace and Economics\",\"All of the above\"], \n\t\t\t\t\t\tcorrectChoice: \"All of the above\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Hitler party which came into power in 1933 is known as\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"Labour Party\", \"Nazi Party\",\"Ku-Klux-Klan\",\"Democratic Party\"], \n\t\t\t\t\t\tcorrectChoice: \"Nazi Party\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Each year World Red Cross and Red Crescent Day is celebrated on\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"May 8\", \"May 18\",\"June 8\",\"June 18\"], \n\t\t\t\t\t\tcorrectChoice: \"May 8\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Where is the great Barrier Reef?\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"Africa\", \"N.America\",\"S.America\",\"Asia\",\"Australia\"], \n\t\t\t\t\t\tcorrectChoice: \"Asutralia\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"For the Olympics and World Tournaments, the dimensions of basketball court are\", \n\t\t\t\t\t\tquestionType: 1, \n\t\t\t\t\t\tchoices: [ \"26 m x 14 m\", \"28 m x 15 m\",\"27 m x 16 m\",\"28 m x 16 m\"], \n\t\t\t\t\t\tcorrectChoice: \"28 m x 15 m\", \n\t\t\t\t\t\tscore: 5 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Filaria is caused by\", \n\t\t\t\t\t\tquestionType: 2, \n\t\t\t\t\t\tcorrectAnswer: \"Mosquito\", \n\t\t\t\t\t\tscore: 10 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"Fathometer is used to measure\", \n\t\t\t\t\t\tquestionType: 2, \n\t\t\t\t\t\tcorrectAnswer: \"Ocean depth\", \n\t\t\t\t\t\tscore: 10 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"For seeing objects at the surface of water from a submarine under water, the instrument used is\", \n\t\t\t\t\t\tquestionType: 2, \n\t\t\t\t\t\tcorrectAnswer: \"periscope\", \n\t\t\t\t\t\tscore: 10 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"East Timor, which became the 191st member of the UN, is in the continent of\", \n\t\t\t\t\t\tquestionType: 2, \n\t\t\t\t\t\tcorrectAnswer: \"Asia\", \n\t\t\t\t\t\tscore: 10 \n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tquestion: \"First Afghan War took place in\", \n\t\t\t\t\t\tquestionType: 2, \n\t\t\t\t\t\tcorrectAnswer: \"1839\", \n\t\t\t\t\t\tscore: 10 \n\t\t\t\t\t}\n\t\t\t\t];\n\n\t\t\t\tvar result = questions[ind]; \n\t\t\t\treturn result;\n\t\t\t}", "function makeQuestion() {\n const questionbox = document.querySelector('#questionbox');\n const responsebox = document.querySelector('#responsebox');\n responsebox.style.visibility='hidden';\n questionbox.style.visibility='visible';\n // create a variable called questionask\n let questionask = document.querySelector('#question');\n // print the current question\n questionask.innerHTML = questions[counter].ask;\n // loop through all of the answers\n for (let j=0; j < questions[counter].answers.length; j++){\n let answer = document.querySelectorAll('.answer');\n //print the current answer\n answer[j].innerHTML = questions[counter].answers[j].word;\n };\n }", "function extractQuestion() {\n var question = {question: \"\", answers: []};\n question.question = $('.questionText').val();\n $('.answerSlot').each(function() {\n console.log(this);\n var answer = {checked:\"false\", answer:\"\"}\n answer.checked = $(this).children(':nth-child(1)').is(':checked');\n answer.answer = $(this).children(':nth-child(2)').val();\n question.answers.push(answer);\n });\n return question;\n}", "function showAnswers() {\n choiceDisplay.innerText = \"\";\n for (let i = 0; i < quizBank[questionCounter].answers.length; i++) {\n let buttonInput = document.createElement(\"input\");\n buttonInput.setAttribute(\"type\", \"radio\");\n buttonInput.setAttribute(\"name\", \"answer\");\n buttonInput.setAttribute(\"value\", quizBank[questionCounter].answers[i]);\n buttonInput.setAttribute(\"id\", \"radioId\");\n let label = document.createElement(\"label\");\n label.setAttribute(\"for\", \"radioId\");\n label.innerHTML = quizBank[questionCounter].answers[i];\n choiceDisplay.appendChild(buttonInput);\n choiceDisplay.appendChild(label);\n }\n let submitButton = document.createElement(\"input\");\n submitButton.setAttribute(\"type\", \"submit\");\n submitButton.setAttribute(\"id\", \"submitId\");\n choiceDisplay.appendChild(submitButton);\n submitButton.addEventListener(\"click\", function () {\n let answers = document.getElementsByName(\"answer\");\n answers.forEach(function (answer) {\n if (answer.checked == true) {\n userSelection = answer.value;\n checkAnswers();\n }\n });\n });\n}", "display() {\n document.querySelector(\"#question\").innerHTML = this.question;\n for (let i = 0; i < 4; i++)\n showAnswer = selectValue(showAnswer, 4);\n answer1.innerHTML = this.answers[showAnswer[0]];\n answer2.innerHTML = this.answers[showAnswer[1]];\n answer3.innerHTML = this.answers[showAnswer[2]];\n answer4.innerHTML = this.answers[showAnswer[3]];\n }", "function populate() {\n if(quiz.isEnded()) {\n showScores();\n }\n else {\n // show question\n var element = document.getElementById(\"question\");\n element.innerHTML = quiz.getQuestionIndex().text;\n\n // show options\n var choices = quiz.getQuestionIndex().choices;\n for(var i = 0; i < choices.length; i++) {\n var element = document.getElementById(\"choice\" + i);\n element.innerHTML = choices[i];\n guess(\"btn\" + i, choices[i]);\n }\n\n showProgress();\n }\n}", "function selectAnswer() {\n\n}", "function initializePage() {\r\n\t$('.opt_a').hide();\r\n\t$('.sug').hide();\r\n\t$('#q1').show();\r\n\tconsole.log('Javascript connected!');\r\n\tvar numberofsuggestions = 10;\r\n\tfor (var i = 0; i < numberofsuggestions; i++) { \r\n \tvar suggestion = '#s' + i+ ' #opt1';\r\n \tconsole.log($(suggestion).text());\r\n \r\n \t\r\n\t}\r\n\t/*\tfor each suggestions\r\ncompare provided response with json properties (to be inputted)\r\nthen pick a random suggestion from those that matched\r\n\r\n*/\r\n\tvar strring = '#s'+Math.floor((Math.random() * \t10) + 1);\r\n\t\r\n\tconsole.log( strring);\r\n\t$(strring).show();\r\n}", "function generateAnswers() {\n isGameOver()\n var question = questionsList[questionsIndex].question\n $(\"#question\").text(question)\n $(\"#question\").show()\n for (var i = 0; i < 4; i++) {\n var answerSelectList = questionsList[questionsIndex].answerChoices[i]\n var correctChoice = questionsList[questionsIndex].correctChoice\n var answerSelect = $(\"<div>\");\n\n answerSelect.addClass(\"answer-detail\")\n answerSelect.attr(\"answer-select\", answerSelectList)\n answerSelect.attr(\"data-answer-detail\", [i])\n answerSelect.text(answerSelectList)\n\n $(\"#answer-box\").append(answerSelect)\n $(\"#answer-detail\").addClass(\"name\")\n $(\"#answer-detail\").attr(\"answer-select\", answerSelectList)\n $(\"#answer-detail\").attr(\"answer-index\", correctChoice)\n }\n onClick()\n }", "function displayQuestions(question) {\n questionElement.innerText = question.question\n question.answers.forEach(answer => {\n var button = document.createElement('button')\n button.innerText = answer.text\n button.classList.add('btn')\n if (answer.correct) {\n button.dataset.correct = answer.correct\n }\n button.addEventListener('click', selectAnswer)\n choiceEl.appendChild(button)\n })\n}", "function displayQuestions(question) {\n questionElement.innerText = question.question;\n question.answers.forEach(answer => {\n var button = document.createElement(\"button\");\n button.innerText = answer.text;\n button.classList.add(\"btn\");\n if (answer.correct) {\n button.dataset.correct = answer.correct;\n }\n button.addEventListener(\"click\", selectAnswer);\n choiceEl.appendChild(button);\n });\n}", "function takeQuestions() {\n\t\tlet questions=[]\n\t\tinputList=questionsContent.childNodes\n\t\tfor (i=0;i<inputList.length;i++) {\n\t\t\tquestions.push([inputList[i].querySelector('.question').value,inputList[i].querySelector('.anserw').value])\n\t\t}\n\t\tquestions.forEach(function(el) {\n\t\t\tif (el[0].length===0) {el[0]=' '}\n\t\t\tif (el[1].length===0) {el[1]=' '}\n\t\t})\n\t\treturn questions\n\t}", "function getActualQuizEl() {\n return $('[data-actual=\"true\"]');\n}", "function showQuestion(qAndA) {\n document.getElementById('question').innerText = qAndA.question;\n qAndA.answers.forEach(answer => {\n let button = document.createElement('button');\n button.innerText = answer.text;\n button.classList.add('answer');\n if (answer.correct) {\n button.dataset.correct = answer.correct\n\n }\n button.addEventListener('click', selectAnswer)\n document.getElementById('answers').appendChild(button)\n console.log('ping')\n })\n}", "function showAnswers(answers){\n // console.log(`Function showAnswers Started!`); \n document.getElementById(\"answers\").innerHTML = ``;\n for (var answer of answers) {\n document.getElementById(\"answers\").innerHTML += `<p><input class=\"answers\" type=\"radio\" name=\"ans\" value=\"${answer}\">${answer}</p>`; //display each answer as radiobutton option in the html with += \n }\n}", "function selected() {\n let answer = undefined;\n answerElements.forEach((answerElement) => {\n if (answerElement.checked) {\n answer = answerElement.id\n }\n\n });\n return answer;\n}", "function loadQuestion() {\n callTimer(numMinutes);\n getAnswer1.removeAttr(\"Correct-Answer\");\n getAnswer2.removeAttr(\"Correct-Answer\");\n getAnswer3.removeAttr(\"Correct-Answer\");\n getAnswer4.removeAttr(\"Correct-Answer\");\n getQuestion.text(questionsArr[QuestionNum].question);\n getAnswer1.text(questionsArr[QuestionNum].answers[0]);\n getAnswer2.text(questionsArr[QuestionNum].answers[1]);\n getAnswer3.text(questionsArr[QuestionNum].answers[2]);\n getAnswer4.text(questionsArr[QuestionNum].answers[3]);\n currentCorrectAnswer = questionsArr[QuestionNum].correctAnswers;\n if (currentCorrectAnswer === 0) {\n getAnswer1.attr(\"Correct-Answer\", true);\n } else if (currentCorrectAnswer === 1) {\n getAnswer2.attr(\"Correct-Answer\", true);\n } else if (currentCorrectAnswer === 2) {\n getAnswer3.attr(\"Correct-Answer\", true);\n } else {\n getAnswer4.attr(\"Correct-Answer\", true);\n }\n //used for testing/grading\n console.log(\"is getAnswer1 correct? \" + getAnswer1.attr(\"Correct-Answer\"));\n console.log(\"is getAnswer2 correct? \" + getAnswer2.attr(\"Correct-Answer\"));\n console.log(\"is getAnswer3 correct? \" + getAnswer3.attr(\"Correct-Answer\"));\n console.log(\"is getAnswer4 correct? \" + getAnswer4.attr(\"Correct-Answer\"));\n }" ]
[ "0.6990564", "0.6951023", "0.67626506", "0.6757923", "0.67193496", "0.66857815", "0.6649642", "0.65865886", "0.6501033", "0.6465727", "0.6458935", "0.6397727", "0.6389243", "0.6375311", "0.6374095", "0.63699275", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63460535", "0.63390154", "0.6337084", "0.633377", "0.633377", "0.633377", "0.633377", "0.633377", "0.6329596", "0.6315723", "0.6310937", "0.6298758", "0.6283917", "0.62817955", "0.62786835", "0.6268685", "0.6268148", "0.62447155", "0.62429196", "0.6240797", "0.6232848", "0.6231803", "0.62040466", "0.62033355", "0.6199292", "0.618699", "0.6175469", "0.61667144", "0.6165575", "0.61619294", "0.616111", "0.6149951", "0.61412394", "0.6129627", "0.6113264", "0.61129886", "0.6107023", "0.6101925", "0.6101395", "0.60842365", "0.60808146", "0.60497004", "0.6048117", "0.6043707", "0.6042549", "0.603225", "0.6026951", "0.6019614", "0.60165006", "0.60158956", "0.6013068", "0.6008371", "0.60057485", "0.59974325", "0.5994389", "0.59869194", "0.5986243", "0.5983907", "0.5978618", "0.5976634", "0.59751666", "0.59734964", "0.597324", "0.59642226", "0.5962665", "0.5961212", "0.59506", "0.59476703", "0.59458715", "0.5943305", "0.5935453", "0.5929467", "0.59222114", "0.591881", "0.59183294", "0.5905876" ]
0.64544886
11
Grades the question answers of the user
_gradeQuestions() { let totalPossible = 0; // total possible score of quiz let totalScored = 0; // total points scored let totalPenalised = 0; // total penalisation points (incorrect selections on multiples) let totalFinal = 0; // the final score for (let i = 0; i < this._data.length; i++) { let question = this._data[i]; totalPossible += question.weight; let scored = 0; let penal = 0; // get total correct for (let j = 0; j < question.answers.length; j++) { let answer = question.answers[j]; if (answer.is_correct && question._selectedAnswers.indexOf(answer.id.toString()) !== -1) scored += question.weight / question.answers.filter(ans => ans.is_correct === true).length; // penalise on multiple choice for incorrect selection else if (question.has_multiple_answers && !answer.is_correct && question._selectedAnswers.indexOf(answer.id.toString()) !== -1) { // we need to make sure that th penal += question.weight / question.answers.filter(ans => ans.is_correct === true).length; } } // make sure we dont remove points from the total if the penalisation points are larger than the scored points if (scored >= penal) { totalScored += scored; totalPenalised += penal; } } totalFinal = totalScored - totalPenalised; let resData = { totalPossibleScore: totalPossible, totalAchievedScore: totalScored, totalPenalisedScore: totalPenalised, totalFinalScore: totalFinal, percentageAchieved: Math.round(totalFinal / totalPossible * 100), dom_node: null }; return this._constructResultsDOMNode(resData); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function grade() {\n\n//question 1 answer r1\nif (answer1 === \"r1\") {\n correct++;\n } else if ((answer1 === \"r2\") || (answer1 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n\n//question 2 answer r3\nif (answer2 === \"r3\") {\n correct++;\n } else if ((answer2 === \"r2\") || (answer2 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 3 answer r1\nif (answer3 === \"r1\") {\n correct++;\n } else if ((answer3 === \"r2\") || (answer3 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 4 answer r2\nif (answer4 === \"r2\") {\n correct++;\n } else if ((answer4 === \"r1\") || (answer4 === \"r3\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n//question 5 answer r3\nif (answer5 === \"r3\") {\n correct++;\n } else if ((answer5 === \"r2\") || (answer5 === \"r1\")) {\n incorrect++;\n } else {\n unanswered++;\n }\n}", "function scoreAnswers(){}", "function result()\n\t{\n\t\t{\n\t\t\t/* for( i=0; i<questions.length; i++ )\n\t\t\t\t {\n\t\t\t\t checkAnswers( questions[i]);\t\t\n\t\t\t\t } */\n\t\t\t\t\n\t\t\t//To test in console.log\n\t\t\tconsole.log( \"a1 Score is: \" + checkAnswers( questions[0] ) );\n\t\t\tconsole.log( \"a2 Score is: \" + checkAnswers( questions[1] ) );\n\t\t\tconsole.log( \"a3 Score is: \" + checkAnswers( questions[2] ) );\n\t\t\tconsole.log( \"a4 Score is: \" + checkAnswers( questions[3] ) );\n\t\t\tconsole.log( \"a5 Score is: \" + checkAnswers( questions[4] ) );\n\t\t\t\n\t\t\t// To accumulate total marks in to one variable \n\t\t\tvar m1 = parseInt( checkAnswers( questions[0] ) );\n\t\t\tvar m2 = parseInt( checkAnswers( questions[1] ) );\n\t\t\tvar m3 = parseInt( checkAnswers( questions[2] ) );\n\t\t\tvar m4 = parseInt( checkAnswers( questions[3] ) );\n\t\t\tvar m5 = parseInt( checkAnswers( questions[4] ) );\n\n\t\t\tvar total = m1 + m2 + m3 + m4 + m5;\n\n\t\t\tconsole.log( \"Total Score is: \" + total );\n\t\t\t\n\t\t\tquiz.answersBox.value = \"Total Score is: \" + total;\n\t\t}\n\t}", "function evaluateAnswers() {\n arrAnswers.forEach(objAnswer => {\n arrAnswerVotes[objAnswer.answer]++;\n\n // If answer is correct, we give the user points\n if(currentReactive.correct[objAnswer.answer] == true)\n {\n let points = 100 - 40*(objAnswer.pastTime/totalTime);\n points = Math.ceil(points);\n objGame.Players.forEach(player => {\n if(player.username === objAnswer.username) player.points = Number(player.points) + points;\n });\n }\n });\n}", "function calcScore(){\n\tfor (var i = 0; i < userPicks.length; i++) {\n\t\tif(userPicks[i] == \"correct\"){\n\t\t\tcounters.updateCorrect();\n\t\t}\n\t\telse{\n\t\t\tcounters.updateIncorrect();\n\t\t}\n\t};\n\n\tif (userPicks.length < 6) {\n\t\tcounters.unanswered = 6 - userPicks.length;\n\t}\n\n}", "function gradeQuiz() {\n var usersArray = makeUserArray();\n scoreQuiz(usersArray);\n colorAnswers(usersArray);\n}", "function keepingScore() {\n\n var userAnswer1 = $(\"input[name='answer1']:checked\").val();\n var userAnswer2 = $(\"input[name='answer2']:checked\").val();\n var userAnswer3 = $(\"input[name='answer3']:checked\").val();\n var userAnswer4 = $(\"input[name='answer4']:checked\").val();\n var userAnswer5 = $(\"input[name='answer5']:checked\").val();\n var userAnswer6 = $(\"input[name='answer6']:checked\").val();\n var userAnswer7 = $(\"input[name='answer7']:checked\").val();\n\n // Q1\n if (userAnswer1 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer1 == questions[0].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q2\n if (userAnswer2 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer2 == questions[1].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q3\n if (userAnswer3 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer3 == questions[2].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q4\n if (userAnswer4 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer4 == questions[3].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q5\n if (userAnswer5 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer5 == questions[4].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q6\n if (userAnswer6 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer6 == questions[5].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n }\n\n // Q7\n if (userAnswer7 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer7 == questions[6].answer) {\n\n correctAnswers++;\n }\n else {\n\n wrongAnswers++;\n } \n\n}", "function scoreCount() {\n for (var i = 0; i < userSelection.length; i++) {\n // If user selected an answer\n if (userSelection[i].checked) {\n // check if what the user select is equal to the array answers\n\n if (answers.indexOf(userSelection[i].value) !== -1) {\n correctAnswer++;\n } else {\n incorrectAnswer++;\n }\n }\n }\n //check how many questions were blank by subtracting the if/else values from above from the total number of questions.\n\n var totalAnswered = correctAnswer + incorrectAnswer;\n\n if (totalAnswered !== totalQuestions) {\n blank = totalQuestions - totalAnswered;\n }\n\n $(\"#correct\").html(\" \" + correctAnswer);\n $(\"#incorrect\").html(\" \" + incorrectAnswer);\n $(\"#blank\").html(\" \" + blank);\n } //end scoreCount", "function gradeTestME() {\n \n var i;\n for (var i = 0; i < questionsME.length; i++) {\n if (Response = Answer){\n totalScore++;\n }\n if (q2 = a2){\n totalScore++;\n }\n if (q3 = a3){\n totalScore++;\n }\n if (q4 = a5){\n totalScore++;\n } \n if (q6 = a7){\n totalScore++;\n } \n if (q8 = a8){\n totalScore++;\n }\n if (q9 = a9){\n totalScore++;\n }\n if (q10 = a10){\n totalScore++;\n }\n if (q11 = a11){\n totalScore++;\n }\n if (q12 = a12){\n totalScore++;\n }\n return totalScore;\n }\n}", "function grader(userAns, sum){\n\n counter++;\n console.log('user: ' + userAns);\n console.log('answer: ' + sum);\n if(userAns == sum){\n counterCorrect++;\n console.log('yes');\n\n }\n else{\n counterWrong = counterWrong + 1;\n console.log('wrong');\n \n }\n\n //number of problems in game\n counter = counterCorrect + counterWrong;\n if(counter === 100){ // number of problems\n result = counterCorrect/100;\n result = result * 100; \n clearInterval(stop);\n document.getElementById('main-question-box').style.display = 'none'; \n document.getElementById('result').style.display = 'block';\n document.getElementById('result').textContent = 'Score: ' + result + '%';\n }\n\n }", "function keepingScore() {\n\n var userAnswer1 = $(\"input[name='answer1']:checked\").val();\n var userAnswer2 = $(\"input[name='answer2']:checked\").val();\n var userAnswer3 = $(\"input[name='answer3']:checked\").val();\n var userAnswer4 = $(\"input[name='answer4']:checked\").val();\n var userAnswer5 = $(\"input[name='answer5']:checked\").val();\n var userAnswer6 = $(\"input[name='answer6']:checked\").val();\n var userAnswer7 = $(\"input[name='answer7']:checked\").val();\n var userAnswer8 = $(\"input[name='answer8']:checked\").val();\n var userAnswer9 = $(\"input[name='answer9']:checked\").val();\n var userAnswer10 = $(\"input[name='answer10']:checked\").val();\n \n \n // Question 1\n if (userAnswer1 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer1 == questions[0].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 2\n if (userAnswer2 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer2 == questions[1].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 3\n if (userAnswer3 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer3 == questions[2].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 4\n if (userAnswer4 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer4 == questions[3].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 5\n if (userAnswer5 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer5 == questions[4].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 6\n if (userAnswer6 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer6 == questions[5].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 7\n if (userAnswer7 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer7 == questions[6].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 8\n if (userAnswer8 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer8 == questions[7].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 9\n if (userAnswer9 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer9 == questions[8].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n // Question 10\n if (userAnswer10 === undefined) {\n\n unanswered++;\n }\n else if (userAnswer10 == questions[9].answer) {\n\n correctAnswers++;\n }\n else {\n\n incorrectAnswers++;\n }\n\n \n}", "function quizResult(){\n document.querySelector(\".total-questions\").innerHTML=myApp.length;\n document.querySelector(\".correct\").innerHTML=score;\n document.querySelector(\".wrong\").innerHTML=score;\n const percentage=(score/myApp.length)*100;\n document.querySelector(\".percentage\").innerHTML=percentage.toFixed(2) + \"%\";\n}", "function scoreCount() {\n for (var i = 0; i < data.length; i++) {\n\n // If user selected an answer\n if (data[i].checked) {\n\n // check if what the user select is equal to the array answers\n\n if (answers.indexOf(data[i].value) !== -1) {\n correct++;\n } else {\n incorrect++;\n }\n }\n }\n //check how many questions were blank\n //subtracting the if/else values from above from TOTAL Q's\n \n var totalAnswered = correct + incorrect;\n console.log(totalAnswered);\n if (totalAnswered !== totalQuizQuestions) {\n unanswered = totalQuizQuestions - totalAnswered;\n }\n\n $('#correct').html(\" \" + correct);\n $('#incorrect').html(\" \" + incorrect);\n $(\"#unanswered\").html(\" \" + unanswered);\n }", "function checkAnswer () {\n console.log(userSelected.text);\n\n if (userSelected === questions[i].correctAnswer) {\n score ++;\n $(\"#score\").append(score);\n $(\"#answerCheck\").append(questions[i].rightReply);\n i++;\n } else {\n $(\"#answerCheck\").append(questions[i].wrongReply);\n i++;\n } \n }", "function myFunction() {\n\n //Create variable to count correct answers \n // var correctAnswers = 0;\n var answers = 0;\n //Create variables for each question's input value\n //Create variables for each question's input value\n var quizOne = $(\"input:radio[name=question1]:checked\").val();\n var quizTwo = $(\"input:radio[name=question2]:checked\").val();\n var quizThree = $(\"input:radio[name=question3]:checked\").val();\n var quizFour = $(\"input:radio[name=question4]:checked\").val();\n var quizFive = $(\"input:radio[name=question5]:checked\").val();\n var quizSix = $(\"input:radio[name=question6]:checked\").val();\n var quizSeven = $(\"input:radio[name=question7]:checked\").val();\n var quizEight = $(\"input:radio[name=question8]:checked\").val();\n\n\n\n\n\n\n if (quizOne == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizTwo == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizThree == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizFour == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizFive == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizSix == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizSeven == \"correct\") {\n answers = answers + 12.5;\n }\n if (quizEight == \"correct\") {\n answers = answers + 12.5;\n }\n\n\n\n document.getElementById(\"message\").innerHTML = \"Score is \" + answers + \"%\";\n document.getElementById(\"result\").style.visibility = \"visible\";\n}", "function calculateScore (answerArray, questionArray) {\n answerArray.forEach(function (question) {\n if (question.answer === undefined || question.answer === '') {\n score.noOfUnanswered += 1\n } else {\n questionArray.forEach(function (answer) {\n if (answer.id === question.id) {\n if (answer.answer === question.answer) {\n score.noOfCorrect += 1\n } else {\n score.noOfIncorrect += 1\n }\n }\n })\n }\n })\n }", "function showAnswers(){\t\n\t\tvar rightAnswers = 0;\n\t\tvar wrongAnswers = 0;\n\t\tvar userInput1 = $('#a1 input:checked').val();\n\t\tvar userInput2 = $('#a2 input:checked').val();\n\t\tvar userInput3 = $('#a3 input:checked').val();\n\t\tvar userInput4 = $('#a4 input:checked').val();\n\t\tvar userInput5 = $('#a5 input:checked').val();\n\t\tif (userInput1 === 'quail'){\n\t\t\trightAnswers++;\n\t\t}\n\t\telse {\n\t\t\twrongAnswers++;\n\t\t}\n\t\tif (userInput2 === 'frog') {\n\t\t\trightAnswers++;\n\t\t}\n\t\telse {\n\t\t\twrongAnswers++;\n\t\t}\n\t\tif (userInput3 === 'bear') {\n\t\t\trightAnswers++;\n\t\t}\n\t\telse {\n\t\t\twrongAnswers++;\n\t\t}\n\t\tif (userInput4 === 'avacado') {\n\t\t\trightAnswers++;\n\t\t}\n\t\telse {\n\t\t\twrongAnswers++;\n\t\t}\n\t\tif (userInput5 === 'artichoke') {\n\t\t\trightAnswers++;\n\t\t}\n\t\telse {\n\t\t\twrongAnswers++;\n\t\t}\n\t\tconsole.log('Input1:' + userInput1);\n\t\tconsole.log('Input2: ' + userInput2);\n\t\tconsole.log('Input3: ' + userInput3);\n\t\tconsole.log('Input4: ' + userInput4);\n\t\tconsole.log('Input5: ' + userInput5);\n\t\tconsole.log('Right Answers: ' + rightAnswers);\n\t\tconsole.log('Wrong Answers: ' + wrongAnswers);\n\t\t$('#time').remove();\n\t\t$('#submitButton').remove();\n\t\t$('#formQuestions').remove();\n\t\t$('#questions').html('<div id=\"results\">Results</div>');\n\t\t$('#questions').html(\"<div>\" + 'Right Answers: ' + rightAnswers + \"</div>\");\n\t\t$('#questions').append(\"<div>\" + 'Wrong or Empty Answers: ' + wrongAnswers + \"</div>\");\n\n\t}", "function scoreKeep(){\n var userAnswer1 = $(\"input[name='answer1']:checked\").val();\n var userAnswer2 = $(\"input[name='answer2']:checked\").val();\n var userAnswer3 = $(\"input[name='answer3']:checked\").val();\n var userAnswer4 = $(\"input[name='answer4']:checked\").val();\n var userAnswer5 = $(\"input[name='answer5']:checked\").val();\n var userAnswer6 = $(\"input[name='answer6']:checked\").val();\n var userAnswer7 = $(\"input[name='answer7']:checked\").val();\n\n //now keep score for all questions and answers\n if (userAnswer1 === undefined) {\n\n unanswered++;\n } else if (userAnswer1 == questions[0].answer) {\n\n correctAnswers++;\n } else {\n\n incorrectAnswers++;\n }\n if(userAnswer2 === undefined) {\n unanswered++;\n } else if (userAnswer2 == questions[1].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n if(userAnswer3 === undefined) {\n unanswered++;\n } else if (userAnswer3 == questions[2].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n if(userAnswer4 === undefined) {\n unanswered++;\n } else if (userAnswer4 == questions[3].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n if(userAnswer5 === undefined) {\n unanswered++;\n } else if (userAnswer5 == questions[4].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n if(userAnswer6 === undefined) {\n unanswered++;\n } else if (userAnswer6 == questions[5].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n if(userAnswer7 === undefined) {\n unanswered++;\n } else if (userAnswer7 == questions[6].answer){\n correctAnswers++;\n } else {\n incorrectAnswers++;\n }\n}", "function submitAnswers(){\n\tvar total = 5;\n\tvar score = 0;\n\n\t//get user input\n\tvar q1 = document.forms[\"quizForm\"][\"q1\"].value;\n\tvar q2 = document.forms[\"quizForm\"][\"q2\"].value;\n\tvar q3 = document.forms[\"quizForm\"][\"q3\"].value;\n\tvar q4 = document.forms[\"quizForm\"][\"q4\"].value;\n\tvar q5 = document.forms[\"quizForm\"][\"q5\"].value;\n\n\t\n\n\t\n\t//validate that all questions are answered\n\n\tfor(var i=1; i<=total; i++){\n\t\tif(eval('q'+i) == null || eval('q'+i) ==''){\n\t\t\talert('You missed question ' + i );\n\t\t\treturn false;\n\t}\n\t\n\n\t}\n\n\tvar ans = [\"c\", \"d\", \"b\", \"c\", \"b\"];\n\n\tfor(var i=1; i<=total; i++){\n\t\t\n\t\t\tif(eval('q'+i) == ans[i-1]){\n\t\t\t\tscore++;\n\t\t}\n\t\t\n\t}\n\t\n\n\n\tvar results = document.getElementById('results');\n\tresults.innerHTML = '<h3>You scored <span>'+score+'</span> out of <span>'+total+' </span> </h3>';\n\talert('You scored '+score+ ' out of '+total+'.');\n\n\treturn false;\n\n}", "function checkAnswer() {\n if (userAnswer === currentQuestion.correctAnswer) {\n // add to the number of correct answers\n points++;\n\n // color the answers green\n answerContainers[questionNumber].style.color = \"darkgreen\";\n }\n // if answer is wrong or blank\n else {\n // color the answers red\n answerContainers[questionNumber].style.color = \"red\";\n }\n }", "function calculateScore(qAnswers, uAnswers) {\n var score = 0;\n for (i = 0; i <= numberOfQuestions - 1; i++) {\n \n if(qAnswers[i][4] === uAnswers[i]){\n score = score + 1; \n } else {\n continue;\n }\n }\n return score; \n}", "function scoreSum(correctAnswers, testAnswers) {\n\tlet score = 0;\n\tfor (let i = 0; i < correctAnswers.length; i++) {\n\t\tif (testAnswers[i] == correctAnswers[i]) {\n\t\t\tscore++;\n\t\t}\n\t}\n\treturn `You answered correctly ${score} questions`;\n}", "function checkAnswer(answer) {\n if (answer[userAnswer].isCorrect) {\n console.log('Your answer is correct! :D');\n score++;\n } else {\n console.log('Your answer is incorrect! D:');\n if (score > 0) {\n score--;\n }\n }\n}", "calculateGrade(state, action) {\n var numOfQuestion = state.student.test.questions ? state.student.test.questions.length : 0\n var americanQuestionSum = 0\n var currentGrade = 0\n for (let i = 0; i < numOfQuestion; i++) {\n //if multy question\n if (!state.student.test.questions[i].openQuestion) {\n americanQuestionSum++;\n }\n }\n for (let c = 0; c < state.student.test.answersArray.length; c++) {\n if (state.student.test.answersArray[c].is_correct)\n currentGrade += 100;\n }\n\n //we finished to check the student answers\n //set the student grade\n state.student.test.multyQuestion_grade = americanQuestionSum == 0 ? 0 : currentGrade / americanQuestionSum;\n state.student.test.grade = numOfQuestion == 0 ? 0 : currentGrade / numOfQuestion;\n }", "function tabulateAnswers() {\n // initialize variables for each choice's score\n // If you add more choices and outcomes, you must add another variable here.\n var yes1score = 0;\n var no1score = 0;\n var yes2score = 0;\n var no2score = 0;\n var yes3score = 0;\n var no3score = 0;\n var yes4score = 0;\n var no4score = 0;\n var yes5score = 0;\n var no5score = 0;\n var yes9score = 0;\n var no9score = 0;\n\n var c1score = 0;\n var c2score = 0;\n var c3score = 0;\n var c4score = 0;\n\n // get a list of the radio inputs on the page\n var choices = document.getElementsByTagName('input');\n console.log(choices)\n // loop through all the radio inputs\n for (i=0; i<choices.length; i++) {\n // if the radio is checked..\n if (choices[i].checked) {\n // add 1 to that choice's score\n if (choices[i].value == 'yes1score') {\n yes1score = yes1score + 1;\n }\n if (choices[i].value == 'no1score') {\n no1score = no1score + 1;\n }\n if (choices[i].value == 'yes2score') {\n yes2score = yes2score + 1;\n }\n if (choices[i].value == 'yes3score') {\n yes3score = yes3score + 1;\n }\n if (choices[i].value == 'no2score') {\n no3score = no3score + 1;\n }\n if (choices[i].value == 'c4') {\n c4score = c4score + 1;\n }\n if (choices[i].value == 'yes1') {\n c1score = c1score + 1;\n }\n if (choices[i].value == 'c2') {\n c2score = c2score + 1;\n }\n if (choices[i].value == 'c3') {\n c3score = c3score + 1;\n }\n if (choices[i].value == 'c4') {\n c4score = c4score + 1;\n }\n if (choices[i].value == 'c4') {\n c4score = c4score + 1;\n }\n if (choices[i].value == 'c4') {\n c4score = c4score + 1;\n }\n\n //calling all the text boxes\n var answerbox = document.getElementById('box');\n\n // If you add more choices and outcomes, you must add another if statement below.\n }\n }\n // Find out which choice got the highest score.\n // If you add more choices and outcomes, you must add the variable here.\n var maxscore = Math.max(yes1score,no1score,yes2score,no2score,yes3score,no3score,yes4score,no4score,yes5score,no5score,yes9score,no9score);\n\n // Display answer corresponding to that choice\n var answerbox = document.getElementById('answer');\n if (c1score == maxscore) { // If user chooses the first choice the most, this outcome will be displayed.\n answerbox.innerHTML = \"Thank you for taking our survey! Feel free to contact us for more questions or feedback\";\n }\n if (c2score == maxscore) { // If user chooses the second choice the most, this outcome will be displayed.\n answerbox.innerHTML = \"Thank you for taking our survey! Feel free to contact us for more questions or feedback\";\n }\n if (c3score == maxscore) { // If user chooses the third choice the most, this outcome will be displayed.\n answerbox.innerHTML = \"Thank you for taking our survey! Feel free to contact us for more questions or feedback\";\n }\n if (c4score == maxscore) { // If user chooses the fourth choice the most, this outcome will be displayed.\n answerbox.innerHTML = \"Thank you for taking our survey! Feel free to contact us for more questions or feedback\";\n }\n // If you add more choices, you must add another response below.\n}", "function incrementUserScore() {\n score++;\n incrementCorrectAnswers(score);\n}", "function getAnswers() {\n $(\"#submit\").on(\"click\", function (event) {\n event.preventDefault();\n\n //First question data and if statement to put data in scoring categories\n var q1Data = $('input[name=q1]:checked').val();\n // console.log(q1Data);\n if (q1Data == \"true\") {\n correct++;\n console.log(q1Data + correct);\n } else if (q1Data == \"false\") {\n incorrect++;\n console.log(q1Data + incorrect);\n } else {\n unanswered++\n console.log(q1Data + unanswered);\n }\n\n //Second question data\n var q2Data = $('input[name=q2]:checked').val();\n if (q2Data == \"true\") {\n correct++;\n console.log(q2Data + correct);\n } else if (q2Data == \"false\") {\n incorrect++;\n console.log(q2Data + incorrect);\n } else {\n unanswered++\n console.log(q2Data + unanswered);\n }\n\n //Third question data\n var q3Data = $('input[name=q3]:checked').val();\n if (q3Data == \"true\") {\n correct++;\n console.log(q3Data + correct);\n } else if (q3Data == \"false\") {\n incorrect++;\n console.log(q3Data + incorrect);\n } else {\n unanswered++\n console.log(q3Data + unanswered);\n }\n //fourth question data\n var q4Data = $('input[name=q4]:checked').val();\n if (q4Data == \"true\") {\n correct++;\n console.log(q4Data + correct);\n } else if (q4Data == \"false\") {\n incorrect++;\n console.log(q4Data + incorrect);\n } else {\n unanswered++\n console.log(q4Data + unanswered);\n }\n\n })\n }", "function gradeQuiz() {\n if(submitPushes === 0 ){\n submitPushes++;\n var answerContainers = quizContainer.querySelectorAll(\".answers\");\n var correctAnswers = 0;\n possibleQuestions.forEach(\n (currentQuestion, questionNumber) => {\n var answerContainer = answerContainers[questionNumber];\n var selector = `input[name=question${questionNumber}]:checked`;\n var selected = (answerContainer.querySelector(selector) || {}).value;\n\n if (selected === currentQuestion.correctAnswer) {\n correctAnswers++;\n answerContainers[questionNumber].style.color = 'lightgreen';\n }\n });\n resultsContainer.innerHTML = (`${correctAnswers} out of ${possibleQuestions.length}`);\n }\n}", "function displayScore() {\r\n var score = $('<p>',{id: 'question'});\r\n \r\n var numCorrect = 0;\r\n for (var i = 0; i < selections.length; i++) {\r\n if (selections[i] === questions[i].correctAnswer) {\r\n numCorrect++;\r\n }\r\n }\r\n \r\n var result = numCorrect*100/questions.length;\r\n\tresult = Math.round(result);\r\n\tscore.append('You scored ' + result + ' % ');\r\n\t\t\t \r\n return score;\r\n }", "function checkAnswer() {\n\n // get length of radio buttons form - changes dependent on quiz difficulty\n let numOfRadios = document.getElementById(\"mc-form-right\").length;\n\n // get scores\n let oldCorrectTally = parseInt((document.getElementById(\"correct-tally-num\").innerText));\n let oldIncorrectTally = parseInt((document.getElementById(\"incorrect-tally-num\").innerText));\n\n let pickedAnswer;\n\n // Check status of radio buttons\n for (i = 0; i < numOfRadios; i++) {\n\n // if a radio button is picked\n if (document.getElementsByTagName(\"input\")[i].checked) {\n\n // get the user's answer\n pickedAnswer = document.getElementsByTagName(\"label\")[i].innerText;\n\n // if user answer is correct, increment correct tally - if not, increment incorrect tally\n if (pickedAnswer === mcQuestion) {\n document.getElementById(\"correct-tally-num\").innerText = ++oldCorrectTally;\n } else {\n document.getElementById(\"incorrect-tally-num\").innerText = ++oldIncorrectTally;\n }\n\n // increment progress tally, remove old question and answers, and regenerate question\n questionsAnswered++;\n document.getElementsByTagName(\"h1\")[0].remove();\n document.getElementById(\"mc-form-left\").remove();\n document.getElementById(\"mc-form-right\").remove();\n document.getElementsByTagName(\"p\")[1].remove();\n generateQuestion();\n break;\n\n } else {\n if (i === numOfRadios - 1) {\n chooseAnswerPopUp();\n }\n continue;\n }\n }\n\n // add user answer to array for feedback later\n userAnswers.push(pickedAnswer);\n\n // get score\n finalCorrect = parseInt((document.getElementById(\"correct-tally-num\").innerText));\n\n // end game if questions answered = game length\n if (questionsAnswered === parseInt(gameLength)) {\n showAnswers();\n }\n}", "function scoreCount() {\n for (var i = 0; i < data.length; i++) {\n \n // If user selected an answer\n if (data[i].checked) {\n \n // check if what the user select is equal to the array answers\n \n if (answers.indexOf(data[i].value) !== -1) {\n correctAnswer++;\n } else {\n incorrectAnswer++;\n }\n }\n }\n\n //check how many questions were blank by subtracting the if/else values from above from the total number of questions.\n\n var totalAnswered = correctAnswer + incorrectAnswer;\n console.log(totalAnswered);\n if (totalAnswered !== totalQuiz) {\n blank = totalQuiz - totalAnswered;\n }\n\n $('#correct').html(\" \" + correctAnswer);\n $('#incorrect').html(\" \" + incorrectAnswer);\n $(\"#blank\").html(\" \" + blank);\n\n } //end scoreCount", "function choice() {\n \n for (var i = 0; i < 4; i++) {\n if(document.getElementById('option' + i).checked){ // if answer is checked\n var answers = i; //document.getElementById('option' + i).value\n } \n }\n\n// Create conditions to check if answer choices are right or wrong\n\n if(randomQuestion == 0) { // question in array 0\n if(answers == 1){ // correct answer is choice in index 1\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n }else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n }\n }\n\n if(randomQuestion == 1) {\n if(answers == 0){\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n } else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n\n }\n }\n\n if(randomQuestion == 2) {\n if(answers == 2){\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n } else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n \n }\n }\n\n if(randomQuestion == 3) {\n if(answers == 3){\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n } else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n \n }\n }\n\n if(randomQuestion == 4) {\n if(answers == 0){\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n } else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n \n }\n }\n\n if(randomQuestion == 5) {\n if(answers == 2){\n document.getElementById('submit').innerHtml = alert('Correct');\n score++;\n } else {\n document.getElementById('submit').innerHtml = alert('Wrong');\n \n }\n }\n \n document.getElementById('results').innerText = `Score: ${score}`;\n\n\n}", "function displayScore() {\n var score = $('<p>',{id: 'question'});\n \n var numCorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i] === questions[i].correctAnswer) {\n numCorrect++;\n }\n }\n\n var numIncorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i] === questions[i].wrongAnswer) {\n numIncorrect++;\n }\n }\n \n score.append('Correct Answers:' + numCorrect);\n score.append('Incorrect Answers:' + numInorrect);\n \n \n }", "function submit() {\n studentAnswer = document.getElementById(\"studentAnswer\").value;\n studentAnswers.push(studentAnswer);\n\n score = 0;\n for (s = 0; s < questionCount; s++){\n if (studentAnswers[s] == questionAnswers[s]){\n score++;\n }\n }\n document.getElementById(\"score\").innerHTML = (\"Total Correct: \" + score);\n}", "function getScore(correct, missed, noAnswer){\n let x = (correct / (correct + missed + noAnswer)) * 100;\n return x;\n }", "function createGradedQuestion(studAnswer, corrAnswer, numAnswerChoices, numAnswerPoints, questions, studName, examCurrentCode, examTotalPoints) {\n var awardedPoints = 0;\n if(corrAnswer == \"true\"){\n corrAnswer = \"0\";\n numAnswerChoices = 2;\n }\n else if(corrAnswer == 'false') {\n corrAnswer = \"1\";\n numAnswerChoices = 2;\n }\n\n var correct = false;\n if(studAnswer == corrAnswer) {\n correct = true;\n }\n\n if(questions.type != \"fr\" && correct) {\n sessionStorage.setItem(\"totalPointsExcludingFr\", parseInt(sessionStorage.getItem(\"totalPointsExcludingFr\")) + parseInt(questions.points))\n }\n\n var exam = document.getElementById('question-data');\n\n var question = document.createElement('div');\n question.className = \"question\";\n question.id = document.getElementsByClassName('question').length + 1;\n\n var num = document.createElement('span');\n num.innerHTML = document.getElementsByClassName('question').length + 1 + \". \";\n num.style.color = \"#97a5aa\";\n\n var hr = document.createElement('hr');\n\n var question_title = document.createElement('input');\n question_title.readOnly = true;\n question_title.value = questions.title;\n question_title.id = \"question-title\";\n\n question.appendChild(num);\n question.appendChild(question_title);\n\n if(correct) {\n awardedPoints = numAnswerPoints;\n }\n\n var points = document.createElement('div');\n points.id = \"points\";\n\n var span = document.createElement('span');\n span.innerHTML = \"( \";\n\n var numPoints = document.createElement('span');\n numPoints.type = \"text\";\n numPoints.id = \"numPoints\";\n numPoints.innerHTML = numAnswerPoints;\n\n var finishingSpan = document.createElement('span');\n finishingSpan.className = \"pa\";\n finishingSpan.innerHTML = \" points) - points awarded: \" + awardedPoints;\n\n points.appendChild(span); points.appendChild(numPoints); points.appendChild(finishingSpan);\n\n question.appendChild(points);\n\n var answer_choices = document.createElement('div');\n answer_choices.className = \"mc\";\n\n for(var i = 0; i < numAnswerChoices; i++) {\n var label = document.createElement('label');\n label.id = \"label\";\n label.style.width = \"95%\"\n if((correct && i == studAnswer) || i == corrAnswer) {\n label.style.background = \"#e4f7e4\";\n label.style.borderTop = \"1px solid #00cc00\"\n label.style.borderBottom = \"1px solid #00cc00\"\n\n var correctAnswer = document.createElement('span');\n correctAnswer.innerHTML = \"Correct Answer\"\n correctAnswer.style.float = \"right\";\n correctAnswer.style.fontWeight = \"normal\";\n correctAnswer.style.marginTop = \"10px\";\n correctAnswer.style.color = \"#00cc00\";\n correctAnswer.style.marginRight = \"15px\";\n\n label.appendChild(correctAnswer);\n }\n else if(!correct && i == studAnswer) {\n label.style.background = \"#f2ebeb\";\n label.style.borderTop = \"1px solid #cc5252\"\n label.style.borderBottom = \"1px solid #cc5252\"\n label.style.color = \"#cc5252\";\n\n var incorrectAnswer = document.createElement('span');\n incorrectAnswer.innerHTML = \"Student Answer\"\n incorrectAnswer.style.float = \"right\";\n incorrectAnswer.style.fontWeight = \"normal\";\n incorrectAnswer.style.marginTop = \"10px\";\n incorrectAnswer.style.color = \"#cc5252\";\n incorrectAnswer.style.marginRight = \"15px\";\n label.appendChild(incorrectAnswer);\n }\n\n var input = document.createElement('input');\n input.disabled = true;\n input.style.outline = \"none\";\n input.type = \"radio\";\n input.className = \"option-input radio\";\n input.name = num.innerHTML;\n\n var span = document.createElement('span');\n if(questions.type != \"tf\" && questions.type != \"fr\") {\n span.innerHTML = questions.choices[i];\n }\n else if(questions.type == \"tf\"){\n if(i == 0) {\n span.innerHTML = \"True\";\n }\n else {\n span.innerHTML = \"False\";\n }\n }\n span.style.fontWeight = \"normal\"\n\n var answer_choice = document.createElement('span');\n answer_choice.className = \"option\";\n answer_choice.id = \"question-choice\";\n\n label.appendChild(input);\n label.appendChild(answer_choice);\n label.appendChild(span);\n answer_choices.appendChild(label);\n }\n\n if(questions.type == \"fr\") {\n var ta = document.createElement('textarea');\n $(ta).attr(\"readonly\", true);\n ta.className = \"fr\";\n ta.value = studAnswer;\n\n var pointsAwardedSpan = document.createElement('span');\n pointsAwardedSpan.innerHTML = \"Points Awarded - \";\n\n var numAcceptedPoints = document.createElement('input');\n numAcceptedPoints.maxLength = questions.points.length;\n\n firebase.database().ref(\"Teachers/\" + userName + \"/Classes/\" + sessionStorage.getItem(\"className\") + \"/Exams/\" + examCurrentCode + \"/responses/\" + studName).once('value', function(snapshot) {\n snapshot.forEach(function(childSnapshot) {\n var questionNum;\n var answers = childSnapshot.val().answers;\n\n if(answers[2].split(\";\")[2] != undefined) {\n setTimeout(function(){ document.getElementsByClassName('pa')[parseInt(num.innerHTML.substring(0, num.innerHTML.indexOf(\".\"))) - 1].innerHTML = \" points) - points awarded: \" + answers[2].split(\";\")[2]; }, 100);\n numAcceptedPoints.value = answers[2].split(\";\")[2];\n }\n });\n });\n\n numAcceptedPoints.onkeyup = function () {\n this.value = this.value.replace(/[^\\d]/,'');\n this.value = this.value.replace('-', '');\n\n if(this.value != \"\") {\n document.getElementsByClassName('pa')[parseInt(num.innerHTML.substring(0, num.innerHTML.indexOf(\".\"))) - 1].innerHTML = \" points) - points awarded: \" + this.value;\n }\n else {\n document.getElementsByClassName('pa')[parseInt(num.innerHTML.substring(0, num.innerHTML.indexOf(\".\"))) - 1].innerHTML = \" points) - points awarded: 0\";\n }\n\n var cleanVersion = this.value;\n\n firebase.database().ref(\"Teachers/\" + userName + \"/Classes/\" + sessionStorage.getItem(\"className\") + \"/Exams/\" + examCurrentCode + \"/responses/\" + studName).once('value', function(snapshot) {\n snapshot.forEach(function(childSnapshot) {\n var questionNum;\n var answers = childSnapshot.val().answers;\n\n for(var k = 0; k < answers.length; k++) {\n if(isNaN(answers[k].split(\";\")[1])) {\n answers[k] = answers[k].split(\";\")[0] + \";\" + answers[k].split(\";\")[1] + \";\" + cleanVersion;\n }\n }\n firebase.database().ref(\"Teachers/\" + userName + \"/Classes/\" + sessionStorage.getItem(\"className\") + \"/Exams/\" + examCurrentCode + \"/responses/\" + studName + \"/\" + childSnapshot.key).update({ 'answers': answers });\n\n var newScore = (((parseInt(sessionStorage.getItem(\"totalPointsExcludingFr\")) + parseInt(cleanVersion)) / examTotalPoints) * 100).toFixed(1);\n firebase.database().ref(\"Teachers/\" + userName + \"/Classes/\" + sessionStorage.getItem(\"className\") + \"/Exams/\" + examCurrentCode + \"/responses/\" + studName + \"/\" + childSnapshot.key).update({ 'totalScore': newScore });\n\n document.getElementById(\"score\").innerHTML = newScore + \"%\";\n document.getElementById(\"score-num\").innerHTML = (parseInt(sessionStorage.getItem(\"totalPointsExcludingFr\")) + parseInt(cleanVersion)) + \" / \" + examTotalPoints;\n });\n });\n }\n\n numAcceptedPoints.placeholder = \"0 - \" + questions.points;\n numAcceptedPoints.style.padding = \"5px\";\n numAcceptedPoints.style.fontSize = \"15px\";\n numAcceptedPoints.style.border = \"1px solid #808080\";\n numAcceptedPoints.style.borderRadius = \"3px\";\n numAcceptedPoints.style.marginTop = \"20px\";\n\n question.appendChild(ta);\n question.appendChild(document.createElement('br'));\n question.appendChild(pointsAwardedSpan);\n question.appendChild(numAcceptedPoints);\n }\n else {\n question.appendChild(answer_choices);\n }\n\n exam.appendChild(question);\n exam.appendChild(document.createElement('br'));\n exam.appendChild(hr);\n\n}", "function calcScore(givenAnswers, correctAnswers) {\r\n givenAnswers.forEach((answer, i) => {\r\n if (answer === correctAnswers[i]) {\r\n score++;\r\n }\r\n });\r\n}", "function displayScore() { \n var numCorrect = 0;\n for (var i = 0, length = selections.length; i < length; i++) {\n if (selections[i] == questions[i].correctAnswer) {\n numCorrect++;\n }\n }\n \n return numCorrect;\n}", "function generateResults(){\n //grabs answer user selected, current question number, and correct answer\n let selected = $('input[type=radio]:checked', '#question-form').val();\n let allQuestions = store.questions;\n let currentQuestionNumber = store.questionNumber;\n let correct = Object.values(allQuestions)[currentQuestionNumber].correctAnswer;\n \n //determines which view to generate based on if users selected the correct answer. if so, increments the score. determines\n if (correct === selected && currentQuestionNumber < store.questions.length) {\n store.score++;\n return generateCorrectPage();\n }\n else if (correct !== selected && currentQuestionNumber < store.questions.length) {\n return generateWrongPage();\n }\n}", "function scoreEvaluate() {\n for ( i = 0; i < userAnswers.length; i++) {\n const element = userAnswers[i];\n if (element == correct[i]) {\n correctUserAnswers.push(element);\n console.log(correctUserAnswers) \n }\n }\n if (correctUserAnswers.length == 5) {\n $(\"#messageArea\").text(\"YOU GOT A PERFECT SCORE! HASTA LA VICTORIA SIEMPRE!\")\n // alert(\"YOU GOT A PERFECT SCORE! HASTA LA VICTORIA SIEMPRE!\")\n stop(); \n }\n else{ \n // amtCorrect();\n // alert(\"ONWARD COMRADE, you got \" + correctUserAnswers.length + \" out of 5 correct!\")\n $(\"#messageArea\").text(\"ONWARD COMRADE, you got \" + correctUserAnswers.length + \" out of 5 correct!\")\n stop();\n } \n }", "function gameCheck(){\r\n\t\tfor(var i=0; i<answerKey.length; i++){\r\n\t\t\tif (userAnswers[i] == answerKey[i]){\r\n\t\t\t\tcorrectGuesses++;\r\n\t\t\t\tconsole.log(\"correct guesses is \" + correctGuesses);\r\n\t\t\t\tconsole.log(correctGuesses/totalQuestions);\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tconsole.log(\"did not match\");\r\n\t\t\t}\r\n\t\t}\r\n\t}", "calculateScore () {\n this.allCorrectAnswers = {};\n this.allSelectedAnswers = readFromCache('selectedAnswers');\n this.quizData.map((qA) => {\n const correctAnswers = [];\n for (const [key, value] of Object.entries(qA.correct_answers)) {\n if (value == 'true') {\n const correctAnswer = helpers.splitter(key, '_', 2);\n correctAnswers.push(correctAnswer);\n }\n }\n this.allCorrectAnswers[qA.id] = correctAnswers;\n });\n for (const [key, value] of Object.entries(this.allSelectedAnswers)) {\n if (value.sort().join(',') === this.allCorrectAnswers[key].sort().join(',')) {\n this.score++;\n }\n }\n this.score = this.score / Object.keys(this.allSelectedAnswers).length * 100;\n this.score = this.score.toFixed(2);\n let allScores = readFromCache('scores');\n allScores = allScores || {};\n allScores[new Date().toLocaleString()] = this.score;\n writeToCache('scores', allScores);\n }", "function checkAnswer() {\n let userAnswer = document.getElementsByName('ans');\n let cAns;\n for (i = 0; i < userAnswer.length; i++) {\n if (userAnswer[i].checked) {\n cAns = userAnswer[i].value;\n }\n }\n if (cAns == correct[qtrack]) {\n score++;\n wright.push(qtrack);\n }\n else wrong.push(qtrack);\n}", "function showResults(questions, quizContainer, resultsContainer){\r\n\t\t// gather answer containers from our quiz\r\n\tvar answerContainers = quizContainer.querySelectorAll('.answers');\r\n\t\r\n\t// keep track of user's answers\r\n\tvar userAnswer = '';\r\n\tvar numCorrect = 0;\r\n\t\r\n\t// for each question...\r\n\tfor(var i=0; i<questions.length; i++){\r\n\r\n\t\t// find selected answer\r\n\t\tuserAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;\r\n\t\t\r\n\t\t// if answer is correct\r\n\t\tif(userAnswer===questions[i].correctAnswer){\r\n\t\t\t// add to the number of correct answers\r\n\t\t\tnumCorrect=numCorrect+2;\r\n\t\t\t\r\n\t\t\t// color the answers green\r\n\t\t\tanswerContainers[i].style.color = 'lightgreen';\r\n\t\t}\r\n\t// if answer is wrong or blank\r\n\t\telse{\r\n\t\t\t// color the answers red\r\n\t\t\tanswerContainers[i].style.color = 'red';\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\r\n\t// show number of correct answers out of total\r\n\tresultsContainer.innerHTML ='Your scores is ' + numCorrect +'%' + ' out of ' + (questions.length*2) + '%';\r\n\t// alert('Your scores is ' + numCorrect +'%' + ' out of ' + (questions.length*2) + '%');\r\n\t\r\n}", "function evaluate() {\n $('#quizBoard').hide();\n $('#results').show();\n if ($('#q1f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q2t').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q3f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q4f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q5t').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q6t').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q7f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q8f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n if ($('#q9f').is(':checked')) {\n correct++\n } else {\n incorrect++\n }\n $('#corr').html(correct)\n $('#incorr').html(incorrect)\n $('#percent').html(correct/9)\n}", "function ScoreCheck() {\n an1 = $('input:radio[name=q1]:checked').val();\n an2 = $('input:radio[name=q2]:checked').val();\n an3 = $('input:radio[name=q3]:checked').val();\n an4 = $('input:radio[name=q4]:checked').val();\n\n console.log(\"an1: \" + an1);\n console.log(\"an2: \" + an2);\n console.log(\"an3: \" + an3);\n console.log(\"an4: \" + an4);\n\n if (an1 == 'answer1') {\n correct++;\n } else if (an1 == undefined) {\n unAnswered++;\n } else {\n incorrect++;\n }\n \n if (an2 == 'answer2') {\n correct++;\n } else if (an2 == undefined) {\n unAnswered++;\n } else {\n incorrect++;\n }\n \n if (an3 == 'answer3') {\n correct++;\n } else if (an3 == undefined) {\n unAnswered++;\n } else {\n incorrect++;\n }\n \n if (an4 == 'answer4') {\n correct++;\n } else if (an4 == undefined) {\n unAnswered++;\n } else {\n incorrect++;\n }\n\n DisplayResults();\n}", "function showResults(){\n\n\t// gather answer containers from our quiz\n\tconst answerContainers = quizContainer.querySelectorAll('.answers');\n \n\t// keep track of user's answers\n\tlet numCorrect = 0;\n \n\t// for each question...\n\tmyQuestions.forEach( (currentQuestion, questionNumber) => {\n \n\t // find selected answer\n\t const answerContainer = answerContainers[questionNumber];\n\t const selector = `input[name=question${questionNumber}]:checked`;\n\t const userAnswer = (answerContainer.querySelector(selector) || {}).value;\n \n\t // if answer is correct\n\t if(userAnswer === currentQuestion.correctAnswer){\n\t\t// add to the number of correct answers\n\t\tnumCorrect++;\n \n\t\t//color the answers green\n\t\tanswerContainers[questionNumber].style.color = 'blue';\n\t }\n\t // if answer is wrong or blank\n\t else{\n\t\t// color the answers red\n\t answerContainers[questionNumber].style.color = 'red';\n\t }\n\t});\n \n\t// show number of correct answers out of total\n\tresultsContainer.innerHTML = `Your score is : ${numCorrect} out of ${myQuestions.length}`;\n }", "function checkAnswers() {\n for (var i = 0; i <= 6; i++) {\n var radios = document.getElementsByName(\"colors\" + i);\n for (var j = 0; j < radios.length; j++) {\n var radio = radios[j];\n if (radio.value == \"correct\" && radio.checked) {\n correctAnswers++;\n }\n else if (radio.value == \"wrong\" && radio.checked) {\n incorrectAnswers++;\n }\n }\n }\n\n //formula to arrive at incomplete answers\n if (correctAnswers + incorrectAnswers < 5) {\n var incompVal = 5 - (correctAnswers + incorrectAnswers);\n incomplete = incompVal;\n }\n\n if (correctAnswers >= 4){\n $(\"#resultMessage\").html(\"<h5>WAY TO GO! YOU ARE A SUPER GENIUS!</h5>\");\n }\n else{\n $(\"#resultMessage\").html(\"<h4>BOOOOO! YOU STINK!!!!</h4>\");\n }\n\n //hides the question divs\n $(\"#question1\").hide();\n $(\"#ans1\").hide();\n $(\"#question2\").hide();\n $(\"#ans2\").hide();\n $(\"#question3\").hide();\n $(\"#ans3\").hide();\n $(\"#question4\").hide();\n $(\"#ans4\").hide();\n $(\"#question5\").hide();\n $(\"#ans5\").hide();\n //hides the timer and submit button\n $(\"#submitButton\").hide();\n\n if (timer === 0) {\n stop();\n $(\"#time\").html(\" TIME'S UP!! \");\n }\n else {\n $(\"#time\").hide();\n }\n\n //displays the results\n $(\"#results\").append(\"Correct Answers: \" + correctAnswers + \"<br>\" + \"Incorrect Answers: \" +\n incorrectAnswers + \"<br>\" + \"Incomplete Answers: \" + incomplete)\n\n //stops the timer\n stop();\n\n}", "function questionSix() {\n \n for (var i = 4; i>0 ; i--) {\n\n var question6 = parseInt(prompt('Hey ' + user +' What is my favorite number?')); //ask question\n\n console.log('what is my favorite number', question6); //log answer\n\n\n if (randomNum < question6){\n guessesLeft1--;\n\n alert('OOPS! ' + user + ', you guessed too high!' + ' number of guesses left: ' + guessesLeft1);\n //if input is higher than randomNum, display this\n }else if (randomNum > question6){\n guessesLeft1--;\n\n alert('OOPS! ' + user + ', you guessed too low!' +' number of guesses left: ' + guessesLeft1); // if input is lower than randomNum, display this\n\n }else if (question6 === randomNum){\n score++;\n alert('WOW! ' + user + ' i cannot believe you guessed my favorite number!'); //if you got the answer right display this\n\n break; //end loop\n }\n }\n }", "function generateQuestionResultsForm(answer) {\n if (answer == store.questions[store.questionNumber].correctAnswer) {\n store.score += 1;\n $('#question-container').append(\n `<p class=\"reply\">Correct!</p>`\n );\n } else {\n $('#question-container').append(\n `<p class=\"reply\">Sorry, the correct answer is: ${store.questions[store.questionNumber].correctAnswer}</p>`\n );\n }\n}", "function checkAnswer() {\r\n STORE.view = 'feedback';\r\n let userSelectedAnswer = STORE.userAnswer;\r\n let correctAnswer = STORE.questions[STORE.questionNumber].correctAnswer;\r\n console.log('Checking answer...');\r\n if (userSelectedAnswer == correctAnswer) {\r\n STORE.score++;\r\n STORE.correctAnswer = true;\r\n }\r\n else {\r\n STORE.correctAnswer = false;\r\n }\r\n}", "function displayScore() {\r\n var score = $('<p>', {\r\n id: 'question'\r\n });\r\n var numCorrect = 0;\r\n for (var i = 0; i < selections.length; i++) {\r\n if (selections[i] === questions[i].correctAnswer) {\r\n numCorrect++;\r\n }\r\n }\r\n score.append('You got ' + numCorrect + ' out of ' +\r\n questions.length + '.');\r\n return score;\r\n }", "function calcWrongAnswers(){\n showVariables();\n $(\"#wrongAns\").html(\"Number of wrong answers : \"+wrongAnswers);\n\n }", "function calculatePercentage() {\n // Constants:\n let MAX_QUESTIONS1 = 5;\n \n // Converting \"score\" to an integer:\n var scoreInteger = parseInt(score1);\n \n // Calculating percentage:\n let finalPerecntage = Math.floor((scoreInteger / MAX_QUESTIONS1) * 100);\n \n // Converting \"finalPerecntage\" to an integer:\n var finalPerecntageInteger = parseInt(finalPerecntage);\n\n // Proceeding depending on the user's percentage score:\n // If user got 60% or higher (Answered 3 questions correctly):\n if (finalPerecntageInteger >= 60) {\n // User passed quiz:\n // Calling function \"quizPassed\" with \"finalPerecntageInteger\" as parameters to proceed:\n quizPassed(finalPerecntageInteger);\n } else {\n // User failed quiz:\n // Calling function \"quizFailed\" with \"finalPerecntageInteger\" as parameters to proceed:\n quizFailed(finalPerecntageInteger);\n }\n}", "function submitAnswer() {\n let radios = document.getElementsByName(\"choice\");\n let userAnswer;\n \n for(i = 0 ; i < radios.length; i++ ) {\n if(radios[i].checked) {\n checked = true;\n userAnswer = radios[i].value;\n }\n } \n\n// if user click submit button without selecting any option\n if(!checked) {\n alert(\"You must select an answer\");\n return;\n }\n \n // Correct answer\n if(userAnswer === \"option4\") {\n alert(\"Answer is correct!\");\n rightAnswer++;\n $(\"#right\").text(\"Correct answers: \" + rightAnswer);\n reset();\n }\n // incorrect answer\n else {\n alert(\"Answer is wrong!\");\n wrongAnswer++;\n $(\"#wrong\").text(\"Inccorect answers: \" + wrongAnswer);\n reset();\n }\n}", "function checkAnswer(ev) {\n let currentAnswer = ev.currentTarget.getAttribute('data-answer');\n // Store what answer the user chose in an array\n userAnswers.push(currentAnswer);\n // If the chosen answer is correct increase the score\n if(questionList[questionIndex].answer === currentAnswer) {\n score++;\n }\n // Raise questionIndex if it's not already the last question, if thats the case show the score\n if(questionIndex < questionList.length - 1) {\n questionIndex++;\n clearInterval(questionTimer);\n displayNewQuestion(questionIndex);\n } else {\n clearInterval(questionTimer);\n showResults();\n }\n}", "function getAnswers(){\n\t\t//go through array, asking the user each question\n\t\tfor(var i = 0; i < questions.length; i++){\n\t\t\t//Get the user's answer\n\t\t\tanswers[i] = prompt(questions[i]);\n\t\t\t//Process the user's answer\n\t\t\tif(i === questions.length - 1){ //the last question is not a yes or no question\n\t\t\t\t//convert the user's last answer to a number type\n\t\t\t\tanswers[i] = parseInt(answers[i]);\n\t\t\t\t//console.log(answers[i]);\n\t\t\t\t//verify the user entered one of the correct numbers\n\t\t\t\tif(answers[i] !== 23 && answers[i] !== 65 && answers[i] !== 93){ \n\t\t\t\t\tresultEl.innerHTML += \"<h3>I'm sorry, you didn't pick one of the given numbers in question 6. Please refresh the page to start over and be sure to answer 23, 65, or 93.</h3>\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}else if(answers[i].toLowerCase() === \"n\" || answers[i].toLowerCase() === \"no\"){\n\t\t\t\tanswers[i] = \"No\";\n\t\t\t}else if(answers[i].toLowerCase() === \"y\" || answers[i].toLowerCase() === \"yes\"){\n\t\t\t\tanswers[i] = \"Yes\";\n\t\t\t}else{ //User did not answer yes or no - exit game\n\t\t\t\tresultEl.innerHTML += \"<h3>I'm sorry, I didn't understand your answer. Please refresh the page to start over and be sure to answer 'Yes' or 'No'</h3>\";\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}", "function showResults(){\n\n // gather answer containers from our quiz\n const answerContainers = quizContainer.querySelectorAll('.answers');\n \n // keep track of user's answers\n let numCorrect = 0;\n \n // for each question...\n myQuestions.forEach( (currentQuestion, questionNumber) => {\n \n // find selected answer\n const answerContainer = answerContainers[questionNumber];\n const selector = `input[name=question${questionNumber}]:checked`;\n const userAnswer = (answerContainer.querySelector(selector) || {}).value;\n \n // if answer is correct\n if(userAnswer === currentQuestion.correctAnswer){\n // add to the number of correct answers\n numCorrect++;\n \n // color the answers green\n answerContainers[questionNumber].style.color = 'lightgreen';\n }\n // if answer is wrong or blank\n else{\n // color the answers red\n answerContainers[questionNumber].style.color = 'red';\n }\n });\n \n // show number of correct answers out of total\n resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;\n}", "function addToScore () {\n score += questionInfo[correspondingQuestion].points\n document.querySelector('#score').innerHTML = `Score: ${score}`\n numberOfCorrectAnswers++\n}", "function checkAnswer(e) {\n // targets user selection\n var answer = e.target.innerText;\n console.log(answer);\n\n //cannot set answer = to question correct answer\n // !!!!! NEED HELP WITH THIS !!!!\n if (answer === questions[qIndex].correct) {\n userScore++;\n scoreBox.innerHTML = `<h2>Score: ${userScore}</h2>`;\n console.log(userScore);\n // if answer correct, add one to question index\n qIndex++;\n // run questionCycle again prompting new question\n questionCycle();\n // box for user score have it update everytime this happens\n } else {\n // decreases timer by one second if user selects wrong answer\n timerCount = timerCount - 5;\n qIndex++;\n scoreBox.innerHTML = `<h2>Score: ${userScore}</h2>`;\n // prompts new question if answered incorrectly\n questionCycle();\n }\n}", "function timeUp(){\n\n\n\t\t// Which radio buttons are checked \n\t\tvar Q1 = $('#questionForm input:radio[name=\"q1\"]:checked').val();\n\t\tvar Q2 = $('#questionForm input:radio[name=\"q2\"]:checked').val();\n\t\tvar Q3 = $('#questionForm input:radio[name=\"q3\"]:checked').val();\n\t\tvar Q4 = $('#questionForm input:radio[name=\"q4\"]:checked').val();\n\t\tvar Q5 = $('#questionForm input:radio[name=\"q5\"]:checked').val();\n\t\tvar Q6 = $('#questionForm input:radio[name=\"q6\"]:checked').val();\n\n console.log(\n 'Q1', Q1,\n '\\nQ2', Q2,\n '\\nQ3', Q3,\n '\\nQ4', Q4,\n '\\nQ5', Q5,\n '\\nQ6', Q6\n );\n\t\t// right/wrong answers determined here\n\t\tif(Q1 == undefined){\n console.log(\"Q1 == undefined\")\n unansweredCount++;\n\t\t}\n\t\telse if(Q1 == \"Greenland\"){\n console.log('Q1 == \"Greenland\"')\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n console.log(\"else\")\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\tif(Q2 == undefined){\n\t\t\tunansweredCount++;\n\t\t}\n\t\telse if(Q2 == \"8,000\"){\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\tif(Q3 == undefined){\n\t\t\tunansweredCount++;\n\t\t}\n\t\telse if(Q3 == \"Casablanca\"){\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\tif(Q4 == undefined){\n\t\t\tunansweredCount++;\n\t\t}\n\t\telse if(Q4 == \"Mona Lisa\"){\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\tif(Q5 == undefined){\n\t\t\tunansweredCount++;\n\t\t}\n\t\telse if(Q5 == \"1989\"){\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\tif(Q6 == undefined){\n\t\t\tunansweredCount++;\n\t\t}\n\t\telse if(Q6 == \"50 inches\"){\n\t\t\tcorrectCount++;\n\t\t}\n\t\telse{\n\t\t\twrongCount++;\n\t\t}\n\n\n\t\t// show score results\n\t\t$('#correct_answers').html(correctCount);\n\t\t$('#wrong_answers').html(wrongCount);\n\t\t$('#unanswered').html(unansweredCount);\n\n\n\t\t// Show the end game scores\n\t\t$(\"#end-container\").show();\n\n\n\t}", "function count(){\n game.correct = 0;\n game.wrong = 0;\n game.unanswered = 0;\n // question 1\n if ($('input:radio[name=\"o1\"]:checked').val() === game.answers.a1) {\n game.correct++;\n console.log(\"this is correct! number:\")\n }\n else if($('input:radio[name=\"o1\"]:checked').val() === undefined){\n game.unanswered++;\n console.log(\"You put nothing...\");\n }\n else{\n game.wrong++;\n console.log(\"this is wrong! number:\");\n };\n\n // question 2\n if ($('input:radio[name=\"o2\"]:checked').val() === game.answers.a2 ) {\n game.correct++;\n console.log(\"this is correct! number:\")\n } \n else if($('input:radio[name=\"o2\"]:checked').val() === undefined){\n game.unanswered++;\n console.log(\"You put nothing...\");\n }\n else{\n game.wrong++;\n console.log(\"this is wrong! number:\");\n };\n\n // question 3\n if ($('input:radio[name=\"o3\"]:checked').val() === game.answers.a3 ) {\n game.correct++;\n console.log(\"this is correct! number:\")\n } \n else if($('input:radio[name=\"o3\"]:checked').val() === undefined){\n game.unanswered++;\n console.log(\"You put nothing...\");\n }\n else{\n game.wrong++;\n console.log(\"this is wrong! number:\");\n };\n \n // question 4\n if ($('input:radio[name=\"o4\"]:checked').val() === game.answers.a4 ) {\n game.correct++;\n console.log(\"this is correct! number:\")\n } \n else if($('input:radio[name=\"o4\"]:checked').val() === undefined){\n game.unanswered++;\n console.log(\"You put nothing...\");\n }\n else{\n game.wrong++;\n console.log(\"this is wrong! number:\");\n };\n }", "function quizTime() {\n for(i=0;i<quesBank[sport_name].length;i++){\n console.log(chalk.bgYellow(`Question ${i + 1}: `));\n console.log(quesBank[sport_name][i].question);\n var ans = readLineSync.question(\"Your answer: \");\n if (ans === quesBank[sport_name][i].answer) {\n console.log(chalk.green(\"\\n Wohoo Correct Answer! You scored 1 points.\"))\n score += 1;\n console.log(chalk.bgBlue(`Current score: ${score}`));\n console.log(\"––––––––––\\n\\n\");\n }\n else {\n console.log(chalk.red(\"\\nWrong Answer! You scored 0 points.\"));\n console.log(chalk.bgBlue(`Current score: ${score}`));\n console.log(\"––––––––––\\n\\n\");\n }\n };\n}", "function checkAnswer() {\n possible_answers = document.getElementsByName(\"possible_answers\");\n for(var i = 0; i < possible_answers.length; i++) {\n if(possible_answers[i].checked) {\n chosen_answer = possible_answers[i].value;\n }\n }\n//if answer is correct, increase points\n if (chosen_answer == questions[pos].answer) {\n correct++;\n }\n pos++;\n displayQuestion();\n}", "function checkAnswer(event) {\n\tevent.preventDefault();\n\tvar button = document.getElementById(event.target.id);\n\tvar userInitials;\n\n\tif (button.id === \"initials\") {\n\t\treturn;\n\t}\n\n\t//saves initials\n\tif (button.id === \"submitScore\") {\n\t\tuserInitials = document.getElementById(\"initials\");\n\t\tsaveScore(userInitials);\n\t\treturn;\n\t}\n\n\t//We are checking here the user answer and the correct answer and acting accordingly\n\tif (answer1.includes(questionsArray[currentQuestion].answer) && button.id === \"choice1\") {\n\t\tuserResult.textContent = \"CORRECT!\";\n\t\tcurrentQuestion++;\n\t\tpoints += 10;\n\t\tdisplayQuestion();\n\t} else if (answer2.includes(questionsArray[currentQuestion].answer) && button.id === \"choice2\") {\n\t\tuserResult.textContent = \"CORRECT!\";\n\t\tcurrentQuestion++;\n\t\tpoints += 10;\n\t\tdisplayQuestion();\n\t} else if (answer3.includes(questionsArray[currentQuestion].answer) && button.id === \"choice3\") {\n\t\tuserResult.textContent = \"CORRECT!\";\n\t\tcurrentQuestion++;\n\t\tpoints += 10;\n\t\tdisplayQuestion();\n\t} else if (answer4.includes(questionsArray[currentQuestion].answer) && button.id === \"choice4\") {\n\t\tuserResult.textContent = \"CORRECT!\";\n\t\tcurrentQuestion++;\n\t\tpoints += 10;\n\t\tdisplayQuestion();\n\t} else {\n\t\tuserResult.textContent = \"WRONG!\";\n\t\tcurrentQuestion++;\n\t\ttimeLeft -= 10;\n\t\tdisplayQuestion();\n\t}\n}", "function displayScore() {\n var score = $('<p>',{id: 'question'});\n \n var numCorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i] === questions[i].correctAnswer) {\n numCorrect++;\n }\n }\n \n score.append('You got ' + numCorrect + ' of ' +\n questions.length + ' correct');\n return score;\n }", "function athena() {\n athenaScore = athenaScore + 1;\n questionCount = questionCount + 1;\n\n if (questionCount >= 5) {\n updateResult();\n }\n}", "function checkAnswer(question, answer) {\n console.log(\"question: \", question);\n console.log(\"asnwer: \", answer);\n let correctAnswer = questions.answer;\n let userAnswer = questions[question].options[answer];\n if (userAnswer == correctAnswer) {\n index = index + 1;\n console.log(score);\n console.log(\"Correct!!\");\n }\n else {\n index = index + 1;\n countDown = countDown - 15;\n score = score - 15;\n console.log(score);\n console.log(\"Next question: \", index);\n console.log(\"Incorrect!\");\n }\n clearQuestion();\n renderAllQuestions();\n // quizOver();\n }", "function question1() {\n let total = 0;\n // console.log('TOTAL', total);\n // Answer:\n for (let i = 0; i < data.length; i++) {\n // console.log('allthethings', data[i].price);\n total += data[i].price;\n // console.log('TOTAL', total);\n }\n // console.log('datalength', data.length);\n let avg = total / data.length;\n console.log('The average price is ', avg);\n}", "function results() {\n // Answer variables.\n correct = 0;\n incorrect = 0;\n unanswered = 0;\n\n for (var i = 1; i < 11; i++) {\n\n if ($(\"input[name='q\" + i + \"']:checked\").val() == \"x\") {\n\n correct++;\n } else if ($(\"input[name='q\" + i + \"']:checked\").val() === undefined) {\n\n unanswered++;\n } else {\n\n incorrect++;\n }\n\n // Display results and hide unwanted elements.\n \n $(\"#quiz\").hide();\n $(\"#whichState\").hide();\n $(\"#validate\").hide();\n $(\"#score\").html(\"Correct: \" + correct + \"<br/>Incorrect: \" + incorrect + \"<br/>Unanswered: \" + unanswered);\n $(\"#timer\").hide();\n $(\"#tally\").show();\n $(\"#clear\").show();\n $(\"#jack\").show();\n }\n\n }", "function displayScore() {\n var score = $('<p>',{id: 'question'});\n \n var numCorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i] == questions[i].correctAnswer) {\n numCorrect++;\n }\n }\n \n score.append('You got ' + numCorrect + ' questions out of ' +\n questions.length + ' right.');\n return score;\n }", "function displayScore() {\n var score = $('<p>',{id: 'question'});\n \n var numCorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (selections[i] === questions[i].awsA) {\n numCorrect += 0;\n }\n else if (selections[i] === questions[i].awsB) {\n numCorrect++;\n }\n else if (selections[i] === questions[i].awsC) {\n numCorrect += 2;\n }\n else {\n numCorrect += 3;\n }\n }\n \n if (numCorrect >5) {\n score.append('You scored ' + numCorrect + ' out of ' +\n questions.length * 3 + '. Exercising several hours before bed is the best time to exercise because it allows our brains to return to baseline activity and eventually allow us to feel sleepy. Because brains are increasingly active during exercise, you should not exercise right before bed or you might risk feeling restless. You’re doing great by giving your brain enough time before bed to calm down! If you don’t exercise, it is still recommended that you start exercising consistently because it correlates with benefits on your sleep quality and memory consolidation - just keep in mind not to exercise too close to bedtime! ');\n return score;\n } else {\n score.append('You scored ' + numCorrect + ' out of ' +\n questions.length * 3 + '. Exercising too close to your bedtime can affect your sleepiness levels and impede on your ability to fall asleep quickly. Because our brains are increasingly active during exercise, they will need an adequate amount of time to return to base level and eventually allow us to feel sleepy. Exercising is good, but do not do it too close to bedtime or else you will not be able to sleep!');\n return score;\n }\n }", "function displayScore() {\r\n var score = $('<p>',{id: 'question'}); \r\n var numCorrect = 0;\r\n for (var i = 0; i < selections.length; i++) {\r\n if (selections[i] === questions[i].correctAnswer) {\r\n numCorrect++;\r\n }\r\n }\r\n \r\n score.append('You got ' + numCorrect + ' questions out of ' +\r\n questions.length + ' right!!!');\r\n return score;\r\n }", "function answerIsCorrect () {\r\n feedbackForCorrect();\r\n updateScore();\r\n}", "function sumScore(questions) {\n return score.reduce(function (previousValue, currentValue, index, array) {\n return previousValue + currentValue;\n });\n }", "function genarateQuestion() {\r\n if(quiz.isEnded()){\r\n //showScore\r\n showScore();\r\n } else {\r\n //show question\r\n let element = document.getElementById(\"question\");\r\n element.innerHTML = quiz.getQuestion().question;\r\n\r\n //show choices\r\n let choices = quiz.getQuestion().choices;\r\n\r\n for(let i = 0; i < choices.length; i++) {\r\n let element = document.getElementById(\"choice\" + i);\r\n\r\n element.innerHTML = choices[i];\r\n guessCorrectAnswer(\"choice\" + i, choices[i]);\r\n \r\n }\r\n\r\n showProgress();\r\n \r\n }\r\n}", "total_incorrect_questions() {\n var total_incorrect_questions = 0;\n for (var i = 0; i < this.state.quiz_log.length; i++) {\n total_incorrect_questions = total_incorrect_questions + this.state.quiz_log[i][2];\n }\n return (total_incorrect_questions)\n }", "function gryffindor() {\n gryffindorScore += 1;\n questionCount += 1;\n if (questionCount >= 3) {\n updateResult();\n }\n}", "function scoreKeeper() {\n for (i = 0; i < storeAnswers.length; i++) {\n if (storeAnswers[i] === questionsArray[i].answer) {\n correct++;\n console.log(correct);\n } else {\n incorrect++;\n }\n }\n }", "function answerCheck() {\n\n var question1 = $(\"input[type='radio'][name='question1']:checked\").val();\n var question2 = $(\"input[type='radio'][name='question2']:checked\").val();\n var question3 = $(\"input[type='radio'][name='question3']:checked\").val();\n var question4 = $(\"input[type='radio'][name='question4']:checked\").val();\n var question5 = $(\"input[type='radio'][name='question5']:checked\").val();\n\n // if statements compare checked value vs pre determined html values\n if (question1 == timechecks()) {\n score += 1;\n }\n if (question2 == \"B\") {\n score += 1;\n }\n if (question3 == \"C\") {\n score += 1;\n }\n if (question4 == \"D\") {\n score += 1;\n }\n if (question5 == \"A\") {\n score += 1;\n }\n return score;\n}", "function checkAnswer(answer){\n\n if( answer == questions[runningQuestion].correct){\n score ++;\n // for correct\n answerIsCorrect();\n }else{\n // if the answer is wrong,it's need to change the color in red\n answerIsWrong();\n }\n count = 0;\n if(runningQuestion < lastQuestion){\n runningQuestion++;\n renderQuestion();\n \n }else{\n // end the quiz and show the score\n clearInterval(TIMER);\n scoreRender();\n \n }\n}", "function results(){\n gameStart=false;\n correct=0;\n //checking if selected answer is correct\n var yes1=$(\"input#qb\").prop(\"checked\");\n var yes2=$(\"input#qf\").prop(\"checked\");\n var yes3=$(\"input#qg\").prop(\"checked\");\n //increase correct total with correct answer\n if(yes1===true){\n correct++;\n }\n if(yes2===true){\n correct++;\n }\n if(yes3===true){\n correct++;\n }\n if (correct===3){\n $(\"#timeRemain\").html(\"<h1>Right. Off you go.</h1>\");\n }\n else{\n $(\"#timeRemain\").html(\"<h1>Auuuuuuuugh!</h1>\"+\"YOU ONlY GOT \"+correct+\" CORRECT!\");\n }\n correct=0;\n clearTimeout(timerEnd);\n clearInterval(timerCount);\n $(\"#start\").prop(\"disabled\",false);\n }", "function askNumericQuestion() {\n var actualAnswer = 5;\n var userAnswer1;\n for (var attempts = 0; attempts < 4; attempts++) {\n userAnswer1 = Number(prompt('How many years did I serve in the army?'));\n if (userAnswer1 > actualAnswer) {\n alert('That\\'s too high');\n } else if (userAnswer1 < actualAnswer) {\n alert('That\\'s too low');\n } else if (userAnswer1 === actualAnswer) {\n alert('That\\'s correct!');\n scoreCounter++;\n break;\n }\n }\n if (attempts === 4) {\n alert(userName + ', the correct answer is 5!');\n }\n}", "function checkAnswers (){\n \n // variables needed to hold results\n var correct = 0;\n var incorrect = 0;\n var unAnswered =0\n \n // for loop iterates through each question and passes the questions at each index first into\n // the isCorrect function to see if they match the indices of correct answers, and if they do,\n // increments up the correct score\n for (var i = 0; i<questions.length; i++) {\n if (isCorrect(questions[i])) {\n correct++;\n } else {\n // then this statement runs the questions at each index through the checkAnswered function\n // to determine whether the user clicked an answer, or did not click an answer, so that\n // incorrect and unAnswered scores can be delineated from each other\n if (checkAnswered(questions[i])) {\n incorrect++;\n } else {\n unAnswered++;\n }\n }\n \n }\n // display the results of the function in the results div and use strings of text to relate the\n // results of the for loop with their corresponding values\n $('#results').html('correct: '+correct+ \"<br>\" +'incorrect: '+incorrect+ \"<br>\" +'unanswered: '+unAnswered);\n }", "function submitAnswers() {\n var correctAnswer1 = document.getElementById(\"1a\");\n if (correctAnswer1.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer2 = document.getElementById(\"2c\");\n if (correctAnswer2.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer3 = document.getElementById(\"3d\");\n if (correctAnswer3.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer4 = document.getElementById(\"4c\");\n if (correctAnswer4.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer5 = document.getElementById(\"5b\");\n if (correctAnswer5.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer6 = document.getElementById(\"6d\");\n if (correctAnswer6.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n\n var correctAnswer7 = document.getElementById(\"7b\");\n if (correctAnswer7.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n var correctAnswer8 = document.getElementById(\"8c\");\n if (correctAnswer8.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n var correctAnswer9 = document.getElementById(\"9d\");\n if (correctAnswer9.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n var correctAnswer10 = document.getElementById(\"10d\");\n if (correctAnswer10.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n var correctAnswer11 = document.getElementById(\"11c\");\n if (correctAnswer11.checked === true) {\n correct++;\n console.log(\"Correct: \" + correct);\n } else {\n incorrect++;\n console.log(\"Incorrect: \" + incorrect);\n }\n\n //alert(\"Correct: \" + correct);\n //alert(\"Incorrect: \" + incorrect);\n //window.location.href = 'results.html';\n\n //Displays results\n $(\"#main-body\").html(\"<h3>\" + \"Correct: \" + correct + \"</h3>\" +\n \"<h3>\" + \"Incorrect: \" + incorrect + \"</h3>\" +\n \"<h3>\" + \"Percentage Correct: \" + Math.floor(correct / (correct + incorrect) * 100) + \"%\" + \"</h3>\");\n $(\"#main-body\").append(\"<br>\" + '<a id=\"start-over\" href=\"index.html\">Start Over</a>')\n\n }", "function results() {\n selectedAnswers = $(displayTest.find(\"input:checked\"));\n //if user is correct\n if (\n selectedAnswers[0].value === testSetup[currentQuestion - 1].questionAnswer\n ) {\n //add to correct score and display on element\n correct++;\n $(\"#correct\").text(\"Answers right: \" + correct);\n } else {\n //if user is wrong then add to wrong score and display on element\n wrong++;\n $(\"#incorrect\").text(\"Wrong answers: \" + wrong);\n }\n //check to see if the user has reached the end of the test\n if (currentQuestion === 10) {\n //toggle finalize modal at end of test to display score\n $(\"#modalMatch\").modal(\"toggle\");\n $(\"#testScore\").text(\n \"End of test! You scored a \" + (parseFloat(correct) / 10) * 100 + \"%\"\n );\n //show postTest element\n $(\"#postTest\").show();\n $(\"#submitTest\").hide();\n }\n }", "function assessAnswer(userLevel, userScore) {\n let a = correctAnswer[userLevel];\n // targets input answer based on userLevel\n let aGiven = document.querySelector('input[name=\"' + answerSelector[userLevel] + '\"]:checked').value\n //let aGiven = document.querySelector('input[name=\"q1\"]:checked').value\n if (aGiven == a){\n userLevel ++;\n // userScore += seconds;\n\n // load next question\n // displayQuestion(userLevel, userScore)\n\n runQuiz(userLevel, userScore)\n }\n else {\n failModal()\n }\n }", "function displayScore() {\r\n var score = $('<p>',{id: 'question'});\r\n \r\n var numCorrect = 0;\r\n for (var i = 0; i < selections.length; i++) {\r\n if (selections[i] === questions[i].correctAnswer) {\r\n numCorrect++;\r\n }\r\n }\r\n \r\n score.append('You got ' + numCorrect + ' questions out of ' +\r\n questions.length + ' right!!!');\r\n return score;\r\n }", "function checkAnswer(selectedAnswer) {\n const correctAnswer = quiz[currentQuestion].answer;\n \n if (selectedAnswer === correctAnswer) {\n score++;\n }\n \n currentQuestion++;\n \n if (currentQuestion < quiz.length) {\n displayQuestion();\n } else {\n showResult();\n }\n }", "function result() {\n $('input:checked').each(function () {\n var r = $(this).data('question-index');\n console.log('question index: ' + game.questions[r].a);\n console.log('question answer: ' + $(this).val());\n if ($(this).val() === game.questions[r].a) {\n wins++;\n } else if ($(this).val() !== undefined) {\n loses++;\n }\n });\n notAnswered = (game.questions.length - wins) - loses;\n console.log('these are my wins:' + ' ' + wins);\n console.log('these are my loses:' + ' ' + loses);\n $('.end').append(\"<p class='results'>RESULTS</p>\"); // Title of results \n $('.end').append(\"<p>Questions you got right: \" + wins + '</p>'); // wins\n $('.end').append(\"<p>Questions you got wrong: \" + loses + '</p>'); // loses\n $('.end').append(\"<p>Questions you did not answer: \" + notAnswered + '</p>');\n $(\".end\").show(); // the print the results in HTML \n}", "function displayScore() {\n var score = $('<p>', {id: 'question'}),\n numCorrect = 0;\n for (var i = 0; i < selections.length; i++) {\n if (JSON.stringify(selections[i]) === JSON.stringify(questions[i].correctAnswer)) {\n numCorrect++;\n }\n }\n\n score.append('You have correctly answered ' + numCorrect + ' out of ' +\n questions.length + ' questions!!!');\n return score;\n }", "function calcScore() {\n console.log(\"incorrect answers: \" + wrongCount);\n console.log(\"correct answers: \" + correctCount);\n let totalAttempts = wrongCount + correctCount;\n let score = (correctCount / totalAttempts) * 100;\n console.log(\"total score: \" + score);\n // textScore = toString(score);\n let printScore = $(\"<h2>\").text(score);\n $('.displayScore').append(printScore);\n\n }", "function submitAnswers() {\n \n q1 = document.forms [\"quizForm\"][\"question-1\"].value;\n q2 = document.forms [\"quizForm\"][\"question-2\"].value;\n q3 = document.forms [\"quizForm\"][\"question-3\"].value;\n q4 = document.forms [\"quizForm\"][\"question-4\"].value;\n q5 = document.forms [\"quizForm\"][\"question-5\"].value;\n q6 = document.forms [\"quizForm\"][\"question-6\"].value;\n q7 = document.forms [\"quizForm\"][\"question-7\"].value;\n q8 = document.forms [\"quizForm\"][\"question-8\"].value;\n q9 = document.forms [\"quizForm\"][\"question-9\"].value;\n q10 = document.forms [\"quizForm\"][\"question-10\"].value;\n q11 = document.forms [\"quizForm\"][\"question-11\"].value;\n q12 = document.forms [\"quizForm\"][\"question-12\"].value;\n\n\n // Remind user if a question is missed\n // If the user misses more than 1 question, it will remind you the first question out of all the questions you missed.\n for (var i = 1; i <= total; i++) {\n if (eval('q'+i) == null || eval('q'+i) == '') {\n alert ('You missed question ' + [i]);\n // When the submit button is clicked, it will not proceed to clear the screen \n // Exit out of the submit button event listener after reminding the user about the missed questions\n return false;\n }\n }\n\n // Total up the number of correct and incorrect answers\n for (var i = 1; i <= total; i++) {\n if (eval('q'+i) == answers[i-1]) {\n correctAnswers++; \n console.log(correctAnswers); \n }\n\n else {\n wrongAnswers++;\n }\n }\n\n // When the submit button is clicked, proceed to clear the screen to show the correct and incorrect answers\n return true;\n\n}", "function submitAnswer(){\r\n\ty = document.getElementById(\"qans\").value\r\n\tvar yy=y.toUpperCase();\r\n\tx = document.getElementById(\"question\").value\r\n \r\n\tif (ans===1){\r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"B\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===2){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"A\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===3){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"C\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===4){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"D\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===5){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"D\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===6){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"B\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===7){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"B\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===8){ \r\n\t\ty = document.getElementById(\"qans\").value;\r\n\t\tif(yy===\"D\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===9){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"C\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===10){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"B\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===11){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"A\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===12){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"A\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===13){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"C\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===14){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"D\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===15){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"B\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\t}\r\n\telse if (ans===16){ \r\n\t\ty = document.getElementById(\"qans\").value\r\n\t\tif(yy===\"D\"){\r\n\t\t\tcorrectAnswer();\r\n\t\t}\r\n\t\telse {\r\n\t\t\twrongAnswer();\r\n\t\t}\r\n\t\tdocument.view.qscore.value=score\r\n\t\tdocument.view.streakscore.value=current_streak\r\n\r\n\t\t// as this is the last question in the quiz, update the text of \"Next Question\" to make it more appropriate\r\n\t\tdocument.view.go.value=\"End Quiz...\"\r\n\t}\r\n\r\n\t// enable selection of \"Next Question\"\r\n\tdocument.getElementById(\"go_id\").disabled = false\r\n\tdocument.getElementById(\"go_id\").style.opacity = \"1\"\r\n\r\n\t// disable selection of \"Submit Answer\" to avoid logic issues\r\n\tdocument.getElementById(\"user_submit\").disabled = true\r\n\tdocument.getElementById(\"user_submit\").style.opacity = \"0.5\"\r\n\r\n\t// update var ans\r\n\tans++; \r\n}", "function calcDistictAnswers(answers, question) {\n\n //Check if answers contains more than one submission and question is defined\n if (answers.length < 1 || question == undefined) {\n console.log(\"Error in calculating disctinct answers: No answers provided or question missing\")\n return;\n }\n\n //Prepare return object\n var result = new Array();\n\n if (question.questionType == \"multi-choice\") {\n //All submissions must have same amount of options\n var optionsLength = question.questionOptions.length;\n\n //Get correct answer\n var solution = new Array();\n for (var i = 0; i < optionsLength; i++) {\n if (question.questionType == \"multi-choice\") {\n solution.push(question.questionOptions[i].correct);\n } else {\n solution.push(question.questionOptions[i].text);\n }\n };\n console.log(solution);\n\n //Iterate over answers\n for (var i = 0; i < answers.length; i++) {\n //Check if answer has the correct amount of options\n if (answers[i].submission.length != optionsLength) {\n console.log(\"Error in calculating disctinct options: Multiple choice options differ in length. This can't be as every answer has to have the same length.\")\n }\n\n //Remember id answer is not part of results yet\n var newAnswer = true\n\n //Check if answer was seen before. If yes increase quantity, if no add to results.\n\n for (var j = 0; j < result.length; j++) {\n //Check if answer alreday exists in results and if yes increase quantity\n if (arrayEqual(result[j].submission, answers[i].submission)) {\n result[j].quantity++;\n newAnswer = false;\n break;\n }\n };\n //If still new anser add to reluts\n if (newAnswer) {\n\n //Check if new answer is correct\n var correct = arrayEqual(answers[i].submission, solution);\n\n //text for each dataset\n var optionText = \"\";\n //text that contains all selected answer option texts\n\n var selected = new Array();\n for (var k = 0; k < answers[i].submission.length; k++) {\n if (answers[i].submission[k] == true) {\n selected.push(question.questionOptions[k].text.trim());\n optionText = optionText + String.fromCharCode(65 + k) + \" \";\n }\n };\n\n if (question.questionType == \"multi-choice\") {\n optionText = optionText + \"- \" + selected.join(\", \");\n\n } else {\n console.log(\"Qswefrgth\");\n optionText = selected.join(\", \");\n }\n\n //push new answer to results\n result.push({\n submission : answers[i].submission,\n text : optionText,\n correct : correct,\n quantity : 1 //How often option was selected\n });\n }\n\n };\n }\n //Text questions\n else if (question.questionType = \"text-input\") {\n for (var i = 0; i < answers.length; i++) {\n //Test if answer is new, if no increase quantity in results\n var isNewAnswer = true;\n for (var j = 0; j < result.length; j++) {\n if (arrayEqual(result[j].submission, answers[i].submission)) {\n isNewAnswer = false;\n result[j].quantity++;\n }\n };\n\n //If new answer push to results\n if (isNewAnswer) {\n var newAnswer = {\n submission : answers[i].submission,\n text : answers[i].submission.join(),\n correct : false,\n quantity : 1 //How often option was selected\n }\n if (answers[i].correctness == 100) {\n newAnswer.correct = true;\n }\n result.push(newAnswer)\n }\n };\n }\n //Else (missing or unknown question type) log error\n //else{\n // console.log(\"Error in calculating disctinct options: question type is unknown or mission: \");\n // console.log(question.questionType)\n //}\n\n return result;\n}", "function testResults() {\n\t//store variables to update correct and incorrct totals\n\tvar correct = 0;\n\tvar incorrect = 0;\n\n//loop through questions array\nfor (var i = 0; i < questions.length; i++) {\n\n var answer = questions[i].answer;\n var guess = document.getElementById('answer' + [i].value);\n //store element to add a class if correct or incorrect\n var questionSpot = document.getElementById('question' + [i]);\n\n //check if the user answer matches the correct answer\n if(answer == guess) {\n \t//update class on questionsSpot\n \tquestionSpot.className = questionSpot.className + ' correct';\n \t//add one to correct\n \tcorrect++;\n } else {\n \t//update class on questionsSpot\n \tquestionSpot.className = questionSpot.className + ' incorrect';\n \t//add one to incorrect\n \tincorrect++;\n };\n };\n\n //update correct and incorrect values\n document.getElementById('correct').textContent = correct;\n document.getElementById('incorrect').textContent = incorrect;\n}", "function getAnswer(question_no){\n let user_ans;\n \n // user_ans = prompt(\"Enter number of correct answer\");\n user_ans = document.getElementById(\"user_ans\").value;\n \n if(user_ans===null){\n throw new Error('Prompt canceled, terminating Quiz');\n }\n if(user_ans!==\"exit\"){\n user_ans=parseInt(user_ans);\n }\n console.log(\"User Answer: \"+user_ans);\n // console.log(\"user_ans type: \"+typeof(user_ans));\n // console.log(\"q_no: \"+question_no);\n // console.log(\"q_no correct ans: \"+Quiz[question_no].correct);\n if(user_ans===Quiz[question_no].correct){\n return \"correct\";\n }else if(user_ans===\"exit\"){\n return \"exit\";\n }else{\n return \"incorrect\"\n }\n \n}", "applyQuestionGrades() {\n let grades = this.question.gradePlayers();\n for (let uid in grades) {\n this.players[uid].updateScore(grades[uid]);\n }\n }", "function userSelection() {\n stopCountdown();\n if ($(this).attr(\"data-name\") == correctAnswers[questionSelector]) {\n rightWrong = true;\n correct++;\n var newScore = score += points;\n $(\"#score\").text(newScore);\n } else {\n incorrect++ \n }\n showResult();\n nextQuestion();\n }", "function firstAnswer()\n\n {\n\n\t\n for (i=0 ; i<document.Q1.quiz.length ; i++) //this is the method of checking which radio button is checked by the user\n {\n if (document.Q1.quiz[i].checked==true) \n {\n var Answer = document.Q1.quiz[i].value\n }\n }\n\n \n//validation -- whether a radio button is checked \nvar Quiz = document.Q1.quiz; \n for(j=0; j<Quiz.length; j++){\n if(Quiz[j].checked)\n break;\n}\nif (j==Quiz.length) //if the user don't pick a radio button this loop will execute again and ask a answer from user untill he checked a one.\nreturn alert(\"Please select an answer \");\n\n \n \n // this is the nested if else statements to do some activities with the radio button which clicked by user \nif (Answer == \"1\" )\n { \n \n \tScore1 = 2; //this is the correct answer which placed in radio button 1.if he check this this will add 2 marks to the total\n\t\n\tvar item = document.getElementById(\"ImageIDCorrect1\"); //in this statement the image for the correct one(between 2 images) at the marks table \n if (item) { //will appear which was hidden already.\n\t\t\titem.className=(item.className=='hidden')?'unhidden':'hidden';\n }\n\t}\n\nelse if (Answer == \"2\"){ //if the user don't check the first answer then this will check this one and so on untill answer 4.\n \n Score1 = -1; //if he check this one it will deduct 1 mark from total.\n \n document.getElementById(\"A12\").style.color=\"#ff0000\"; //this wrong answer's font color which selected by user will be turned into red and display in marks table.\n \t\n\t\tvar item = document.getElementById(\"ImageIDWrong1\"); //And the image for a wrong answer will also display in the marks table\n\t\tif (item) {\n\t\t\titem.className=(item.className=='hidden')?'unhidden':'hidden';\n }\n\t}\n \nelse if (Answer ==\"3\"){ //same comment as in the Answer 2\n\n\tScore1 = -1;\n\tdocument.getElementById(\"A13\").style.color=\"#ff0000\"; \n\t\n\tvar item = document.getElementById(\"ImageIDWrong1\");\n\t\tif (item) {\n\t\t\titem.className=(item.className=='hidden')?'unhidden':'hidden';\n }\n}\n else if (Answer == \"4\"){ //same comment as in the Answer 2\n \n Score1 = -1;\n document.getElementById(\"A14\").style.color=\"#ff0000\";\n \t\n\t\tvar item = document.getElementById(\"ImageIDWrong1\");\n\t\tif (item) {\n\t\t\titem.className=(item.className=='hidden')?'unhidden':'hidden';\n }\n \n}\n \nvar item = document.getElementById(\"Question1\"); //here I use these statements to hide the question 1 after the user calls next question\n if (item) {\n item.className=(item.className=='unhidden')?'hidden':'unhidden';\n } \n \n \n var item = document.getElementById(\"Question2\"); // And after disappearing the Question1 next question, Question2 will appear.\n if (item) {\n item.className=(item.className=='hidden')?'unhidden':'hidden';\n }\n\n }" ]
[ "0.70739365", "0.69831365", "0.69819385", "0.6911157", "0.68497247", "0.6846021", "0.6685604", "0.6646871", "0.6642258", "0.6623925", "0.66044986", "0.6559508", "0.6553108", "0.6531467", "0.6524902", "0.64788014", "0.64725673", "0.6448671", "0.64433736", "0.6415571", "0.6394817", "0.6387453", "0.63314694", "0.63232887", "0.632193", "0.63119024", "0.6303507", "0.62965024", "0.62942725", "0.62885237", "0.6288498", "0.6283532", "0.6275016", "0.6255901", "0.6238024", "0.6222503", "0.6214954", "0.6214123", "0.62084424", "0.62072086", "0.6204251", "0.6192924", "0.61917365", "0.61802584", "0.6154222", "0.61529154", "0.6142399", "0.613154", "0.61275786", "0.6126664", "0.61177945", "0.6116861", "0.61151546", "0.6111639", "0.61098355", "0.60970515", "0.6093767", "0.60898376", "0.6081608", "0.6075003", "0.6069284", "0.60667133", "0.6060061", "0.6059249", "0.605196", "0.6047956", "0.60418427", "0.60398346", "0.60368425", "0.603552", "0.60332114", "0.60276496", "0.6014663", "0.6013106", "0.60124964", "0.60092646", "0.60060084", "0.6004775", "0.60041237", "0.60039043", "0.5998976", "0.5997898", "0.5997681", "0.5995825", "0.59948283", "0.5991699", "0.59910756", "0.598548", "0.5983941", "0.5982396", "0.5980006", "0.59771585", "0.5976399", "0.5976328", "0.5974095", "0.59688383", "0.59643835", "0.59574", "0.59521544", "0.5947402" ]
0.67578584
6
Retrieve the next step in the quiz, either a question or a result
getNext() { if (this._position > -1 && !this._data[this._position]._selectedAnswers) throw new Exceptions.QuizNoAnswerSelectedException(); this._position++; let nextQuestion = this._data[this._position]; if (nextQuestion) { // check if there are multple correct answers or not let possibleAnswerCount = nextQuestion.answers.filter(answer => answer.is_correct === true).length; nextQuestion.has_multiple_answers = possibleAnswerCount === 1 ? false : true; // construct the dom node nextQuestion.dom_node = this._constructQuestionDOMNode(nextQuestion); // return the question data return new QuizifyQuestion(nextQuestion); } else { let results = this._gradeQuestions(); return new QuizifyResult(results); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function nextQuestion() {\n const isQuestionOver = (triviaQuestions.length - 1) === currentQuestion;\n if (isQuestionOver) {\n displayResult();\n }else{\n currentQuestion++;\n loadQuestion();\n }\n\n }", "function nextQuestion() {\n currentQuestion++;\n \n if (currentQuestion < quiz.length) {\n displayQuestion();\n } else {\n showResult();\n }\n }", "function nextQuestion() {\n /* set variable isQuestionOver to the value of the two variable, triviaQuestions.length\n and currentQuestion, being equal*/\n var isQuestionOver = (triviaQuestions.length - 1) === currentQuestion;\n // if isQuestionOver true, run displayResults function\n if (isQuestionOver) {\n displayResults();\n\n // else add 1 to currentQuestion and run loadQuestion function.\n } else {\n currentQuestion++;\n loadQuestion();\n }\n }", "function nextQuestion() {\n showQuestion();\n //*********************************** */\n // this logic is implemented because unable to check whether event listener for first round exists with button\n if (startButton.textContent !== \"Retake Quiz\") {\n addEventListenerToButtons(questionIndex);\n }\n //*********************************** */\n}", "function nextQuestion (rightAnswer) {\n if (rightAnswer){\n scoreUp()\n }\n if (question == (data.length - 1)) {\n setQuizEnd(true)\n } else {\n setQuestion(question + 1)\n } \n }", "function loadNextQuestion() {\n var selectedOption = document.querySelector('input[type=radio]:checked');\n if(!selectedOption){\n alert('Choose an answer!');\n return;\n }\n var answer = selectedOption.value;\n if(questions[currentQuestion].answer == answer){\n score += 20;\n secs += 5;\n }\n if(questions[currentQuestion].answer != answer){\n secs -= 25;\n }\n selectedOption.checked = false\n currentQuestion++;\n \n \n if(currentQuestion == totQuestions - 1){\n nextButton.textContent = 'finished';\n }\n if(currentQuestion == totQuestions){\n container.style.display = 'none';\n resultCont.style.display = '';\n resultCont.textContent = \"Your score:\" + score;\n return;\n }\n loadQuestion(currentQuestion);\n }", "function nextStep(data) {\n if (data.type === \"q\") {\n //check if both has a values or not\n if (Object.keys(remaining.children.both).length !== 0) {\n if (data.answer === \"yes\" || data.answer === \"no\") {\n //get answer object\n let userAnswer = remaining.children[\"both\"];\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n } else {\n //get answer object\n let userAnswer = remaining.children[data.answer];\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n }\n if (data.type === \"i\") {\n let userAnswer = remaining.children[\"normal\"];\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n if (data.type === \"e\") {\n let userAnswer = remaining.children[\"normal\"];\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n if (data.type === \"c\") {\n let userAnswer = \"\";\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n if (data.type === \"a\") {\n let userAnswer = remaining.children[\"normal\"];\n remaining = userAnswer;\n //adding the first object\n finished.push({\n type: data.type,\n answer: data.answer,\n lable: data.lable\n });\n }\n}", "nextBaseQuestion() {\r\n const currentIndex = this.currentQuestionPath[0];\r\n\r\n if (currentIndex + 1 < this.questions.length)\r\n this.question = [currentIndex + 1];\r\n else\r\n this.showResults();\r\n }", "function nextQuestion() {\n questionProgress();\n renderQuiz();\n}", "function nextQuestion() {\n if(\"Manager\"){\n managerInfo\n \n ifelse(\"Engineer\")\n engineerInfo\n \n ifelse(\"Intern\")\n internInfo\n \n ifelse(undefined)\n throw(err)\n }\n}", "function get_next_correct_answer() {\n var result = first_answer.correct_answers[first_answer.correct_answer_index];\n first_answer.correct_answer_index = (first_answer.correct_answer_index + 1) % first_answer.correct_answers.length;\n return result;\n }", "function next() {\n state.index += 1;\n if (state.index >= state.quiz.questions.length) {\n state.stage = stages.FINISHED;\n }\n}", "function nextQuestion() {\n // get selected option\n var selectedOption = document.querySelector('input[type=radio]:checked');\n // if the user has not selected anything inform with a message\n if(!selectedOption) {\n alert('Please select one of the answers.');\n return;\n }\n // if the answers is correct increase the score\n var answer = selectedOption.value;\n if(questions[currentQuestion].answer == answer) {\n score++;\n }\n selectedOption.checked = false;\n currentQuestion++;\n // if it is the last question\n if(currentQuestion == totalQuestions - 1) {\n nextButton.textContent = 'Finish';\n }\n // display the results\n if(currentQuestion == totalQuestions) {\n container.style.display = 'none';\n resultContainer.style.display = 'block';\n resultText.textContent = 'Your score: ' + score + '/5';\n return;\n }\n // load next question\n loadQuestion(currentQuestion);\n}", "function nextQuestion(){\n var questionOver = (questions.length -1) === currentQuestion\n if (questionOver) {\n resultDisplay()\n } else {\n currentQuestion++;\n loadQuestions();\n }\n}", "function nextAnswers() {\n\t\tif (CURRENT_QNUM <= NUM_QUESTIONS) {\n\t\t\tvar index = order[CURRENT_QNUM-1]-1;\n\t\t\treturn answers[index];\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}", "function nextQuestion() {\n const isQuestionOver = (quizQuestions.length - 1) === currentQuestion;\n if (isQuestionOver) {\n console.log('Game has ended.');\n displayResult();\n } else {\n currentQuestion++;\n loadQuestion();\n }\n\n}", "function loadNextQuestion () {\n let selectedOption = document.querySelector('input[type=radio]:checked')\n if (!selectedOption){\n alert(\"Please select your answer!\")\n return\n }\n let answer = selectedOption.value \n //console.log(answer)\n if(questions[currentQuestion].answer == answer){\n score += 10\n }\n //console.log(questions[currentQuestion].answer)\n selectedOption.checked = false\n currentQuestion++\n if (currentQuestion == totalQuestion - 1){\n nextButton.textContent = 'Finish'\n }\n if (currentQuestion == totalQuestion){\n container.style.display = 'none'\n resultCont.style.display = \"\"\n resultCont.textContent = 'Your Score: ' + score\n resetButton.style.display = \"\"\n return\n }\n loadQuestion(currentQuestion)\n}", "function nextQuestion() {\r\n if (STORE.questionNumber < STORE.questions.length - 1) {\r\n STORE.submittedAnswer = false;\r\n STORE.view = 'question';\r\n STORE.questionNumber++;\r\n }\r\n else {\r\n STORE.view = 'score';\r\n finalScore();\r\n }\r\n}", "function getThisQuest(direction){\n questNow = $('#questionNow');\n classNow = $(questNow).attr('class');\n questNum = classNow.split('question');\n questNum = parseInt(questNum[1]);\n // split off - track question # for results\n if (direction === 'answer'){\n return (questNum);\n }\n // split off - track question # for pagination\n else {\n questNext = $('.quizBody.question' + (questNum + 1));\n questBack = $('.quizBody.question' + (questNum - 1));\n quizMove(direction);\n }\n }", "function nextQuestion(question, searchType) {\n inquirer.prompt([\n {\n type: \"text\",\n message: question,\n name: \"answer\"\n }]).then(function (response) {\n //calling specific function to search api\n decision(searchType, response.answer);\n });\n}", "function nextQuestion(){\n questionIndex++\n if (theQuestions.length > questionIndex){\n showQuestion()\n } else {\n quizEnd()\n }\n}", "function nextQuestion(){\n\t\t$(\"#question\").show();\n\t\t$(\".choice\").show();\n\t\t$(\"#solutionDiv\").hide();\n\t\tstopwatch.reset();\n\t\tquizGo(i++);\n\t}", "function nextQuestion() {\n // Increment the quiz question count by 1\n count++\n //Remove previous question from HTML before going onto the next question in the quiz.\n $(\"#question-div\").hide();\n //Remove choice buttons from previous question from HTML.\n $(\"#view-quiz-results-div\").empty();\n //Increment progress bar by 10 for each question.\n // $('#quiz-progress-bar')\n // .progress('increment', 10);\n //If the count is the same as the length of the questionSet.questionArray array, find match.\n if (count === questionSet.questionArray.length) {\n findMatch();\n }\n\n //else, if there are still questions left, go to next question.\n else {\n start();\n }\n}", "function nextQuestion() {\n currentQuestion = currentQuestion + 1;\n if (currentQuestion < questions.length) {\n question();\n } else {\n gameSummary();\n }\n}", "function goToNextQuestion(){\n\n\t// Display question page.\n\tshowSection(questionPage);\n\n\t// Empties out existing answers from previous question.\n\t$( \".answer-choices\" ).empty();\n\n\t// Displays question and possible answers.\n\tdisplayQuestion();\n\n\t// Resets question timer.\n\tresetTimer();\n\n}", "function nextQuestion() {\n $(\".userAnswer\").remove();\n $(\".answerCheck\").show();\n if (this.id === currentQuestion[2][0]) {\n scoreTracker = scoreTracker + 1;\n $(\".answerCheck\").text(\"correct!\");\n } else {\n $(\".answerCheck\").text(\"incorrect!\");\n timePassed = timePassed + 4;\n }\n\n if (questionPlusAnswer < quizquestions.length - 1) {\n startQuiz();\n } else {\n finalScorePage();\n stopTimer();\n }\n }", "function _nextQuestion() {\n var nextQuestion = vm.questionSelected.Id;\n nextQuestion++;\n console.log(nextQuestion);\n // run function to get question \n _getQuestion(nextQuestion);\n }", "function nextQuestion() {\n checkAnswer();\n qtrack += 1;\n isEnd();\n if (!end) updateQuestion();\n}", "function nextQuestion() {\n // checks to see if there is a next q and a in the quiz\n if (currentQuestion < quiz.length - 1) {\n // increment the question index\n currentQuestion++;\n loadQuestion();\n // displays the new question and answers\n }\n if (currentQuestion >= quiz.length) {\n clearTimeout(count);\n endQuiz();\n };\n }", "function clickNext() {\n var currentEQ = checkCurrent();\n\n // 01.save next step to local Storage\n if(currentEQ !== $('.slide').length - 1) {\n saveStorage(currentEQ+1);\n }\n // 02.check if end of quiz\n if(currentEQ == $('.slide').length - 1 ) {\n //localStorage.setItem('step','end');\n //$('.slide').eq(currentEQ).removeClass('active');\n }\n // 03.change status of div view\n checkProgress();\n}", "function nextQuestion() {\n\t$(\"#correct-display\").hide();\n\t$(\"#wrong-display\").hide();\n\t$(\"#oOT-display\").hide();\n\t$(\"#question-container\").show();\n\t$(\"#choices\").show();\n\tcurrentQuestion++;\n\tif (currentQuestion == questions.length) {\n\t\tresults();\n\t} else {\n\t\ttime();\n\t\trun();\n\t\t$(\"#question-container\").html(questions[currentQuestion].question);\n\t\t$(\"#a\").html(questions[currentQuestion].choices[0]);\n\t\t$(\"#b\").html(questions[currentQuestion].choices[1]);\n\t\t$(\"#c\").html(questions[currentQuestion].choices[2]);\n\t\t$(\"#d\").html(questions[currentQuestion].choices[3]);\n\t}\n}", "function nextQuestion() {\n\n}", "function nextQuestion() {\n quizContentIndex++;\n // note that the answerResult box needs to be hidden again as questions and answers are iterated\n hideElement(answerResult);\n renderQuestion();\n}", "function nextQuestion(){\n var isQuestionOver= (quizQuestions.length - 1) === currentQuestion;\n if (isQuestionOver){\n console.log(\"game is over\");\n displayResult();\n } \n \n else{\n currentQuestion++;\n loadQuestion();\n }\n \n}", "function nextQuestion(){\n if(runningQuestion < lastQuestion){\n runningQuestion++;\n showQuestion();\n } else{\n endQuiz();\n }\n}", "function nextQuestion() {\n questionIndex++;\n if (questionIndex === questions.length) {\n time = 0;\n finishQuiz();\n }\n if (time <= 0) {\n finishQuiz();\n }\n buildQuiz();\n}", "function nextQuestion() {\n\t// debugger\n\tlet currentQuestion = questionList[getCurrentIndex()];\n\tlet questionsAnswered = getCurrentIndex();\n\t//.html is a setter\n\t$('#container').html(showQuizTemplate(correctAnswers, currentQuestion, questionNumber));\n\tconsole.log(nextQuestion);\n}", "function nextQuestion() {\n\n if (currentQuestion < lastQuestion) {\n currentQuestion++;\n showQuestion();\n } else {\n endQuiz();\n }\n}", "function nextQuestion() {\n questionsIndex++\n console.log(\"click worked!\")\n\n if (questionsIndex === questions.length) {\n endQuiz()\n } else {\n generateQuestion()\n }\n\n}", "function nextQuestion() {\n if (currentQuestion + 1 < questions.length) {\n setCurrentQuestion(prevCurrent => prevCurrent+1);\n }\n }", "function nextQuestion() {\n resetState();\n showQuestion();\n}", "function nextQuestion(){\n\nbuildQuiz()\n}", "function nextQuestion() {\n if (currentQuestion <= 4) {\n reset();\n displayQuestions();\n displayChoices();\n console.log(currentQuestion);\n } else {\n gameOver();\n }\n}", "nextQuestion() {\n this.stoptimer();\n this.round++;\n if (this.round > 0) {\n this.canConnect = false;\n }\n this.resetReadystate();\n if ((this.round > 0 && this.round <= this.maxrounds) && this.round <= this.questions.length) {\n this.getQuestion().then((q) => {\n this.currentquestion = q;\n if (this.timer === null) {\n this.timer = setTimeout(() => {\n this.finishQuestion();\n }, 30 * 1000); // after 30s\n }\n this.timerUpdate(30);\n this.masterUpdate();\n this.playerUpdate();\n this.allowAnwsers = true;\n }, (err) => {\n console.log(err);\n });\n } else if (this.round > this.maxrounds || this.round > this.questions.length) {\n this.showWinners();\n }\n }", "function nextQuestion() {\n newQuestion();\n}", "function loadNextQuestion()\n{\n //debugger;\n $(\"#questionPanel\").show();\n $(\"#displayAnswer\").empty();\n\n\n\n var selectedAns = document.querySelector(\"input[type=radio]:checked\");\n if(!selectedAns)\n {\n alert(\"select a answer\");\n return;\n }\n var answer = selectedAns.value;\n console.log(answer)\n console.log(question[currentQuestion].answer)\n if(question[currentQuestion].answer===answer)\n {\n correct++;\n console.log(\"correct: \" + correct)\n\n }\n selectedAns.checked = false;\n currentQuestion++;\n if(currentQuestion===totalQuestions-1)\n {\n $(\"#submit\").text(\"Finish\")\n }\n if(currentQuestion===totalQuestions)\n {\n \n stopTimer=true\n \n return;\n }\n\n loadQuestion(currentQuestion)\n\n}", "function nextQuestion(){\t\n\t\thideAnswerBox();\n\t\tremovePosters();\n\t\tstopAudio();\n\t\tquestionCount++;\n\t\t\n\t\tif (questionCount > 9) {\n\t\t\tendGame();\n\t\t\tshowOverlay($('.endGame'));\n\t\t}\n\t\telse if (questionCount > 4 && gameCount < 1) {\n\t\t\tendRound();\n\t\t\tshowOverlay($('.end_round'));\n\t\t}\n\t\telse {\n\t\t\tupdateQuestion();\n\t\t\tplayAudio();\n\t\t}\n\t}", "function nextQuestion() {\n\tif (questionNumber < 6) {\n\tquestionNumber++;\n\tshowTriviaGame();\n\tquestionTimer = 30;\n\tgameTimer();\n\t}\n\telse {\n\t\tresultsScreen();\n\t\t$(\"#results\").show();\n\t}\n}", "function nextQuestion() {\n \n index += questions;\n index = index > quiz.questions.length ? quiz.questions.length : index;\n \n if (index === quiz.questions.length) {\n disableElement(\"#nextBtn\");\n enableElement(\"#prevBtn\");\n $(\".question\").append(\"<input type=\\\"button\\\" onclick=\\\"buildAnswerObj()\\\" id=\\\"submit\\\" data-theme=\\\"b\\\" value=\\\"Submit Quiz\\\">\");\n //TODO fix it\n loadPage(\"#question\");\n } else {\n enableElement(\"#prevBtn\");\n }\n presentQuestion(true);\n}", "function nextQuestion() {\n if (correctAnswers === 5) {\n setQuizStarted(!quizStarted);\n } else {\n let oldBird = correctBird;\n setAnswerType('none_yet');\n setAnswered(false);\n setCorrectBird(randomize(\"correct\", oldBird));\n }\n }", "function moveNext(qn) {\n //get next question number\n var nextQuestion = parseInt($(\"#hQuestionNumber\").val()) + 1;\n //store the current question answer\n sessionStorage.setItem(\n \"oans_\" + qn,\n $(\"input[name=r_\" + qn + \"]:checked\").attr(\"id\")\n );\n ///if last question then display results else move to next question\n if (nextQuestion == items.length) {\n displayResults();\n } else {\n setTimeout(function() {\n displayQuiz(nextQuestion);\n }, 1000);\n }\n}", "function displayNext() {\n quiz.fadeOut(function() {\n $('#question').remove();\n \n if(questionCounter < questions.length){\n var nextQuestion = createQuestionElement(questionCounter);\n quiz.append(nextQuestion).fadeIn();\n if (!(selections[questionCounter] === undefined)) {\n $('input[value='+selections[questionCounter]+']').prop('checked', true);\n }\n }else {\n var projeto = window.location.search.substring(1).split('&')[0].split('=')[1];\n var aluno = window.location.search.substring(1).split('&')[1].split('=')[1];\n $.ajax({\n data: 'result='+selections+'&projeto='+projeto+'&aluno='+aluno,\n url: 'php/servicos/_questionario.php?',\n method: 'POST', // or GET\n success: function(result){\n window.location.replace(\"questionario.php\");\n }\n });\n $('#next').hide();\n }\n });\n }", "function navigate() {\n // Advance to next question by increasing the questionIndex value\n questionIndex++;\n // Verify condition of next question and\n if (questionIndex !== questionArray.length) {\n game();\n } else {\n endGame();\n }\n}", "function getNextQuestion(currentQuestion) {\n\tvar currentAnswer = userAnswers[currentQuestion];\n\tif (currentAnswer == undefined) {\n\t\tif (questionTree[currentQuestion][\"next\"] !== undefined) { //question did not care about user answer\n\t\t\treturn (questionTree[currentQuestion][\"next\"]);\n\t\t} else {\n\t\talert(\"Error: User did not answer this question.\");\n\t\t}\n\t} else {\n\t\tif (questionTree[currentQuestion][currentAnswer] == undefined) {\n\t\t\talert(\"Error: User gave an unacceptable answer to this question.\");\n\t\t} else {\n\t\t\treturn questionTree[currentQuestion][currentAnswer];\n\t\t}\n\t}\n}", "function getNextQuestion(questionID, neither) {\n let currentQuestion = unnested.find(question => question.id == questionID)\n \n if (currentQuestion.next == null) {\n getGenres()\n } else {\n let another = currentQuestion.next.length > 2 ? true : false;\n \n if (optionNum + 2 > currentQuestion.next.length) {\n optionNum = 0;\n } \n \n let choice1 = currentQuestion.next[optionNum];\n let choice2 = currentQuestion.next[optionNum+1];\n \n displayNextQuestion(choice1, choice2, another);\n }\n\t}", "function nextQuestion(){\n console.log('Next Question fired..')\n if((triviaQuestions.length -1) === currentQuestion){\n triviaResult()\n } \n else {\n currentQuestion++;\n $(\"#currentQuestion\").empty();\n displayQuestion()\n }\n}", "nextstep(step) {}", "function nextQuestion(e) {\n var isCorrect = e.target.getAttribute(\"data-correct\");\n //take away time if they choose the wrong answer and shake elements\n if (!isCorrect) {\n timer -= 12;\n $questionBox.addClass('shake');\n $timer.addClass('shakeTime');\n setTimeout(() => {\n $questionBox.removeClass('shake');\n $timer.removeClass('shakeTime');\n }, 300)\n //otherwise, bounce the question box\n } else {\n $questionBox.addClass('bounce');\n setTimeout(() => {\n $questionBox.removeClass('bounce');\n }, 300);\n }\n //update progress bar\n updateProgress(isCorrect);\n qNumber++;\n //if you have reached the end of the questions, end the quiz\n qNumber < questions.length ? loadQuestion(questions, qNumber) : endQuiz();\n }", "getNextQuestion() {\n return this.questions[this.questionIndex];\n // console.log(this.questions[this.questionIndex]);\n }", "function nextQuestion(event) {\n\n\n // condition uses click event to add to user score if correct ansser is made //\n if (event.target.value === questions[currentQuesIndex].correctAns) {\n score++;\n } else {\n time -= 5;\n counter.textContent = time + \" Seconds left on quiz.\";\n }\n\n\n\n // Condition executes next question\n if (currentQuesIndex < questions.length) {\n currentQuesIndex++;\n // moves to next section once condition is met\n } if (currentQuesIndex === questions.length) {\n\n quizEl.style.display = \"none\";\n // this function call takes user to results section\n quizResults();\n return;\n\n }\n showQuestion();\n}", "function goToNextQuestion() {\n\n\n\n // Display question page.\n\n showSection(questionPage);\n\n\n\n // Empties out existing answers from previous question.\n\n $(\".answer-choices\").empty();\n\n\n\n // Displays question and possible answers.\n\n displayQuestion();\n\n\n\n // Resets question timer.\n\n resetTimer();\n\n\n\n}", "function next() {\n globalQuestionNumber += 1;\n if (globalQuestionNumber > globalMaxQuestionNumber) {\n globalState = STATE_FINISHED;\n } else {\n globalState = STATE_PLAYING;\n }\n generateQuestion();\n renderState();\n\n}", "function getNextQuestionIndex () {\n\n // remove current class from all li's\n resetStepIndicator();\n\n // loop thru questions block\n for (var i=0; i < questions[currentTheme].length; i++) {\n\n // if current question is unanswered\n if (!questions[currentTheme][i].answered) {\n\n // add current class to this question\n setCurrentStepIndicator(i);\n\n // return the index\n return i;\n\n }\n else {\n\n // if correct answer\n if (questions[currentTheme][i].correct) {\n\n // add correct class to this question\n setCorrectStepIndicator(i);\n\n }\n else {\n\n // add correct class to this question\n setIncorrectStepIndicator(i);\n\n }\n\n }\n\n }\n\n // all questions are answered\n quizComplete();\n\n}", "function nextQuestion() {\n\n // If all questions are completed hide end the quiz\n if (currentQuestionNumber == questions.length) {\n endQuiz();\n return;\n }\n // Otherwise update current question\n currentQuestion = questions[currentQuestionNumber];\n // Inject all properties to UI\n $(\"#questionNumber\").text(currentQuestionNumber + 1);\n $(\"#questionText\").text(currentQuestion.question);\n $(\"#answerA\").text(currentQuestion.answers.a);\n $(\"#answerB\").text(currentQuestion.answers.b);\n $(\"#answerC\").text(currentQuestion.answers.c);\n\n\n}", "function next_slide(){\n var curEQ = checkCurrent(),\n stepData = localStorage.getItem('step'),\n numGet = stepData.slice(-2),\n slideStep = Number(numGet) - 1;\n\n if(slideStep == (lengthQuiz-1)) {\n //01.update storage\n localStorage.setItem('step','end');\n showResult();\n //02.set hash\n var endStep = localStorage.getItem('step');\n window.location.hash = endStep;\n //03.Go to contact form\n window.location = '/contact/';\n } else {\n slider.goToNextSlide();\n }\n}", "function handleQuizResult() {\n $('.next-button').on('click', function(event){\n handleQuizResult();\n });\n if (STORE.currentQuestionIndex === STORE.questions.length) {\n $('#final-correct').html(\"\");\n $('#final-correct').append(`<h4>You got ${STORE.score} out of 10 correct!</h4>`);\n $('#js-results-page').show();\n $('#js-quiz-page').hide();\n $('#js-feedback-correct').hide();\n $('#js-feedback-incorrect').hide();\n $('#js-starting-screen').hide();\n } else {\n renderQuestion();\n }\n console.log('handleQuizResult` ran');\n}", "function showNextSlide() {\n if (exerciceSlides.includes(currentSlide)) {\n SaveSelectedExerciceRadio(); //save answer\n rowResult.push(GetCurrentDate());\n rowResult.push(timeElapsed); //save time\n }\n\n else if (confSlides.includes(currentSlide)) {\n SaveSelectedExerciceRadio();\n results = results.concat([rowResult]);\n rowResult = [];\n }\n\n\n console.log(\"resultat: \" + JSON.stringify(results));\n showSlide(currentSlide + 1);\n ClearExerciceRadio();\n }", "function nextQuestion() {\n\t\tqCounter++;\n\t\t// clears previous selection\n\t\t$(\"input[name='choice']\").prop(\"checked\", false);\n\n\t\t// checks to see if qCounter is equal to 10\n if (qCounter == 10) {\n\t \tstopwatch.stop();\n\t $(\"#main\").hide();\n\t $(\"#end\").show();\n\t $(\"#final-score\").html(\"<h2>You got \" + correct + \" out of \" + questions.length + \" questions correct!\");\n }\n\n //calls displayQuestions\n stopwatch.stop();\n displayQuestions();\n }", "function nextQuestion() {\n // Clear the timeout that was set by displayAnswer. Clear the interval as well just in case.\n clearTimeout(game.timeoutID);\n clearInterval(game.intervalId);\n // Go to the next question\n game.questionIndex++;\n // If we're on the last question, the game is over. \n if (game.questionIndex >= questions.length) {\n endGame();\n } else { // Otherwise display the next question\n displayQuestion();\n }\n}", "function displayNext() {\n quiz.fadeOut(function() {\n $('#question').remove();\n\n if (questionCounter < questions.length) {\n var nextQuestion = createQuestionElement(questionCounter);\n quiz.append(nextQuestion).fadeIn();\n if (!(isNaN(selections[questionCounter]))) {\n $('input[value=' + selections[questionCounter] + ']').prop('checked', true);\n }\n\n // Controls display of 'prev' button\n if (questionCounter === 1) {\n $('#prev').show();\n } else if (questionCounter === 0) {\n\n $('#prev').hide();\n $('#next').show();\n }\n } else {\n window.location.href = \"results.html\";\n $('#next').hide();\n $('#prev').hide();\n $('#start').show();\n }\n });\n }", "function nextQuestion(){\n var n = Math.floor(Math.random() * q.length);\n q[n].display1();\n var ans = prompt('Please select the correct answer. (tap \\'exit\\' to exit)');\n \n if (ans !== 'exit'){\n q[n].checkAnswer(parseInt(ans),keepScore);\n nextQuestion();\n }\n }", "get next() { return this.nextStep; }", "function getQuestion() {\n let num = store.questionNumber;\n let nextQuestion = store.questions[num];\n return nextQuestion;\n}", "nextPage() {\r\n this.mapSectionStatus();\r\n if (!this.state.allQuestionsCompleted) {\r\n /* reset questions to the top of the page */\r\n this.divRef.current.scrollTo(0, 0);\r\n }\r\n\r\n const numberOfQuestions = this.state.pages[this.state.index].questions\r\n .length;\r\n var controllingQuestionIndex = numberOfQuestions - 1;\r\n var answerIndex = this.findAnswer(\r\n this.state.index,\r\n controllingQuestionIndex\r\n );\r\n\r\n /* validation check for questions */\r\n var passed = true;\r\n\r\n if (\r\n !(\r\n (this.state.SurveyTitle === \"CIDP SOC\" ||\r\n this.state.SurveyTitle === REPEAT_VISIT_SURVEY) &&\r\n this.state.answerIndexes.length !== 0\r\n )\r\n ) {\r\n const currentPage = this.state.pages[this.state.index];\r\n var errors = this.state.errorFields;\r\n var answerIndexes = this.state.answerIndexes;\r\n currentPage.questions.forEach((question, qIndex) => {\r\n const isRequired = question.required;\r\n\r\n var foundObject = answerIndexes.find(answer => {\r\n return answer.qIndex === qIndex && answer.page === this.state.index;\r\n });\r\n\r\n if (!foundObject && question.questionType !== \"Label\") {\r\n var answerObject = {\r\n page: this.state.index,\r\n qIndex: qIndex,\r\n answer: \"\"\r\n };\r\n\r\n answerIndexes.push(answerObject);\r\n }\r\n // we are checking if the foundobject is undefined or foundobect is exist but the answer doesn't\r\n // the foundobject is empty for the first time when we click on the survey and without answers click on Next button\r\n if (\r\n (!foundObject ||\r\n (foundObject &&\r\n (foundObject.answer === \"\" ||\r\n typeof foundObject.answer == \"undefined\"))) &&\r\n this.state.questionsAnswered[qIndex] === false &&\r\n isRequired\r\n ) {\r\n errors[qIndex] = true;\r\n passed = false;\r\n } else {\r\n errors[qIndex] = false;\r\n }\r\n\r\n answerIndexes.sort((a, b) => {\r\n return a.page - b.page || a.qIndex - b.qIndex;\r\n });\r\n\r\n this.setState({ answerIndexes: answerIndexes, errorFields: errors });\r\n });\r\n }\r\n\r\n //updating pending assessments even when we click on next button\r\n updatePendingAssessmentState(\r\n this.props.patient.MRN,\r\n this.state.selectedSurvey,\r\n {\r\n firstName: this.props.patient.FirstName,\r\n lastName: this.props.patient.PatientLastName,\r\n MRN: this.props.patient.MRN,\r\n DOB: moment(new Date(Date.parse(this.props.patient.DOB))).format(\r\n \"MM/DD/YYYY\"\r\n )\r\n }\r\n );\r\n\r\n if (passed) {\r\n var nextPage = getNextPage(\r\n this.state.pages,\r\n this.state.index,\r\n controllingQuestionIndex,\r\n answerIndex\r\n );\r\n\r\n while (nextPage === -1 && controllingQuestionIndex > 0) {\r\n controllingQuestionIndex = controllingQuestionIndex - 1;\r\n answerIndex = this.findAnswer(\r\n this.state.index,\r\n controllingQuestionIndex\r\n );\r\n nextPage = getNextPage(\r\n this.state.pages,\r\n this.state.index,\r\n controllingQuestionIndex,\r\n answerIndex\r\n );\r\n\r\n if (nextPage === -1) {\r\n if (\r\n this.state.pages[this.state.index].questions &&\r\n !this.state.pages[this.state.index].questions.find(\r\n item => item.required\r\n )\r\n ) {\r\n if (this.state.index + 1 < this.state.pages.length) {\r\n nextPage = this.state.index + 1;\r\n }\r\n }\r\n }\r\n }\r\n if (nextPage === -1 && !this.state.allQuestionsCompleted) {\r\n this.setState(\r\n { allQuestionsCompleted: true, progress: \"100\" },\r\n\r\n () => {\r\n this.saveToLocalStorage();\r\n }\r\n );\r\n } else {\r\n /* reset question values back to false */\r\n const questionsToComplete = this.state.pages[nextPage].questions.map(\r\n (question, qIndex) => {\r\n return question.questionType === \"Label\";\r\n }\r\n );\r\n\r\n //getting prevc surveyid,surveyname,surveyindecx for updating survey side bar\r\n this.handleNextandPrevPages(this.state, nextPage);\r\n\r\n const previousPage = {\r\n index: this.state.index,\r\n progress: this.state.progress\r\n };\r\n\r\n const historyStack = this.state.indexProgressStack;\r\n historyStack.push(previousPage);\r\n\r\n this.setState(\r\n {\r\n prevIndex: this.state.index,\r\n index: nextPage,\r\n prevProgress: this.state.progress,\r\n progress: Math.round((nextPage / this.state.pages.length) * 100),\r\n questionsAnswered: questionsToComplete,\r\n indexProgressStack: historyStack\r\n },\r\n () => {\r\n this.saveToLocalStorage();\r\n this.divRef.current.scrollTo(0, 0);\r\n }\r\n );\r\n\r\n /* when decision logic for the page prompts to skip a page,\r\n check whether there were previously stored answers for page\r\n that won't exist;\r\n ex. IG Administration Survey pages 0, 1, 2 where page 0 answer is decision\r\n */\r\n this.removeSkippedAnswersHistory(\r\n this.state.index,\r\n this.state.prevIndex\r\n );\r\n }\r\n }\r\n }", "function nextQuestion() {\n $question.html('')\n if (questionIndex < questionList.length) {\n let questionMsg = '<h3>' + questionList[questionIndex][\"question\"] + '</h3><ol>'\n for (let i = 0; i < questionList[questionIndex][\"answers\"].length; i++) {\n questionMsg += '<li><button id=\"answer' + (i + 1) + '\">' + (i + 1) + '. ' + questionList[questionIndex][\"answers\"][i] + '</button></li>'\n }\n questionMsg += '</ol>'\n $question.append(questionMsg)\n } else {\n endQuiz()\n }\n }", "nextStep() {\n\n if (this.slides[this.currSlide].steps.length - 1 > this.currStep) {\n\n this.goTo(this.currSlide, this.currStep + 1);\n\n }\n\n }", "function fetchQuestion() {\n return questions[currentQuestion-1];\n }", "function loadNextQuestion() {\r\n var selectOption = document.querySelector('input[type=radio] : checked');\r\n var answerFromPlayer = selectOption.value;\r\n \r\n if (!selectOption) {\r\n alert('Please select your answer or You will not get mark for this question');\r\n return ;\r\n }\r\n if (questions[currentQuestion].answer == answerFromPlayer) {\r\n correct++;\r\n }\r\n selectOption.checked = false;\r\n currentQuestion++;\r\n \r\n if (currentQuestion == questions.length - 1) {\r\n nextButton.textContent = \"You finished the quiz. Let see how many correct questions you got\";\r\n nextButton.style.width = \"400px\";\r\n }\r\n if (currentQuestion == questions.length) {\r\n contain.style.display = \"none\";\r\n document.getAnimations(\"result\").style.display = \" \";\r\n document.getAnimations(\"result\").style.display = \"You got \" + correct + \" answers.\";\r\n document.getElementById(\"score\").textContent = score;\r\n return;\r\n }\r\n if (correct <= 5) {\r\n document.getElementById(\"message\").textContent = messages[1];\r\n document.getElementById(\"gif-source\").textContent = video[3];\r\n }\r\n if (correct <= 7) {\r\n document.getElementById(\"message\").textContent = messages[3];\r\n document.getElementById(\"gif-source\").textContent = video[1];\r\n }\r\n if (correct == 10 ) {\r\n document.getElementById(\"message\").textContent = messages[2];\r\n document.getElementById(\"gif-source\").textContent = video[2];\r\n }\r\n loadQuestion(currentQuestion);\r\n\r\n}", "function nextQ() {\n\tif (iQ <= allQ.length) {\n\t\t$('.beginQuestion').text(currentQ.question);\n\t};\n\n}", "skipCurrentQuestion() {\n if (!this._startTime) {\n console.log(\"Comience el cuestionario primero.\");\n return;\n }\n\n let response = {\n timeOver: this[TIME_OVER_SYM],\n finished: this.isOnLastQuestion() || this._endTime || this[TIME_OVER_SYM]\n };\n\n if (!this[TIME_OVER_SYM]) {\n\n const currentQ = this.currentQuestion;\n if (currentQ.skip !== void (0)) {\n console.log(\"Ya se ha saltado esta pregunta\");\n return;\n }\n if (currentQ.answer !== void (0)) {\n console.log(\"Ya respondiste a esta pregunta\");\n return;\n }\n currentQ.skip = true;\n\n if (!response.finished) {\n const nextQ = askNextQuestion.call(this);\n if (nextQ) {\n response.nextQ = nextQ;\n }\n }\n }\n\n if (response.finished) {\n response.result = this.result();\n this.stop();\n }\n\n return response;\n }", "function nextAction() {\n\tinquirer.prompt({\n\t\tmessage: \"What would you like to do next?\",\n\t\ttype: \"list\",\n\t\tname: \"nextAction\",\n\t\tchoices: [\"Add More Items\", \"Remove Items\", \"Alter Item Order Amount\", \"Survey Cart\", \"Checkout\"]\n\t})\n\t\t.then(function (actionAnswer) {\n\t\t\tswitch (actionAnswer.nextAction) {\n\t\t\t\tcase \"Add More Items\":\n\t\t\t\t\t// go to the start function\n\t\t\t\t\tstart();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Remove Items\":\n\t\t\t\t\t// go to the removal function\n\t\t\t\t\tremoveItem();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Checkout\":\n\t\t\t\t\t// go to the checkout tree;\n\t\t\t\t\tverifyCheckout();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Alter Item Order Amount\":\n\t\t\t\t\t// go to the function that alters the shopping cart qty\n\t\t\t\t\talterItem();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"Survey Cart\":\n\t\t\t\t\t// look at the cart\n\t\t\t\t\tcheckoutFunction();\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: console.log(\"how did you get here?\")\n\t\t\t}\n\t\t})\n}", "function next(){\n var buttons = $(\".button\");\n var selected = [];\n\n // Store Question Responses\n for(var i = 0; i<buttons.length; i++){\n //for chosen buttons add their text to the result array\n if(buttons[i].style.backgroundColor==\"rgb(94, 131, 186)\"){\n //for the \"other\" button, add the user input into the array\n if(buttons[i].innerHTML==\"Other\"){\n selected.push($(\"response\").value);\n } else {\n selected.push(buttons[i].innerHTML)\n }\n }\n }\n\n if(selected.length==0){\n $(\"#nothingSelected\").show();\n return\n }\n\n $(\"#nothingSelected\").hide();\n answers.push(selected);\n\n // If we have answered all of the questions, we are done\n if (QuestionQueue.length == 0) {\n $(\"#content\").fadeOut(400);\n sessionStorage.setItem(\"answers\", answers);\n window.location.href=\"result.html\";\n }\n\n // Save old page to the history, and load next page\n History.push(currentPage);\n currentPage = QuestionQueue.shift();\n setQuestion(currentPage);\n}", "function nextQuestion() {\n var n = Math.floor(Math.random() * questions.length);\n\n questions[n].displayQuestion();\n // Use parseInt to convert ex. \"2\" to integer, not string - 2.\n var answer = prompt('Please select the correct answer.');\n\n if (answer !== 'exit') {\n questions[n].checkAnswer(parseInt(answer), keepScore);\n nextQuestion();\n }\n }", "function goto_next_form() {\n context.current++;\n if (context.current >= context.workflow.length) {\n return finish_survey(); //todo: verify that when going Back and clicking Next this doesn't break the flow\n }\n //Store the incremented value of 'current'\n Survana.Storage.Set('current', context.current, function () {\n //load the next form\n window.location.href = context.workflow[context.current];\n }, on_storage_error);\n }", "function nextQuestion() {\n\tif (question_counter < questions.length - 1) {\n\t\tquestion_counter++;\n\t\tquestion_button_default.style.display = \"none\";\n\t\tquestion_button_default.classList.remove('btn--wrong')\n\t\tquestion_button_default.classList.remove('btn--correct')\n\t\tshowQuestions(question_counter)\n\t} else {\n\t\tconsole.log('> No more questions: Staph');\n\t\tshowResultBox();\n\t}\n}", "function displayNextQuestion(nextQuestion) {\n currentIndex++;\n if (currentIndex < questions.length) {\n checkCorrect(nextQuestion.target.innerText === nextQuestions.answer);\n questionAnswers.innerText = '';\n if (currentIndex < questions.length) {\n nextQuestions = questions[currentIndex];\n displayQuestion(nextQuestions);\n } else {\n currentIndex = 0\n displayQuestion(nextQuestions);\n }\n } else {\n endQuiz();\n // setTimeout(function () {\n // endQuiz();\n // }, 1000);\n }\n}", "function resultOfTrivia() {\n\tif (question === 1) {\n\t\tresult1();\n\t}\n\telse if (question === 2) {\n\t\tresult2();\n\t}\n\telse if (question === 3) {\n\t\tresult3();\n\t}\n\telse if (question === 4) {\n\t\tresult4();\n\t}\n\telse if (question === 5) {\n\t\tresult5();\n\t}\n\telse if (question === 6) {\n\t\tresult6();\n\t}\n\telse if (question === 7) {\n\t\tresult7();\n\t}\n\telse if (question === 8) {\n\t\tresult8();\n\t}\n\telse if (question === 9) {\n\t\tresult9();\n\t}\n\telse if (question === 10) {\n\t\tresult10();\n\t}\n}", "function nextQuestion() {\n\t\tif (questionCounter < questions.length) {\n\t\t\ttime = 15;\n\t\t\t$(\"#gameScreen\").html(\"<p>You have <span id='timer'>\" + time + \"</span> seconds left!</p>\");\n\t\t\tquestionContent();\n\t\t\ttimer();\n\t\t\tuserTimeout();\n\t\t}\n\t\telse {\n\t\t\tresultsScreen();\n\t\t}\n\t// console.log(questionCounter);\n\t// console.log(questions[questionCounter].correctAnswer);\n\t}", "function nextQuestion() {\n\t\tif (questionCounter < questions.length) {\n\t\t\ttime = 15;\n\t\t\t$(\"#gameScreen\").html(\"<p>You have <span id='timer'>\" + time + \"</span> seconds left!</p>\");\n\t\t\tquestionContent();\n\t\t\ttimer();\n\t\t\tuserTimeout();\n\t\t}\n\t\telse {\n\t\t\tresultsScreen();\n\t\t}\n\t// console.log(questionCounter);\n\t// console.log(questions[questionCounter].correctAnswer);\n\t}", "function nextQuestion() {\n\t\tif (questionCounter < questions.length) {\n\t\t\ttime = 15;\n\t\t\t$(\"#gameScreen\").html(\"<p>You have <span id='timer'>\" + time + \"</span> seconds left!</p>\");\n\t\t\tquestionContent();\n\t\t\ttimer();\n\t\t\tuserTimeout();\n\t\t}\n\t\telse {\n\t\t\tresultsScreen();\n\t\t}\n\t// console.log(questionCounter);\n\t// console.log(questions[questionCounter].correctAnswer);\n\t}", "function handleNextQuestion() {\n //console.log('Handling next question process');\n $('.result').on('click', '.btnNextQuestion', function(event) {\n clearAnswer();\n if (STORE.currentQuestion < QUESTIONS.length) {\n advanceToNextQuestion();\n STORE.view = 'quiz';\n } else {\n STORE.view = 'finalResult';\n }\n render();\n \n });\n}", "function nextQuestion() {\n console.log(\"question \" + questionCount + \" loaded\");\n startTimer();\n\n $(\"#result\").empty();\n $(\"#question\").html(triviaKey[questionCount].question);\n\n // spawn options for active question\n for (var i = 0; i < triviaKey[questionCount].options.length; i++) {\n var eachOption = $(\"<button>\");\n eachOption.text(triviaKey[questionCount].options[i]);\n eachOption.attr(\"value\", i);\n eachOption.attr(\"type\", \"button\");\n eachOption.addClass(\"btn btn-light choice\");\n $(\"#options\").append(eachOption);\n $(\"#options\").append(\"<br>\");\n console.log(\"index value: \" + eachOption.attr(\"value\"));\n }\n\n // go to results page when an answer is pressed\n $(\".choice\").on(\"click\", function () {\n choice = parseInt($(this).attr(\"value\"));\n console.log(\"index of choice: \" + choice);\n clearInterval(timerOn);\n results();\n });\n }", "function nextQ(){\n\tquestionCount++;\n}", "function next_question() {\n var questionDiv = document.getElementById(\"question\");\n questionDiv.innerText = questions[round].question;\n var choicesDiv = document.getElementById(\"choices\");\n choicesDiv.innerText = questions[round].choices;\n}", "function next_question() {\n if (q_index < 49) {\n q_index++;\n let new_question = questions[q_index];\n console.log(new_question);\n $('.question').text(new_question);\n } else {\n calculate_results();\n $(\".test_interface\").addClass(\"hidden\");\n $(\".test_done\").removeClass(\"hidden\");\n }\n}", "function nextQuestion() {\n resetState()\n showQuestion(getRandomQuestion[questionIndex])\n}", "function continue_next_question() {\n\t// Pressed continue, now get the next question ready\n\tupdate_progress_section()\n\t//display_format = choose_next_display_format()\n\tdebug(\"The display format has been updated:\")\n\tdebug(display_format)\n\thide_or_show_display_format_titles()\n\thide_or_show_hint_button()\n\tprepare_hint_button()\n\treset_temp_score_array()\n\tquestion = generate_formatted_array(display_format)\n\tshow_question_if_scaffold()\n\tarray_to_hidden_divs('content_area_body', question)\n\tshow_latest_question('content_area_body')\n\tprepare_check_button()\n}", "function nextQuestion() {\n defaultState()\n displayQuestions(shuffleQuestions[currentQuestion])\n}", "function nextQuestion() {\n\n progress += parseInt(progressPerQuestion);\n $progressBar.style.width = progress + '%';\n\n if (++currentQuestion > quizItems.length - 1) {\n endQuiz();\n } else {\n clearChoices();\n }\n $submitAnswerButton.setAttribute('disabled', '');\n\n}", "function nextQuestion () {\n $('.js-fieldset').on('click', '#next', function() {\n if (STORE.questionNumber < STORE.questions.length) {\n renderFieldsetForm('question', STORE);\n }\n else {\n renderFieldsetForm('end', STORE);\n }\n });\n}" ]
[ "0.7197843", "0.7099756", "0.7055396", "0.6944611", "0.68791986", "0.67972666", "0.67965084", "0.6787657", "0.6782662", "0.67815286", "0.677654", "0.675929", "0.6755195", "0.67465687", "0.6692765", "0.6681112", "0.66695", "0.6658128", "0.6654292", "0.6642181", "0.6640567", "0.66385114", "0.66372365", "0.6631364", "0.6625884", "0.66050524", "0.6586762", "0.6583823", "0.6583684", "0.65792686", "0.6560152", "0.6552531", "0.6532852", "0.6530689", "0.6526317", "0.65251416", "0.6513069", "0.6507355", "0.6486873", "0.64223987", "0.64176935", "0.64093095", "0.63929516", "0.6373419", "0.63717324", "0.6361575", "0.635996", "0.6341402", "0.63323367", "0.6331373", "0.6318562", "0.6315349", "0.6314429", "0.63123196", "0.63098174", "0.63075244", "0.63019043", "0.6293531", "0.62889665", "0.6288696", "0.6285264", "0.6284821", "0.6284669", "0.6279693", "0.62739915", "0.6266132", "0.6257488", "0.6253786", "0.6246851", "0.6228409", "0.6227402", "0.62247604", "0.6223758", "0.6218903", "0.6214904", "0.61917984", "0.6189912", "0.6186235", "0.61805093", "0.6178602", "0.6176962", "0.6168464", "0.6165907", "0.6162975", "0.6158103", "0.61561567", "0.6149954", "0.61421084", "0.61421084", "0.61421084", "0.613599", "0.61191857", "0.61114675", "0.6109675", "0.60962856", "0.6094157", "0.6092641", "0.6088255", "0.60867447", "0.60837024" ]
0.6596039
26
funcion de mensaje de succes
function vamos() { Swal.fire({ icon: "success", title: "¡Vamos!", text: "Todo a salido bien :)", confirmButtonText: "Cerrar pestaña", }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function OnSuccessCallMaladie(data, status, jqXHR) {\n\t\t\tnotif(\"success\", \"Brief envoyé avec <strong>succès</strong> !\");\n\t\t}", "success(message) {\n return this.sendMessage(MessageType.Success, message);\n }", "function Success(msg, devmsg) {\n success(msg);\n $log.info(devmsg);\n }", "function successMsg(where){\r\n\tsuccess(where,\"Available!\");\r\n}", "function successCB(msg) {\r\n // Success handling\r\n success(msg);\r\n }", "function emailSuccess() {}", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successCB(msg) {\n // Success handling\n success(msg);\n }", "function successTest(data){\r\n return showSuccess(data.message)\r\n}", "function flashSuccess(message) { flashMessage(message, 0); }", "setSuccessMsg(event, data) {\n let _this = event.data;\n _this.tableerr.hide();\n if (data.status === -1) {\n _this.updateMsg(data.errmsg);\n }\n }", "function sentSuccess(){\n //User denied action\n swal({\n title: \"Transaction Successful!\",\n text: \"Reloading Data\",\n type: \"success\",\n timer: 3000,\n showConfirmButton: false\n });\n\n }", "function executing_success(){\n\t\t\t\t\t\t\tvar ret = null;\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\tif App.HTTP['METHOD'] is called with the 'success' field settled, the next conditional is executed\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tif (typeof function_success != \"undefined\") {\n\t\t\t\t\t\t\t\tif (typeof function_success != \"object\") {\n\t\t\t\t\t\t\t\t\tret = {\n\t\t\t\t\t\t\t\t\t\tdata: data\n\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\tfunction_success(ret, textStatus, jqXHR);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tret = Array();\n\n\t\t\t\t\t\t\t\t\tfor (i in function_success) {\n\t\t\t\t\t\t\t\t\t\tret.push({\n\t\t\t\t\t\t\t\t\t\t\tdata: data\n\t\t\t\t\t\t\t\t\t\t}, textStatus, jqXHR);\n\t\t\t\t\t\t\t\t\t\tfunction_success[i]({\n\t\t\t\t\t\t\t\t\t\t\tdata: data\n\t\t\t\t\t\t\t\t\t\t}, textStatus, jqXHR);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t/*\n\t\t\t\t\t\t\t\ta lateral message ('alertify' plugin) is shown if the 'log_ui_msg' is active (settled as 'true')\n\n\t\t\t\t\t\t\t\ta default message is shown if the response of the server doesn't have the field 'message'\n\n\t\t\t\t\t\t\t\tthe default message depends of the type of operation (CREATE, READ, UPDATE, DELETE, POST, PUT)\n\t\t\t\t\t\t\t*/\n\t\t\t\t\t\t\tvar semantic_ref = {\n\t\t\t\t\t\t\t\t\t\"CREATE\" : \"success\",\n\t\t\t\t\t\t\t\t\t\"READ\" : \"warning\",\n\t\t\t\t\t\t\t\t\t\"UPDATE\" : \"success\",\n\t\t\t\t\t\t\t\t\t\"DELETE\" : \"error\",\n\t\t\t\t\t\t\t\t\t\"POST\" : \"message\",\n\t\t\t\t\t\t\t\t\t\"GET\" : \"message\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tsemantic_default_message = {\n\t\t\t\t\t\t\t\t\t\"CREATE\" : \tApp.__GENERAL__.http_message_default_create,\n\t\t\t\t\t\t\t\t\t\"READ\" : \tApp.__GENERAL__.http_message_default_read,\n\t\t\t\t\t\t\t\t\t\"UPDATE\" : \tApp.__GENERAL__.http_message_default_update,\n\t\t\t\t\t\t\t\t\t\"DELETE\" : \tApp.__GENERAL__.http_message_default_delete,\n\t\t\t\t\t\t\t\t\t\"POST\" : \tApp.__GENERAL__.http_message_default_post,\n\t\t\t\t\t\t\t\t\t\"GET\" : \tApp.__GENERAL__.http_message_default_get,\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif(settings.log_ui_msg){\n\t\t\t\t\t\t\t\tif(!jqXHR.responseJSON){\n\t\t\t\t\t\t\t\t\tjqXHR.responseJSON ={}\n\t\t\t\t\t\t\t\t};\n\n\t\t\t\t\t\t\t\tif(!jqXHR.responseJSON.message){\n\t\t\t\t\t\t\t\t\tjqXHR.responseJSON.message = semantic_default_message[semantic.toUpperCase()];\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\talertify[semantic_ref[semantic.toUpperCase()]](jqXHR.responseJSON.message);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tApp.__debug__(ret);\n\n\t\t\t\t\t\t\treturn ret;\n\t\t\t\t\t\t}", "function mensajes(respuesta){\n\n\t\t\t\tvar foo = respuesta;\n\n\t\t\t\t\tswitch (foo) {\n\n\t\t\t\t\t\tcase \"no_exite_session\":\n\t\t\t\t\t\t//============================caso 1 NO EXISTE SESSION==================//\n\t\t\t\t\t\tswal(\n\t\t\t\t\t\t\t\t'Antes de comprar Inicia tu Session en la Pagina?',\n\t\t\t\t\t\t\t\t'Recuerda si no tienes cuenta en la pagina puedes registrarte?',\n\t\t\t\t\t\t\t\t'question'\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\tbreak;\n\n\n\t\t\t\t\t\tcase \"saldo_insuficiente\":\n\t\t\t\t\t\t//==============CASO 2 SALDO INSUFICIENTE=======================//\n\n\t\t\t\t\t\tswal({\n\t\t\t\t\t\t\ttype: 'error',\n\t\t\t\t\t\t\ttitle: 'Oops...',\n\t\t\t\t\t\t\ttext: 'Tu saldo es insuficiente para poder realizar la trasaccion, recarga tu monedero e intenta de nuevo',\n\t\t\t\t\t\t\tfooter: 'Puedes recargas tu saldo con nostros mas informacion en nuestras redes sociales'\n\t\t\t\t\t\t})\n\t\t\t\t\t\tbreak;\n\n\n\n\t\t\t\t\t}\n\t\t\t}", "success(text, dismissable = false){\n this.message(text, 'success', dismissable);\n }", "getSuccessMessage () {\n return SUCCESS_MESSAGE\n }", "function OnSuccessCallMaladie(data, status, jqXHR) {\n\t\t}", "function OnSuccessCallMaladie(data, status, jqXHR) {\n\t\t\treturn true;\n\t\t}", "function successMessage(msg, callback) {\n $.confirm({\n icon: 'fa fa-check fa-lg',\n title: 'Registro correcto!',\n content: `<b>${msg}</b>`,\n type: 'green',\n scrollToPreviousElement: false,\n scrollToPreviousElementAnimate: false,\n buttons: {\n Aceptar: {\n text: 'Aceptar',\n btnClass: 'btn-green',\n action: function () {\n callback;\n }\n }\n }\n });\n}", "function clearSuccessMessage() {\n\n }", "function msgPerdeu() {\n swal({\n title: \"Perdeste!\",\n type: \"error\",\n timer: 3000,\n showConfirmButton: false\n });\n bloqueioBoneco();\n }", "function send() {\r\n\tcheckName();\r\n\tcheckMessage();\r\n\tcheckEmail();\r\n\t//when all are right, show the successful message in the div which id is sendsuccessfully and return true\r\n\tif(checkName()==true && checkMessage()==true && checkEmail()==true) {\r\n\t\tdocument.getElementById(\"sendsuccessfully\").innerHTML=\"Message successfully sent\";\r\n\t\treturn true;\r\n\t}\r\n\t//if one of name, message and email is not right, return false\r\n\treturn false;\r\n}", "static get SUCCESS() { return 0; }", "function add_success_message(js) {\n\teEngine.model('message').msg(JSON.parse(js));\n}", "function createSuccessMsg (loc, msg) {\r\n\t\tloc.append(\r\n\t\t\t'<div class=\"alert alert-success\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button><strong><i class=\"en-checkmark s24\"></i> Well done!</strong> '+ msg + ' </div>'\r\n\t\t);\r\n\t}", "function mensajeGrafico(mensaje,estado,respuesta,estadoRespuesta) {\n\n if(mensaje == \"OK\" && estado == 200 && estadoRespuesta == 10){\n alert(\"Conexion exitosa con Postgres\");\n getBasesDatos_Postgres();\n add_grafico_Postgres();\n }\n else {\n alert(respuesta);\n }\n}", "static succeded() {\n return MediaServerResponse.response('success', '');\n }", "function defaultSuccess(json)\n{\n msg(\"success! \" + (typeof json == \"string\" ? json : JSON.stringify(json)));\n}", "alertSuccess(content) {\n alert(\"success\", content)\n }", "function successRetrieval() {\n console.log(\"Recupero delle notizie completato!\");\n}", "mostra_successo(msg) {\n\t\tvar contenuto = document.getElementById(\"contenuto\");\n\t\twhile ( contenuto.firstChild != null) {\n\t\t\tcontenuto.removeChild(contenuto.firstChild);\n\t\t}\n\t\t$(\"#contenuto\").append(msg);\n\t\t\n\t}", "function messageSuccessHandler() {\n console.log(\"Message send succeeded.\"); \n}", "function messageSuccessHandler() {\n console.log(\"Message send succeeded.\"); \n}", "function messageSuccessHandler() {\n console.log(\"Message send succeeded.\"); \n}", "function msg_success(sText,oOptions){\n\tif (typeof(oOptions) === 'undefined') var oOptions = {};\n\toOptions.additionalClass = 'bg-green';\n\toOptions.message = sText;\n\t//oOptions.button = {text: 'Close',color:'green'};\n\tmsg(oOptions);\n}", "function mensaje(mensaje,estado,respuesta,estadoRespuesta) {\n if(mensaje == \"OK\" && estado == 200 && estadoRespuesta == 10){\n alert(\"Conexion exitosa con Postgres\");\n getBasesDatos_Postgres();\n }\n else {\n alert(respuesta);\n }\n}", "function ShowMessage(title, description, status) {\n debugger\n if (status==1) {\n\n toastr.error(description, title);\n } else {\n\n toastr.success(description, title);\n\n }\n\n}", "function mensaje(){\n\n\talert(\"Mensaje de Bienvenida\");\n}", "static notifySuccess()\n\t\t{\n\t\t\tthis.notify(NotificationFeedbackType.Success);\n\t\t}", "function successMessage() {\n setSubmitButtonMessage(\"Cocktail Saved!\");\n }", "function displaySuccessMsg(msg) {\n\t\t \tswal({\n\t\t \t\t title: \"The action was successfully completed\",\n\t\t \t\t text: msg,\n\t\t \t\t timer: 5000,\n\t\t \t\t type: \"success\",\n\t\t \t\t showConfirmButton: false\n\t\t \t});\n\t\t }", "function mensajeOk(mensaje) {\n $(\"#mensaje\").html(\"\");\n $(\"#mensaje\").append(mensaje);\n mostrarMensaje(\"mensaje\");\n ocultaMensaje(\"mensaje\");\n}", "function Mensajes(mensaje) {\n if (mensaje == 'Transaccion realizada correctamente')\n $().toastmessage('showSuccessToast', mensaje);\n else\n $().toastmessage('showErrorToast', mensaje);\n}", "function msg_SuccessfulSave(){\n new PNotify({\n title: 'Saved',\n text: 'New Record Added.',\n type: 'success'\n });\n }", "function onSuccess () {}", "function getSuccessMessage($form, data) {\n\t\tvar settings = $form.data('inform');\n\t\tif (!settings.successMessage)\n\t\t\treturn data;\n\t\tif ($.isFunction(settings.successMessage))\n\t\t\treturn settings.successMessage.apply($form, [data]);\n\t\treturn settings.successMessage;\n\t}", "function onSuccess() {}", "function setupSuccess(title, message, affirm_button, success_function) {\n \"use strict\";\n if (!title)\n title = \"Success!\";\n if (!message)\n message = \"\";\n if (!affirm_button)\n affirm_button = \"CONTINUE\";\n\n return {title: title, message: message, affirm_button: affirm_button, success_function: success_function};\n}", "function showSuccess() {\n showStatus();\n}", "function notifySuccess(msg, action, on_action) {\n const icon = {\n type: 'icon',\n class: 'material-icons',\n content: 'done',\n };\n console.debug(msg);\n notify('success', msg, action, on_action, icon);\n}", "function checkOk(data){\n if (data[0] != OK) {\n console.log(\"{\\\"error\\\": \\\"cannot establish comms with Testalator\\\"}\")\n return false;\n }\n return true;\n}", "function probando(req, res) {\n res.status(200).send({ message: 'Probando desde del controladaor Message.' });\n}", "retreiveSuccessMessage() {\n this.waitUtil.waitForElementDisplay(\n this.lblSuccessMessage,\n 25000,\n \"Success Message\"\n );\n return this.lblSuccessMessage.getText();\n }", "static success(message, duration = 3000) {\n this.sendNotification(message, 'success', duration);\n }", "function success() {\n form.reset();\n status.classList.add('success');\n status.innerHTML = \"I recieved your message! Will get back to you shortly.\";\n}", "function successMessage(message) {\r\n\t$(\"#successMessageContent\").text(message);\r\n\t$(\"#successMessage\").css(\"display\", \"flex\");\r\n}", "function sendMsg(msg) {\n $('#divResult').addClass(\"alert-danger\")\n $('#result').html(msg)\n $('#divResult').fadeIn(500)\n return false\n}", "function sendMsg(msg) {\n $('#divResult').addClass(\"alert-danger\")\n $('#result').html(msg)\n $('#divResult').fadeIn(500)\n return false\n}", "function failedsent() {\n console.error(\"Invio delle notizie non riuscito!\")\n $(\"#formerr\").fadeIn(750);\n $(\"#infomsg\").text(\"Invio delle notizie non riuscito!\");\n $(\"#formerr\").delay(3000).fadeOut(2000);\n}", "function OnErrorCallMaladie(jqXHR, status) {\n\t\t\tbrief.save();\n\t\t\tnotif(\"warning\", \"Brief sauvegardé avec <strong>succès</strong> !\");\n\n\t\t}", "function returnSuccess(statusCode, Message, context){\n var defaultstatusCode = 201;\n var defaultresponseBody = \"Access Token Created, Email Sent\";\n context.res = { status : (statusCode?statusCode:defaultstatusCode),\n body: (Message?Message:defaultresponseBody)};\n context.done();\n}", "function show_message(res, container){\n if (res.status == 0 ) {\n $(container).addClass('error');\n } else {\n $(container).removeClass('error');\n }\n $(container).show().html(res.message);\n }", "function DialogSuccess(message) {\n\n BootstrapDialog.show({\n type: BootstrapDialog.TYPE_SUCCESS,\n title: \"Exito\",\n message: \"<b>\" + message + \"</b>\",\n buttons: [{\n cssClass: 'btn-success',\n label: 'Cerrar',\n action: function (dialogItself) {\n location.href = $Ctr_help;\n }\n }]\n });\n}", "function addSuccessAlert() {\n $scope.alerts.push({\n type: 'success',\n msg : $filter('translate')('pages.sm.service.SERVICE_MGMT_ALERTS.SERVICE_MGMT_ALERT_SERVICE_ADD_SUCCESSFUL')\n });\n }", "function successCB() {\n //debug\n //alert(\"banco populado\");\n //\n}", "function sucesso(msg) {\n \t$.notify({\n \tmessage: msg\n\n },{\n type: 'success',\n timer: 1000\n });\n}", "function sucesso(msg) {\n \t$.notify({\n \tmessage: msg\n\n },{\n type: 'success',\n timer: 1000\n });\n}", "function ShowMessages(data) {\n if (data.IsSuccess != undefined && data.Message != undefined) {\n if (data.IsSuccess && data.ErrorCode == 'warning') {\n ShowMessage(data.Message, 'warning');\n }\n else if (data.IsSuccess) {\n ShowMessage(data.Message);\n } else {\n ShowMessage(data.Message, \"error\");\n }\n }\n}", "[form.action.success] ({commit}, msg) {\n // triggering form notified\n commit(form.mutation.NOTIFIED, msg, true)\n\n // triggering that form was finished\n commit(form.mutation.FINISHED)\n }", "function showMsg(status, msg) {\n if (status === 1) {\n Swal.fire({\n title: 'Success!',\n icon: 'success',\n text: msg,\n showConfirmButton: false,\n timer: 1500\n });\n } else {\n Swal.fire({\n title: 'Error!',\n text: msg,\n icon: 'error',\n confirmButtonText: 'ok'\n });\n }\n }", "function showMsg(status, msg) {\n if (status === 1) {\n Swal.fire({\n title: 'Success!',\n icon: 'success',\n text: msg,\n showConfirmButton: false,\n timer: 1500\n });\n } else {\n Swal.fire({\n title: 'Error!',\n text: msg,\n icon: 'error',\n confirmButtonText: 'ok'\n });\n }\n }", "function mostrarMensaje($id, $success, $error_msg, $dataTable) {\n\n\n // alert('id = ' + $id + ' success ' + $success + ' error ' + $error_msg)\n // return false\n\n if ($id == '#mensajeError' && $success == 'false' && $error_msg != undefined) {\n\n $($id).addClass(\"alert alert-warning alert-dismissible fade show\");\n\n $($id).html(\n \"<b> \" + $error_msg + \"</b>\" +\n \"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>\" +\n \"<span aria-hidden='true'>&times;</span>\" + \"</button>\"\n\n );\n\n cerrarFadePopup($id, $dataTable)\n\n } else if ($id == '#mensaje' && $success == 'true' && $error_msg != undefined) {\n\n\n // alert('Entro aqui dos')\n // return false\n\n if ($(\"#formModal\").is(\":visible\")) {\n $('#formModal').modal('hide');\n\n $($id).addClass(\"alert alert-success alert-dismissible fade show\");\n\n $($id).html(\n // \"<strong>Info!</strong>\" +\n \"<b> \" + $error_msg + \"</b>\" +\n \"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>\" +\n \"<span aria-hidden='true'>&times;</span>\" + \"</button>\"\n\n );\n\n cerrarFadePopup($id, $dataTable)\n\n } else {\n $($id).addClass(\"alert alert-success alert-dismissible fade show\");\n\n $($id).html(\n // \"<strong>Info!</strong>\" +\n \"<b> \" + $error_msg + \"</b>\" +\n \"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>\" +\n \"<span aria-hidden='true'>&times;</span>\" + \"</button>\"\n\n );\n\n cerrarFadePopup($id, $dataTable)\n\n }\n\n\n\n } else if ($id == '#mensaje' && $success == 'false' && $error_msg != undefined) {\n //validacion cuando se presentan errores pero son manejados por jquery validate en caso de fallar se valida con larval validate\n\n\n var ariaInvalidNotFalse = document.querySelectorAll('input[aria-invalid]:not([aria-invalid=\"false\"])');\n\n\n // alert('DDDDDDDDDDDDDDDD ' + 'error ' + $error_msg + ariaInvalidNotFalse.length);\n // return false\n\n if (ariaInvalidNotFalse.length < 0 || ariaInvalidNotFalse.length == 0) {\n\n // alert('EEEEEEEEEEEEEEEEEEEEEEEEEEEE ' + $id + ' success ' + $success + ' error msg ' + $error_msg);\n // return false\n\n\n $($id).addClass(\"alert alert-warning alert-dismissible fade show\");\n\n $($id).html(\n // \"<strong>Warning!</strong>\" +\n \"<b> \" + $error_msg + \"</b>\" +\n \"<button type='button' class='close' data-dismiss='alert' aria-label='Close'>\" +\n \"<span aria-hidden='true'>&times;</span>\" + \"</button>\"\n\n );\n\n }\n }\n }", "function displaySuccess () {\n $('.validationText').hide();\n $('#wishForm').hide();\n return $(\"#successMsg\").show();\n }", "resultat(message) {\n this.objectif.style.display = \"none\";\n this.success.style.display = \"block\";\n this.success.innerText = message;\n this.snailTop();\n }", "function msgbox(div,error,errormsg){$(div).hide();$(div).html(errormsg);if(error){$(div).addClass(\"alert alert-danger\");}else{$(div).removeClass('alert alert-danger').addClass('alert alert-success');}$(div).fadeIn(\"fast\");}", "hasSuccess () {\n return this.successMessages.length > 0 ||\n this.success\n }", "function mailReturn(data, status){\n\tvar obj = jQuery.parseJSON(data);\n\t\n\talert(\"test\");\n\talert(obj);\n\t\n\t// There was no error\n\tif (obj.error == \"\"){\n\t\t //alert(\"Success : \" + obj.success);\n\t\t $(\"#sendmessage\").addClass(\"show\"); \n\t}\n\t// There was an error\n\telse {\n\t\t //alert(\"Error : \" + obj.error);\n\t\t $(\"#errormessage\").html(\"An unexpected error has occured. Please try again.\");\n\t\t $(\"#errormessage\").removeClass(\"show\");\t \n\t}\n}", "function successMessage(){\n window.alert(\"Success: Deadline Sent to Deadline Dashboard\");\n}", "function AlertSuccess(msg) {\n $(\"#alertSuccess\").css('display', 'block');\n var success = \"<div class='alert alert-success'><button type='button' class='close' data-dismiss='alert'>&times;</button><span>\" + msg + \"</span></div>\";\n $(\"#alertSuccess\").html(success);\n}", "function successCB() {\n alert(\"funca!\");\n \n}", "function successForm(data) {\n\t\t\tvar serverAnswer = $.parseJSON(data);\n\t\t\t$('.callback-form__message').next().text(serverAnswer.result);\n\t\t\tconsole.log(serverAnswer.result);\n\t\t\tif (serverAnswer.result == \"pass\") {\n\t\t\t\t$(\".callback-form__errors\").empty();\n\t\t\t\t$('.callback-form').trigger(\"reset\");\n\t\t\t\t$('.callback-form__button').prop('disabled', false);\n\t\t\t\t$(\".callback-block\").hide(0.607);\n\t\t\t\t$('.сallback-close').hide(0.607);\n\t\t\t\t$(\".callback-status\").show(0.607);\n\t\t\t} else {\n\t\t\t\tvar showError = $('.callback-errors').attr(\"data-errors-server\");\n\t\t\t\t$('.callback-status__message').text(showError);\n\t\t\t\t$(\".callback-block\").hide(0.607);\n\t\t\t\t$(\".callback-status\").show(0.607);\n\t\t\t\tsetTimeout(reloadPage, 5000);\n\t\t\t}\n\t\t}", "function errorDialog(status){\n window.alert(\"Chyba pri naÄŤĂ­tanĂ­ Ăşdajov zo servera.\\nStatus= \"+status);\n}", "function cmdCallMsg(res) {\n if (res.result) {\n printMsgAttendant(res.error.data.text, formatTime(res.error.data.date)) \n } else {\n printMsgInfo(res.error.msg, formatTime(res.error.data.date))\n }\n }", "function ok() {\n controlHasSuccess(element, 1000);\n }", "function popupSuccess(title, mensagem) {\n swal(title, mensagem, 'success');\n}", "function errorDialog(status){\n window.alert(\"Chyba pri načítaní údajov zo servera.\\nStatus= \"+status);\n}", "function addedSuccessfully() {\n noty({\n text: 'Item added successfully',\n type: 'success',\n layout: 'topCenter',\n timeout: 2000\n });\n }", "RespondSuccess(data) {\n if (data.status == true) {\n toastr.success(data.message);\n this.loadThanhVien();\n }\n else {\n setTimeout(function () {\n $('.modal-body > .card-body').append(data.message);\n }, 3000);\n }\n }", "function SendUserSuccess(ws, request, successMessage) {\n ws.send({\n \"type\": \"success\",\n \"data\": {\n \"request\": request,\n \"success-message\": successMessage\n }\n });\n}", "function callAjaxControllerRegisterSuccess(msg) {\n var response = JSON.parse(msg);\n // If there is error\n if (response.msg != 'Success') {\n alert(\"Registration Failed!\");\n // If everything are OK\n } else {\n opts.stop = false;\n animateCloseWindow('register', false, true);\n if (response.msg == 'Success') {\n setTimeout(\n animateShowWindow('confirmmsg'),\n 3000);\n } else {\n // Redirect\n if (opts.redirection == '1') {\n window.location = opts.profileUrl;\n sessionStorage.setItem(\"user\", response.userId);\n } else {\n window.location.reload();\n sessionStorage.setItem(\"user\", response.userId);\n }\n }\n }\n animateLoader('register', 'stop');\n opts.stop = false;\n }", "function showManageAgentSuccessAlert() {\n\t\t \tvar successMsg = $(\"#myModal\").attr(\"saveAgentWithSuccess\");\n\t\t \t\n\t\t \tif (successMsg !== undefined) {\n\t\t \t\tdisplaySuccessMsg(successMsg);\n\t\t \t}\n\t\t }", "function fallo() {\n return error(\"Reportar fallo\");\n}", "hasSuccess() {\n return this.internalSuccessMessages.length > 0 || this.success;\n }", "hasSuccess() {\n return this.internalSuccessMessages.length > 0 || this.success;\n }", "hasSuccess() {\n return this.internalSuccessMessages.length > 0 || this.success;\n }" ]
[ "0.7595283", "0.7076018", "0.7046274", "0.7010905", "0.69970345", "0.6987952", "0.6926352", "0.6926352", "0.6926352", "0.6926352", "0.6926352", "0.6926352", "0.6926352", "0.6926352", "0.6908995", "0.6897187", "0.674808", "0.6707035", "0.6694319", "0.66782093", "0.66721964", "0.6646384", "0.6627239", "0.6582508", "0.65467745", "0.6534529", "0.65341294", "0.6530068", "0.65093935", "0.64948565", "0.64944774", "0.64768696", "0.64701605", "0.64641076", "0.64630294", "0.6460841", "0.6457453", "0.6433165", "0.6433165", "0.6433165", "0.6426953", "0.64268935", "0.6414831", "0.6401098", "0.6394762", "0.63930005", "0.63817346", "0.6371588", "0.6363877", "0.6354847", "0.63508874", "0.6350272", "0.63492376", "0.6346836", "0.6342209", "0.6314675", "0.6313739", "0.6267443", "0.6263709", "0.6261146", "0.6252962", "0.6252061", "0.6251818", "0.6251818", "0.62439036", "0.6236402", "0.62361145", "0.6210483", "0.6201277", "0.6194654", "0.61925006", "0.61879", "0.61879", "0.61857355", "0.6172163", "0.61545265", "0.61545265", "0.615214", "0.6151892", "0.6149515", "0.6128953", "0.612826", "0.61258304", "0.61244535", "0.61236554", "0.6122769", "0.61224204", "0.6119177", "0.6119051", "0.6113711", "0.6105554", "0.6101719", "0.60979176", "0.6088425", "0.60861063", "0.608238", "0.6081543", "0.6074408", "0.60661066", "0.60661066", "0.60661066" ]
0.0
-1
function to get the selected id from table
function getSelectedNetMdId(pgTableName) { var netmdId=""; if($j(pgTableName).dataTable().fnGetData().length>0) { var selNetMd = $j(pgTableName + ' tbody tr[selected]'); if(selNetMd.length==0){ updateTipsNew("select atleast one netmd",$j('#errorDivData'),$j('#errorDivHeader')); } else if(selNetMd.length>1) updateTipsNew("select only one netmd",$j('#errorDivData'),$j('#errorDivHeader')); else netmdId=selNetMd.attr('id'); } return netmdId; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function get_id_selection () {\n return $.map($table.bootstrapTable('getSelections'), function (row) {\n return row.id;\n })\n}", "selectId() {\n return this.id ? this.id : this._uid; // eslint-disable-line no-underscore-dangle\n }", "selectFriend (rowId) {\n\n }", "function fnGetSelected( oTableLocal ){\n\treturn oTableLocal.$('tr.row_selected');\n}", "function getItemCurrent(row){\n let idCurrent=document.getElementById(\"table\").rows[row].cells[0].getElementsByTagName('INPUT')[0].value;\n return idCurrent;\n}", "function fnGetSelected( oTableLocal )\n{\n return oTableLocal.$('tr.row_selected');\n}", "function fnGetSelected( oTableLocal )\r\n\t{\r\n\t\treturn oTableLocal.$('tr.row_selected');\r\n\t}", "function chosenID(parm){\n connection.query(\"SELECT * FROM products WHERE ID=?\",[parm],function(err,res){\n if(err) {\n throw error;\n }else if(res[0]){\n \n console.log(\n \"You select:\\n\"+\n res[0].ID + \n \" | \" + res[0].product_name + \n \" | \" + res[0].price + \n \" | \" + res[0].department_name +\n \" | \" + res[0].stock_quantity ); \n \n }else{\n console.log(\"We could not find the ID you've Chosen. Try again.\");\n connection.end();\n } \n });\n \n }", "function findSelectedAssessId() {\n\n if (selectedAssessment!=null){\n return $(selectedAssessment).attr(\"id\");\n }\n return null;\n}", "function getId(ele){\t// store the id value\r\n id_value = ele.id; \r\n}", "function getSelectPrimaryKey(){\n let selectPrimaryKey = document.getElementById('primary-key')\n return selectPrimaryKey.options[selectPrimaryKey.selectedIndex].value.toLowerCase()\n}", "function getIDStudent(){\n\t//Obtenim el ID de la part superior.\n\treturn $(\"#alumnes\").val();\n}", "function getSelectedNetmdBranchId(pgTableName) {\r\n\t\tvar branchId=\"\";\r\n\t\tif($j(pgTableName).dataTable().fnGetData().length>0) {\r\n\t\t\tvar selBranch = $j(pgTableName + ' tbody tr[selected]');\r\n\t\t\tif(selBranch.length==0){\t\r\n\t\t\t\tupdateTipsNew(\"Select atleast one branch\",$j('#errorDivData'),$j('#errorDivHeader'));\r\n\t\t\t} else if(selBranch.length>1) \r\n\t\t\t\tupdateTipsNew(\"Select only one branch\",$j('#errorDivData'),$j('#errorDivHeader'));\r\n\t\t\telse\r\n\t\t\t\tbranchId=selBranch.attr('id');\r\n\t\t}\t\t\r\n\t\treturn branchId;\r\n\t}", "function getSelectedID() {\r\n return $(\"#assignment-id-\" + userSession.selectedAssignment).text();\r\n}", "function getSelectedRowId(mode) {\n var aSelectedTableRowIds;\n if (window.emxEditableTable.isRichTextEditor) {\n aSelectedTableRowIds = getSelectedTableRowIds();\n\n } else {\n var aRowsSelected = emxUICore.selectNodes(oXML.documentElement,\n \"/mxRoot/rows//r[@checked='checked']\");\n aSelectedTableRowIds = getCheckboxArray(aRowsSelected, mode);\n }\n if (aSelectedTableRowIds.length > 1 && mode == \"Mark\") {\n alert(SBPleaseSelectOneItemOnlyText);\n return;\n }\n return aSelectedTableRowIds;\n}", "function getItemId() {\r\n var item_id = 0;\r\n var element = document.getElementById('Table6');\r\n try {\r\n a_tag = element.getElementsByTagName('a');\r\n slug = a_tag[0].href.split('?');\r\n item_id = slug[1].match(/[0-9]*[\\.]?[0-9]+/g);\r\n } catch (e) {\r\n alert('Không lấy được id sản phẩm. ' + e);\r\n }\r\n return item_id;\r\n }", "function selectRecord(target, idValue){\r\n\t\tvar opts = $.data(target, 'datagrid').options;\r\n\t\tvar data = $.data(target, 'datagrid').data;\r\n\t\tif (opts.idField){\r\n\t\t\tvar index = -1;\r\n\t\t\tfor(var i=0; i<data.rows.length; i++){\r\n\t\t\t\tif (data.rows[i][opts.idField] == idValue){\r\n\t\t\t\t\tindex = i;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (index >= 0){\r\n\t\t\t\tselectRow(target, index);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "function getSelectedID(select2_) {\n var select2 = _getSelect2(select2_);\n var values = select2.val();\n if (values) {\n if (typeof values === \"string\")\n return values;\n return values[0];\n }\n return null;\n }", "function getSelectedIndex(id) {\n for (var i = 0; i < $scope.listProducts.length; i++) {\n if ($scope.listProducts[i].id == id) {\n return i;\n }\n }\n return -1;\n }", "function datagrid_get_selected_row(table) {\n\tvar rows = table.fnGetNodes();\n\tfor (var i = 0; i < rows.length; i++) {\n\t\tvar row = rows[i];\n\t\tif (row && $(row).hasClass('datagrid_row_selected'))\n\t\t\treturn row;\n\t}\n\treturn null;\n}", "function fnGetSelected(oTableLocal)\n {\n return oTableLocal.$('tr.selected');\n }", "function getModelId()\n{\n\t var id = null;\n var inp = document.getElementsByName('modelId');\n var rw = -1;\n var r = -1;\n var sign = 1;\n for (var i = 0; i < inp.length; i++) {\n \tr++;\n if (inp[i].type == \"radio\" && inp[i].checked) {\n \trw = r + 1;\n \tbreak;\n }\n }\n if (rw >= 0) {\n \tvar table = document.getElementById(\"models\");\n \tvar row = table.rows[rw];\n \tif (row.style.color === 'lightgray') {\n sign = - 1;\n\t\t}\n var cell = row.cells[1];\n id = cell.innerHTML * sign;\n }\n return id;\n}", "function fnGetSelected(oTableLocal) {\r\n\treturn oTableLocal.$('tr.selected');\r\n}", "function selectID(belly) {\r\n return belly.id == \"940\";\r\n }", "function getSelectedTermId() {\n\t\t\t\n\t\t\tif (!vm.selectedTerm || !vm.selectedTerm.primaryid) {\n\t\t\t\t// no term selected\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\t\n\t\t\tvar stage = vm.selectedStage;\n\t\t\tvar termId = vm.selectedTerm.primaryid;\n\t\t\t\n\t\t\tif (stage == 0) {\n\t\t\t\ttermId = getEmapaId(termId);\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttermId = getEmapsId(termId, stage);\n\t\t\t}\n\t\t\t\n\t\t\treturn termId;\n\t\t\t\n\t\t}", "function printSelectedFilesId() {\n console.log(\"Selected Files Id:\" + rows_selected);\n}", "function selectID(belly) {\r\n return belly.id == userSelection;\r\n }", "function getSelected() {\n\t\t\t\treturn angular.element(document.getElementById(scope.selected.id));\n\t\t\t}", "static get idColumn() {\n return 'id';\n }", "function fnc_Get_DataTable_RowData_Selected(ic_grid) {\n\tvar table = $('#' + ic_grid).DataTable();\n\tvar rows = table.rows('.selected').indexes();\n\tvar data = table.row(rows).data();\n\treturn data;\n}", "function getSelectedRow(){\r\n\t\r\n\t// find selected tr in the table and map it to the variable\r\n\tvar currentRow = $('#TableHead').find('tr.highlight').first().children(\"td\").map(function() {\r\n\t\treturn $(this).text();\r\n\t}).get();\r\n\t\r\n\treturn currentRow;\r\n}", "function current_selection() {\n return window.current_row_index;\n}", "getId (){\r\n return this.id;\r\n }", "function getSelection(){\n return selection;\n }", "function getID(id){\r\n return document.getElementById(id).value;\r\n}", "function _fnGetRowIDFromAttribute(row) {\n return row.attr(\"id\");\n }", "getRowSelectStatus() {\n if(this.state.isClicked) {\n return this.state.rowId;\n } else {\n return 0;\n }\n }", "function grabEBI(id){ return tf_Id(id); }", "function selectedIndex(x) {\n return x==selectedID;\n }", "function get_check_row(row, data){\n var selected = $('#table_selected').val();\n $.each(data,function(index, value){\n if (value.items_id == row) {\n selected = selected+','+index\n }\n })\n $('#table_selected').val(selected);\n // console.log(selected);\n}", "function getSavedTaskID(row)\n{\n const nameBox = getNameBox(row);\n const taskIDSpan = $(nameBox.children().filter(\".taskid\")[0]);\n const taskID = $(taskIDSpan.children()[0]).val();\n return taskID;\n}", "function fnSetSelectedIDInput(dataTable, td, event, column_id, input_id) {\n\t\n\tif (!$(td).hasClass('dataTables_empty')) {\n\t\tvar selected = !$(event.target.parentNode).hasClass('row_selected');\n\t\t\n\t\t$(dataTable.fnSettings().aoData).each(function (){\n\t\t\t$(this.nTr).removeClass('row_selected');\n\t\t});\n\n\t\tif (selected) {\n\t\t\t// Get the position of the current data from the node\n\t\t\tvar aPos = dataTable.fnGetPosition( td.parentNode );\n\t\t\t// Get the data array for this row\n\t\t\tvar aData = dataTable.fnGetData( aPos[0] );\n\t\t\t// Put ID into input hidden\n\t\t\t$('#'+input_id).attr('value', aData[column_id]);\n\n\t\t\t$(event.target.parentNode).addClass('row_selected');\n\t\t}\n\t\telse $('#'+input_id).attr('value', '');\n\t}\n}", "function selectId (context) {\n if (selected == 0) {\n firstID = $(context).children(\"img\").attr(\"id\");\n $(context).addClass(\"inactive\"); // Make sure same card can't be select again\n } else if (selected == 1) {\n secondId = $(context).children(\"img\").attr(\"id\");\n $(\"td\").addClass(\"inactive\");\n }\n\n selected = $(\".show\").length;\n\n if (selected > 1) {\n checkId(firstID, secondId);\n selected = 0;\n }\n }", "function ambilId(id) {\n dbprom.then((db) => {\n let tx = db.transaction('produk'); //buat obj transaksi\n let dbStore = tx.objectStore('produk'); //pilih table\n let index = dbStore.index('id'); //pilih index\n return index.get(id); //cari berdasarkan index\n }).then((data) => {\n $('#eNama').val(data.nama); //masukan hasil pencarian ke tampilan form nama\n $('#eHarga').val(data.harga); //masukan hasil pencarian ke tampilan form harga\n $('#eStok').val(data.stok);\n $('#eDeskripsi').val(data.deskripsi);\n $('#eId').val(data.id); //!! eId diset dengan suatu nilai id yang akan diubah\n $('#modForm').modal('show'); //tampilkan modal\n }).catch((err) => {\n console.log('error ' + err);\n });\n}", "function getTableID()\n{\n _href = document.location.href ? document.location.href : document.location;\n\n var suffix = _href.split('?');\n var args = suffix[suffix.length-1].split('&');\n var tID = args[0].split('=');\n\n return tID[1];\n}", "function rowLookup() {\n console.log(this);\n $(\"#lookup-user_id\").val($(this).attr(\"id\").substring(3));\n getInformation();\n }", "function getRowsTable(row)\n{\n return row.parent().attr(\"id\");\n}", "handleRowClick(event) {\n\t\tthis.selectedRecordId = event.detail.pk;\n\t}", "getRowId(){\n\t\treturn 'speclist_'+this.spec_id;\n\t}", "handleRowSelect(row){\n console.log(row);\n }", "selectRow(e) {\n const { selectRow } = this.props;\n selectRow(e.target.dataset.id);\n }", "function getItemId() {\r\n var item_id = 0;\r\n try {\r\n item_id = document.getElementById('idNO').value;\r\n } catch (e) {\r\n alert('Không lấy được id sản phẩm. ' + e);\r\n }\r\n return item_id;\r\n }", "function getId(cell) {\r\n\t\treturn parseInt(cell.attr('id'), 10);\r\n\t}", "getId()\n\t{\n\t\treturn this.id;\n\t}", "getId()\n\t{\n\t\treturn this.id;\n\t}", "function listSelect(){\r\n\t\r\n\tvar count_rdl=document.frmlist.rdl.length;\t\r\n\tvar id=-1;\r\n\tif(typeof count_rdl == \"undefined\"){\r\n\t if(document.frmlist.rdl.checked)\r\n\t\t\tid=document.frmlist.rdl.value;\r\n\t}\r\n\telse\r\n\tfor(var i=0;i<count_rdl;i++)\r\n\t\tif(document.frmlist.rdl[i].checked)\r\n\t\t{\t\r\n\t\t\tid=document.frmlist.rdl[i].value;\t\t\r\n\t\t\tbreak;\r\n\t\t}\t\t\t\t\t\r\n\treturn id;\r\n}", "function getItemId()\r\n {\r\n var element =document.getElementsByName(\"goods_id\");\r\n element=element[0];\r\n var item_id=0;\r\n item_id = element.value;\r\n return item_id;\r\n }", "function item_id(tv) {\n var item_id = tv.id;\n return item_id;\n }", "get selectedRowIds() {\n const rowIds = this.selectedCheckboxes.map((checkbox) => {\n const checkboxId = checkbox.id.toString();\n const idArr = checkboxId.split('-');\n const rowIdIndex = 1;\n return idArr[rowIdIndex];\n });\n return rowIds;\n }", "function defaultSelectId(entity) {\n return entity == null ? undefined : entity.id;\n}", "function selectRecord(target, idValue, state) {\n if (!state) state = $.data(target, 'datagrid');\n var opts = state.options;\n if (opts.idField) {\n var index = getRowIndex(target, idValue, state);\n if (index >= 0) {\n selectRow(target, index, undefined, state);\n }\n }\n }", "static async getId(username){\n const res = await db.query(\n 'SELECT id FROM users WHERE username=$1',[username]\n );\n console.log('getting userid',res.rows[0].id);\n return res.rows[0].id;\n }", "function getRowID(idx){\n return 'row' + idx;\n}", "function get_selection()\n {\n return selection;\n }", "getId() {\n \n return this.id; \n }", "function whichRow(id) {\n var matches = id.match(/\\d+$/);\n if (matches==null || matches.length != 1) return 0;\n return matches[0];\n}", "function getItemId() {\r\n var item_id = \"\";\r\n try {\r\n item_id = content_data.getElementsByTagName('tr')[0].getElementsByTagName('td')[0].getElementsByTagName('font')[1].innerHTML;\r\n } catch (e) {\r\n alert('Can not get item id. ' + e);\r\n }\r\n return item_id.replace(/\\s/g, '');\r\n }", "select(id) { this._updateActiveId(id, false); }", "getId() {\n\t\treturn this.id;\n\t}", "static getId() {\n // get id of last inserted article\n this.command = \"SELECT id FROM articles ORDER BY id DESC LIMIT 1;\";\n db.get(this.command, (error, value) => {\n if (error) {\n response.send(`Error: ${error.message}`);\n } else {\n return checkLastId(value);\n }\n });\n }", "id() {\n const model = internal(this).model;\n return internal(model).entities.id(this);\n }", "checkId(id1, id2) {\n if (this.getCurTab() === \"dbms\")\n return DOC.iSel(id1);\n else\n return DOC.iSel(id2);\n }", "function getSelectedRecords(smtTableId){\r\n\tsmtTable = document.getElementById(smtTableId);\r\n\ttrs = smtTable.getElementsByTagName('tbody')[0].trs2;\r\n\tvar res = '';\r\n\tif(trs!=null){\r\n\t\tfor(var i = 0, k = 0; i<trs.length; i++){\r\n\t\t\tif(trs[i].className=='smartTablSeselected'){\r\n\t\t\t\tif(trs[i].getAttribute('smtId')!=null){\r\n\t\t\t\t\tif(k!=0){\r\n\t\t\t\t\t\tres = res+',';\r\n\t\t\t\t\t}\r\n\t\t\t\t\tres = res + trs[i].getAttribute('smtId');\r\n\t\t\t\t\tk++;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn res;\r\n}", "function getItemId() {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "getSeletedRecord(recordId) {\n let selectedRecord = null;\n this.searchList.forEach((record) => {\n if (record.Id === recordId) {\n selectedRecord = record;\n }\n });\n return selectedRecord;\n }", "function selectList(op){\n listSelected = op.getAttribute(\"id\");\n}", "function get_id() {\n\treturn $('.user-link').attr('id');\n}", "function getListIdForActiveTaskList() {\n\tvar activeTaskNode = document.querySelector(\".selected\");\n if (!activeTaskNode) {\n\t\t\tactiveTaskNode = appUIController.getUIVars().allListsElem;\n\t}\n\treturn activeTaskNode.getAttribute('data-id');\n}", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Product_main1_Product_top11_Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getId(el){\n var id = el.getAttribute('adf-id');\n return id ? id : '-1';\n }", "selectOneQuery() {\n return `select * from ${this.tablename('selectOne')} where id = $1`;\n }", "getId() {\n return this._executeAfterInitialWait(() => this.currently.getAttribute('id'));\n }", "function _handleSelect(id) {\n selected(id);\n }", "function callToEdit()\n{\n\tvar id = $(this).parents('tr').children('td').children('p.editId').attr('editId');\n\t//var id = $(this).children('td:eq(0)').children('p.editId').attr('editId');\n\twindow.location.href = \"media/editmedia/id/\" + id;\n}", "function _id(val) {\n return document.getElementById(val);\n}", "function findId(object) {\n return object.id\n }", "function update_entity_selection_id(id) {\n current_id = id;\n\n //setup the selected record\n var existing_record;\n if(current_id != undefined) {\n existing_record = Controller.get_record(current_id);\n Forms.set_scope_can_record(existing_record);\n }\n\n //only update the display, don't reinit the form\n update_edit_form_display();\n\n}", "function getnextid(tablename){\n\tvar next_id =0;\n\t$.ajaxSetup({async:false});\n$.post(\"php/db_query_fun.php\",{param:'3~'+tablename},function(server_response) {\n\t\tnext_id =parseInt(server_response);\n});\t\nreturn next_id;\n}", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getItemId()\r\n {\r\n var element =document.getElementById(\"Label12\");\r\n var item_id=0;\r\n item_id = element.textContent;\r\n return item_id;\r\n }", "function getFirstCheckedId(tblName)\n\t{\n\t\tfor (var i=1; i<tblName.rows.length; i++)\n\t\t{\n\t\t\tif (tblName.rows(i).cells(0).firstChild.checked) return tblName.rows(i).cells(0).firstChild.name;\n\t\t}\n\t\treturn null;\n\t}" ]
[ "0.77054846", "0.6874063", "0.678539", "0.668275", "0.6632723", "0.66003734", "0.65655893", "0.65271795", "0.6497005", "0.64847237", "0.64712465", "0.64539504", "0.6421429", "0.6364018", "0.63632745", "0.6358161", "0.63525355", "0.63245887", "0.63199544", "0.63189983", "0.63093275", "0.62425244", "0.6230182", "0.62262887", "0.6208818", "0.6207954", "0.6187534", "0.61776423", "0.6171709", "0.6132493", "0.6118535", "0.6115323", "0.6095988", "0.6087245", "0.60867834", "0.60758245", "0.60577714", "0.6041127", "0.60266155", "0.6022849", "0.60174", "0.6001939", "0.59967446", "0.5992144", "0.5977649", "0.5971535", "0.59675777", "0.5957447", "0.5950069", "0.59366655", "0.59345055", "0.59290165", "0.59247077", "0.5915873", "0.5915873", "0.5914359", "0.591077", "0.5884796", "0.5882328", "0.5868856", "0.58657795", "0.58500254", "0.58482134", "0.5845403", "0.58093137", "0.57971585", "0.57800037", "0.57714546", "0.57670826", "0.57649624", "0.5749892", "0.5731271", "0.573114", "0.57280624", "0.57232493", "0.5720521", "0.5709902", "0.57030725", "0.5696944", "0.5696944", "0.5696944", "0.5696944", "0.5696944", "0.56964755", "0.5695767", "0.5692135", "0.5691935", "0.5691377", "0.56900257", "0.56799084", "0.56783396", "0.56742", "0.5673726", "0.5673726", "0.5673726", "0.5673726", "0.5673726", "0.5673726", "0.5673726", "0.56716317" ]
0.69430244
1
This is for http interceptor
function httpServiceFactory(backend, options) { return new __WEBPACK_IMPORTED_MODULE_11__providers_http_service_service__["a" /* HttpService */](backend, options); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function interceptor($q) {\n return {\n 'request': function(config) {\n // do something on success\n console.log(\"Intercepter, request \", config.url);\n var url = config.url.toString();\n console.log(url);\n\n if (url.indexOf(\"special-api\") > -1) {\n console.log(\"injecting special header\");\n \n config.headers[\"X-Special-Token\"] = \"SPECIAL-1234\";\n }\n\n\n return config;\n },\n\n // optional method\n 'requestError': function(rejection) {\n // do something on error\n console.log(\"Intercepter, request requestError \");\n return $q.reject(rejection);\n },\n\n // optional method\n 'response': function(response) {\n // do something on success\n console.log(\"Intercepter, response \", response.status);\n if (response.config.url.indexOf(\"special-api\") > -1) {\n response.data.message = 'Special Processing Done';\n }\n \n return response;\n },\n\n // optional method\n 'responseError': function(rejection) {\n // do something on error\n\n //Samples only, examples at Authentication and Authorization\n if (rejection.status === 403) {\n console.log(\"Invalid request, not authorized\");\n rejection.data.message = 'special processing failed';\n $q.reject(rejection);\n //$location.url('/user/signin');\n }\n \n \n console.log(\"Intercepter, responseError \");\n return $q.reject(rejection);\n }\n };\n }", "intercept(req, next) {\n if (req.method === 'JSONP') {\n return this.jsonp.handle(req);\n }\n // Fall through for normal HTTP requests.\n return next.handle(req);\n }", "intercept(req, next) {\n if (req.method === 'JSONP') {\n return this.jsonp.handle(req);\n }\n // Fall through for normal HTTP requests.\n return next.handle(req);\n }", "intercept(req, next) {\n if (req.method === 'JSONP') {\n return this.jsonp.handle(req);\n }\n // Fall through for normal HTTP requests.\n return next.handle(req);\n }", "intercept(req, next) {\n if (req.method === 'JSONP') {\n return this.jsonp.handle(req);\n }\n // Fall through for normal HTTP requests.\n return next.handle(req);\n }", "intercept(req, next) {\n if (req.method === 'JSONP') {\n return this.jsonp.handle(req);\n }\n // Fall through for normal HTTP requests.\n return next.handle(req);\n }", "intercept(req, next) {\n if (this.loggedIn) {\n this.logger.log(\"loggedin into interceptor\", \"\");\n return this.auth.getTokenSilently$().pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_1__[\"mergeMap\"])(token => {\n const tokenReq = req.clone({\n setHeaders: { Authorization: `Bearer ${token}` }\n });\n return next.handle(tokenReq);\n }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_1__[\"catchError\"])(err => {\n this.logger.error(\"injector error\", \"\");\n return Object(rxjs__WEBPACK_IMPORTED_MODULE_0__[\"throwError\"])(err);\n }));\n }\n else {\n this.logger.log(\"not loggedin into interceptor\", \"\");\n return next.handle(req);\n }\n }", "constructor(props){\n super(props); \n this.reqInterceptor = axios.interceptors.request.use(req => {\n // clear null state before request sent \n this.setState({error: null});\n return req; \n });\n\n // interceptors intercept the requests or response before they are handled by then and catch\n // first param is to do something with the response data, which we do not want to do here so we instantly return it \n this.respInterceptor = axios.interceptors.response.use(res => res, error => {\n this.setState({error: error}); \n });\n }", "componentWillMount(){\n this.reqInterceptor= axios.interceptors.request.use(req=>{\n // console.log(req);\n this.setState({error:null});\n return req;\n })\n\n this.resInterceptor =axios.interceptors.response.use(res =>res,error=>{\n this.setState({error:error});\n })\n }", "intercept(request, next) {\n return next.handle(request).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"tap\"])((event) => {\n if (event instanceof _angular_common_http__WEBPACK_IMPORTED_MODULE_1__[\"HttpResponse\"]) {\n /* const errMsg = event.body.error;\n if (errMsg) {\n if (errMsg === 'You should login first!') {\n // debugger;\n this.authService.destroy_session();\n this.router.navigate(['/auth/login']);\n this.utilService.showErrorToast('You need to login first !');\n // this.messageService.displayToast(errMsg);\n } else if (errMsg === 'Access token is incorrect !!') {\n // dismiss\n } else {\n // this.messageService.displayToast(errMsg);\n }\n }*/\n }\n }, (err) => {\n if (err.status === 401) {\n this.authService.destroy_session();\n this.router.navigate(['/auth/login']).then();\n this.utilService.showErrorToast('You need to login first !');\n }\n else if (err.status === 500) {\n // this.messageService.displayToast(err.error.msg);\n }\n }));\n }", "constructor(props) {\n super(props);\n this.reqInterceptor = axios.interceptors.request.use(request => {\n this.setState({error: null});\n return request;\n })\n this.resInterceptor = axios.interceptors.response.use(res => res, error => { //res => res returns the res\n this.setState({error: error});\n })\n }", "componentWillMount() {\n this.reqInterceptor = axios.interceptors.request.use(req => {\n this.setState({ error: null });\n return req;\n });\n this.resInterceptor = axios.interceptors.response.use(res => res, error => {\n this.setState({ error: error });\n });\n }", "function timeStampInterceptor() {\r\n\t var factory = {\r\n\t\t request : function(config){\r\n\t\t\t var url = config.url;\r\n\t\t\t if (url.indexOf('view') > -1) return config;\r\n\t\t\t var timeStamp = new Date().getTime();\r\n\t\t\t config.url = url + \"?timestamp=\" + timeStamp;\r\n\t\t\t console.log(config.url);\r\n\t\t\t return config;\r\n\t\t }\r\n\t }\r\n\r\n\t return factory;\r\n }", "function NetworkResponseInterceptor() {\n this._originalAjax = $.ajax;\n this._successInterceptors = [];\n this._errorInterceptors = [];\n this._urlPatterns = [];\n}", "function NetworkResponseInterceptor () {\n this._originalAjax = $.ajax;\n this._successInterceptors = [];\n this._errorInterceptors = [];\n this._urlPatterns = [];\n}", "function myHttpInterceptor($q, $rootScope) {\n var loadingCount = 0;\n return {\n request: function (config) {\n if(++loadingCount === 1) $rootScope.$broadcast('loading:progress');\n return config || $q.when(config);\n },\n\n response: function (response) {\n if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');\n return response || $q.when(response);\n },\n\n responseError: function (response) {\n if(--loadingCount === 0) $rootScope.$broadcast('loading:finish');\n return $q.reject(response);\n }\n };\n\n }", "componentWillMount(){\n this.reqInterceptor = axios.interceptors.request.use(req =>{\n this.setState({error: null});\n return req;\n })\n this.resInterceptor = axios.interceptors.response.use(res => res, error =>{\n this.setState({error:error});\n });\n }", "function httpMethodInterceptor() {\n return {\n request: function (config) {\n if (config.url.indexOf('cmsapi/newsletters/') >= 0) {\n return config;\n }\n\n if (config.method === 'POST') {\n config.url += '/Post';\n }\n\n if (config.method === 'PUT') {\n config.method = 'POST';\n config.url += '/Put';\n }\n\n if (config.method === 'DELETE') {\n config.method = 'POST';\n config.url += '/Delete';\n }\n\n return config;\n }\n };\n }", "function LoadingHttpInterceptor($rootScope, $q) {\n\n //21. se incremente y decrementa el contador loadingCount y lo usamos porque estas\n // solicitudes son asincrónicas es totalmente posible y de hecho ocurre todo el\n // tiempo cuando algunas solicitudes ocurrieron al mismo tiempo.\n // Entonces, por ejemplo, el servicio HTTP puede cargar algunas plantillas al\n // mismo tiempo y haciendo algunas solicitudes al mismo tiempo.\n // No querríamos apagarlo completamente cuando volviera la primera solicitud\n // mientras que la segunda solicitud aún está pendiente.\n // Lo que significa que necesitamos un contador, un contador de incremento cada\n // vez que hay un nueva solicitud y un contador de decrementos cada vez que vuelve\n // una de las solicitudes. Entonces, mientras tengamos solicitudes pendientes,\n // este indicador de carga seguirá funcionando y no lanzaremos otro evento con la\n // propiedad on igual a false. SE va a esperar hasta que reduzcamos el contador\n // hasta el punto donde no hay nada de carga en absoluto, entonces es un 0.\n // Y luego, transmitiremos que puedes seguir y apagar.\n var loadingCount = 0;\n\n var loadingEventName = 'spinner:activate';\n\n//21. el return de esta fn tiene una declaracion object literal\n// y tiene 3 propiedades: request, response y responseError\n return {\n // request propiety es una fn q tiene como arg config object\n // y este obj es todo lo que se necesita para $http service\n // haga el request xq ej. the url, the header request, etc\n // Entonces cuando http service hace un request, viene por esta\n //propiedad primero antes de hacer el request\n request: function (config) {\n // console.log(\"Inside interceptor, config: \", config);\n\n if (++loadingCount === 1) {\n // se engancha el proceso de transmitir (broadcast) al $rootScope\n // cambiando el estado del evento loadingEventName = 'spinner:activate\n // con el valor de on = a true. Se enciente o lanza el spinner\n $rootScope.$broadcast(loadingEventName, {on: true});\n }\n\n return config;\n },\n\n response: function (response) {\n if (--loadingCount === 0) {\n // y cuando la respuesta esté de vuelta,, nosotros podemos again\n // transmitir o broadcas usando $rootScope cambiamos a false la\n //propiedad on, entonces apagamos el spinner\n $rootScope.$broadcast(loadingEventName, {on: false});\n }\n\n return response;\n },\n\n responseError: function (response) {\n if (--loadingCount === 0) {\n // si hay algun error en la respuesta igual se apaga el spinner\n $rootScope.$broadcast(loadingEventName, {on: false});\n }\n// se hace un reject del promise si no se hace hace se retorna responseError\n// siempre como un exitoso.. que no siempre es el caso\n\n// ¿Qué pasaría si omitiéramos la siguiente línea de código en la función\n// 'responseError' del interceptor?\n// La llamada volverá a la persona que llama y se verá como nuestra promesa\n// \"resuelta\" cuando sea cierto, la promesa falló. El código de la persona que\n// llama tratará el objeto de respuesta como si fuera el resultado esperado,\n// lo que probablemente cause errores.\n\n return $q.reject(response);\n }\n };\n}", "intercept(): * {\n return {}\n }", "function VMInterceptor() {\r\n}", "function RequestIntercepterAccept($injector) {\n\t\t\n\t\t//setup and return service \t\n var intercepter = {\n \trequest \t: request,\n };\n \n return intercepter;\n\n ////////////\n \n //request function\n \n /**\n\t\t * request\n\t\t * \n\t\t * Intercepts a request and sets the request attribute \n\t *\n\t\t * @param \t{Object} config The requests config object \n\t\t * \n\t\t * @return {Object} The edited config object\n\t\t * \n\t\t**/\n function request(config){\n\n \t\n \t$injector.invoke(['DrupalApiConstant', 'FileResourceConstant', function (DrupalApiConstant, FileResourceConstant) {\n \t \t\t\n \t\tconfig.headers['Accept'] = DrupalApiConstant.responseFormat;\n \t\t\n \t\tif(!(config.method == 'POST' && config.url == DrupalApiConstant.drupal_instance + DrupalApiConstant.api_endpoint + FileResourceConstant.resourcePath)) {\n \t \tconfig.headers['Content-Type'] = DrupalApiConstant.responseFormat;\n \t\t}\n \t\t\n\t \t\n \t \t\n \t }]);\n\n\t\t\treturn config;\n };\n \t\n\t}", "intercept(initialRequest, next) {\n return this.injector.runInContext(() => jsonpInterceptorFn(initialRequest, downstreamRequest => next.handle(downstreamRequest)));\n }", "intercept(initialRequest, next) {\n return this.injector.runInContext(() => jsonpInterceptorFn(initialRequest, downstreamRequest => next.handle(downstreamRequest)));\n }", "function eventGatewayInterceptor($httpProvider) {\n $httpProvider.interceptors.push(['$q', '$injector', function ($q, $injector) {\n var config = $injector.get('config');\n var $location = $injector.get('$location');\n\n var queryPairs = $location.search(),\n ajaxAnalyticsEnabled = config.getBool(config.eventgatewayV4.logServiceCalls),\n ajaxAnalyticsEnabledErrorsOnly = config.getBool(config.eventgatewayV4.logServiceCallErrorsOnly);\n\n // Override reporting level by query param egErrorReportingLevel\n switch (queryPairs.egErrorReportingLevel) {\n case 'all':\n ajaxAnalyticsEnabled = true;\n ajaxAnalyticsEnabledErrorsOnly = false;\n break;\n case 'errors':\n ajaxAnalyticsEnabled = true;\n ajaxAnalyticsEnabledErrorsOnly = true;\n break;\n case 'none':\n ajaxAnalyticsEnabled = false;\n break;\n }\n\n return {\n request: function request(config) {\n var eventGatewayService = $injector.get('eventGatewayService');\n if (ajaxAnalyticsEnabled && config && config.url.indexOf('http') === 0) {\n config.startTime = new Date().getTime();\n eventGatewayService.setServiceCallStartTime();\n }\n return config;\n },\n responseError: function responseError(response) {\n if (ajaxAnalyticsEnabled && response && response.config && response.config.url.indexOf('http') === 0) {\n remoteCallReturned(true, response);\n }\n\n return $q.reject(response);\n },\n response: function response(_response) {\n if (ajaxAnalyticsEnabled && !ajaxAnalyticsEnabledErrorsOnly && _response.config.url.indexOf('http') === 0) {\n remoteCallReturned(false, _response);\n }\n return _response;\n }\n };\n\n function remoteCallReturned(err, config) {\n var eventGatewayService = $injector.get('eventGatewayService');\n var timedOut = config.status === 408,\n result;\n\n if (err) {\n\n if (config.status === -1) {\n return null;\n }\n\n if (timedOut) {\n result = 'timeout';\n } else {\n result = 'failure';\n }\n } else {\n result = 'success';\n }\n\n eventGatewayService.sendEvent('serviceCallResult', {\n httpStatusCode: config.status,\n httpUrl: config.config.url,\n httpVerb: config.config.method,\n result: result\n });\n }\n }]);\n }", "setResponseInterceptor() {\n let self = this;\n this._axios.interceptors.response.use(\n response => {\n return response;\n },\n error => {\n self.checkResponseStatus(error);\n return Promise.reject(new QbResponseError(error));\n }\n );\n }", "addDefaultRequestInterceptor() {\n\t\tthis.axiosInstance.interceptors.request.use((config) => {\n\t\t\tlet need = Object.keys(this.option.auth).length > 0\n\t\t\tif (need) {\n\t\t\t\tconst timestamp = Date.now()\n\n\t\t\t\tlet query = {}\n\t\t\t\tconst array = config.url.split('?')\n\t\t\t\tif (array.length > 1) {\n\t\t\t\t\tquery = qs.parse(array[1])\n\t\t\t\t}\n\t\t\t\tconst data = config.data || {}\n\t\t\t\tconst params = config.params || {}\n\n\t\t\t\t// signature\n\t\t\t\tconst signature = sign(\n\t\t\t\t\tObject.assign({\n\t\t\t\t\t\t__timestamp__: timestamp\n\t\t\t\t\t}, data, params, query),\n\t\t\t\t\tthis.option.auth.token\n\t\t\t\t)\n\n\t\t\t\t// headers\n\t\t\t\tconfig.headers = {\n\t\t\t\t\t'h-token': this.option.auth.token,\n\t\t\t\t\t'h-nonce': this.option.auth.nonce,\n\t\t\t\t\t'h-signature': signature,\n\t\t\t\t\t'h-timestamp': timestamp\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn config\n\t\t}, (err) => {\n\t\t\treturn Promise.reject(err)\n\t\t})\n\t}", "function xhrInterceptor() {\n var originalXHR = window.XMLHttpRequest;\n var xhrSend = XMLHttpRequest.prototype.send;\n var xhrOpen = XMLHttpRequest.prototype.open;\n originalXHR.getRequestConfig = [];\n function ajaxEventTrigger(event) {\n var ajaxEvent = new CustomEvent(event, { detail: this });\n window.dispatchEvent(ajaxEvent);\n }\n function customizedXHR() {\n var liveXHR = new originalXHR();\n liveXHR.addEventListener('readystatechange', function () {\n ajaxEventTrigger.call(this, 'xhrReadyStateChange');\n }, false);\n liveXHR.open = function (method, url, async, username, password) {\n this.getRequestConfig = arguments;\n return xhrOpen.apply(this, arguments);\n };\n liveXHR.send = function (body) {\n return xhrSend.apply(this, arguments);\n };\n return liveXHR;\n }\n window.XMLHttpRequest = customizedXHR;\n }", "function LoadingHttpInterceptor($rootScope, $q) {\n\n var loadingCount = 0;\n var loadingEventName = 'spinner:activate';\n\n return {\n request: function (config) {\n // config object is everything needed to make $http request\n // runs this function before making request \n\n // console.log(\"Inside interceptor, config: \", config);\n\n if (++loadingCount === 1) {\n // above: incremet then test vs 1\n // to deal with multiple things at a time\n // change only happens at 1/0 boundary \n $rootScope.$broadcast(loadingEventName, {on: true});\n }\n\n return config;\n },\n\n response: function (response) {\n if (--loadingCount === 0) {\n $rootScope.$broadcast(loadingEventName, {on: false});\n }\n\n return response;\n },\n\n responseError: function (response) {\n if (--loadingCount === 0) {\n $rootScope.$broadcast(loadingEventName, {on: false});\n }\n\n return $q.reject(response); \n // reject promise to ensure that caller is not returned a success in the case of error\n }\n };\n}", "setRequestInterceptor() {\n this._axios.interceptors.request.use(config => {\n // a unique id per request\n config.headers[constants.HEADER.SESSION_ID] = uuid.v1();\n // not including now, but this is where we would add another header\n // if want to send unique id per user session --> config.uid\n\n let ticket = this.getCookie(CookieConstants.COOKIES.TICKET);\n if (ticket) {\n config.headers[constants.HEADER.TICKET] = ticket;\n }\n return config;\n });\n }", "static filterHttpRequest (request) {}", "function middleware(request, response, next) {}", "function IAjaxHttpHook() { }", "function interceptor(f){\n\n return function(){\n console.log('before function call...');\n var r = f.apply(this, arguments);\n console.log('after function call..');\n return r;\n }\n }", "function w3HttpInterceptor($q, $rootScope, $log, $injector) {\n\n var toastr;\n var service = {\n request: function(request) { \n request.headers['Authorization'] = 'Bearer ' + window.localStorage.getItem('token'); \n return request; \n },\n 'response': function (response) {\n //hideLoader();\n responseMensage(response.data);\n return response || $q.when(response);\n },\n 'responseError': function (rejection) {\n\n // hideLoader();\n\n if (rejection.status === 400) {\n \n if(rejection.data.error === 'token_invalid' || rejection.data.error === \"token_not_provided\"){\n $rootScope.$broadcast('w3HttpInterceptor:loginRequired', rejection);\n }\n \n //Erro de validacao\n responseMessageValidation(rejection.data);\n } else if (rejection.status === 403) {\n //Usuario não possui essa permissão\n $rootScope.$broadcast('w3HttpInterceptor:permissionRequired', rejection);\n } else if (rejection.status === 404) {\n //Não encontrado\n $rootScope.$broadcast('w3HttpInterceptor:notFound', rejection);\n responseMessageNotFound(rejection.data);\n } else if (rejection.status === 401) {\n //User não logado\n $rootScope.$broadcast('w3HttpInterceptor:loginRequired', rejection);\n } else if (rejection.status) {\n //alert(angular.toJson(rejection))\n $log.error(rejection);\n }\n\n return $q.reject(rejection);\n }\n };\n\n return service;\n\n //-----------------------------------------\n function getToaster() {\n if (!toastr) {\n toastr = $injector.get(\"toastr\");\n }\n return toastr;\n }\n\n // function showLoader() {\n // $rootScope.w3Loading = true;\n // }\n //\n // function hideLoader() {\n // $rootScope.w3Loading = false;\n // }\n\n function responseMensage(data) {\n if (data.status === \"success\" && data.message) {\n $log.info(data.message);\n getToaster().success(data.message);\n }\n }\n\n function responseMessageNotFound(data) {\n if (data.status === \"error\" && data.error.message) {\n $log.info(data.error.message);\n getToaster().error(data.error.message);\n }\n }\n\n function responseMessageValidation(data) {\n\n if (data.status === \"error\" && data.error.message) {\n\n if (data.error.validation.length) {\n\n var messageTemplate = \"<ul>\" +\n \"<li>\" +\n data.error.validation.join('</li><li>') +\n \"</li>\" +\n \"</ul>\";\n\n getToaster().error(messageTemplate, data.error.message);\n\n } else {\n getToaster().error(data.error.message);\n }\n\n }\n\n }\n\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.ResponseHeader;\n }", "onStartHeaders() {}", "userResDecorator(proxyRes, proxyResData, userReq, userRes) {\n // console.log(userRes);\n // return proxyResData;\n try {\n // get, parse, and transform the data if possible\n\n const dataString = proxyResData.toString('utf8');\n let data;\n try {\n // try for json data\n data = JSON.parse(proxyResData.toString('utf8'));\n } catch {\n console.log(\"couldn't parse data\");\n // otherwise just use the stringified data\n data = proxyResData.toString('utf8');\n }\n const modified = interceptor(data, userReq, userRes);\n // return transformed data to client\n return JSON.stringify(modified);\n } catch (e) {\n console.log(\"couldn't parse data, again! recieved error\", e);\n // on error, pass the data forward\n return proxyResData;\n }\n }", "componentWillMount() {\n\t\t\t// we will store reference to these interceptors which will be used upon ejecting\n\t\t\tthis.requestInterceptor = axios.interceptors.request.use(\n\t\t\t\tconfig => {\n\t\t\t\t\t// before sending a new request, we first clear any errors that were set earlier\n\t\t\t\t\tthis.setState({ error: null });\n\t\t\t\t\treturn config;\n\t\t\t\t},\n\t\t\t\terror => {\n\t\t\t\t\tthis.setState({ error: error });\n\t\t\t\t\treturn Promise.reject(error);\n\t\t\t\t\t// return Promise.reject(error.response); // correct because axios wraps error\n\t\t\t\t}\n\t\t\t);\n\t\t\tthis.responseInterceptor = axios.interceptors.response.use(\n\t\t\t\tresponse => response,\n\t\t\t\terror => {\n\t\t\t\t\tthis.setState({ error: error });\n\t\t\t\t\treturn Promise.reject(error);\n\t\t\t\t\t// return Promise.reject(error.response); // correct because axios wraps error\n\t\t\t\t}\n\t\t\t);\n\t\t}", "constructor(props, context) {\n super(props, context);\n\n // console.log('[withErrorHandler] constructor');\n // add interceptor for request to CLEAN state\n this.reqInterceptor = axios.interceptors.request.use(\n request => {\n this.setState({error: null});\n return request;\n })\n // add interceptor on axios to save if an error occured\n this.resInterceptor = axios.interceptors.response.use(\n response => response,\n error => {\n //console.log('[withErrorHandler]:', error);\n this.setState({error: error});\n })\n }", "setupAxiosIntercentors(token){\n\n \n\n axios.interceptors.request.use(\n (config) => {\n if(this.isUserLoggedIn()){\n \n config.headers.authorization = token\n }\n return config\n }\n )\n\n }", "async intercept(_ctx, _next) {\n let routeData = { match: false };\n switch (_ctx.request.method.toLowerCase()) {\n case 'head': routeData = this._travel('head', _ctx); break;\n case 'get': routeData = this._travel('get', _ctx); break;\n case 'post': routeData = this._travel('post', _ctx); break;\n case 'put': routeData = this._travel('put', _ctx); break;\n case 'patch': routeData = this._travel('patch', _ctx); break;\n case 'delete': routeData = this._travel('delete', _ctx); break;\n }\n\n if (routeData.match) {\n _ctx.request.route = routeData;\n await routeData.match(_ctx, _next, routeData);\n }\n await _next();\n }", "function ejectRequestInterceptors(){\n API_CLIENT.interceptors.request.eject(REQUEST_INTERCEPTOR);\n}", "function wirejQueryInterceptor() {\n $(document).ajaxStart(function () { processRequest(); });\n $(document).ajaxComplete(function () { processResponse(); });\n $(document).ajaxError(function () { processResponse(); });\n }", "function HttpHandler() {\n\t\t\tthis.activeDeffered = null;\n\t\t}", "function http(_x) {\n return _http.apply(this, arguments);\n} // exported for testing", "function http(_x) {\n return _http.apply(this, arguments);\n} // exported for testing", "function interceptingHandler(backend) {\n var interceptors = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n\n if (!interceptors) {\n return backend;\n }\n\n return interceptors.reduceRight(function (next, interceptor) {\n return new HttpInterceptorHandler(next, interceptor);\n }, backend);\n }", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n } else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n } else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n } else {\n params = new HttpParams({\n fromObject: options.params\n });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, options.body !== undefined ? options.body : null, {\n headers,\n context: options.context,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = (0,rxjs__WEBPACK_IMPORTED_MODULE_0__.of)(req).pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_1__.concatMap)(req => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_2__.filter)(event => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe((0,rxjs_operators__WEBPACK_IMPORTED_MODULE_3__.map)(res => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "callback( xhttp ){}", "addDefaultResponseInterceptor() {\n\t\tthis.axiosInstance.interceptors.response.use((res) => {\n\t\t\tconst data = res.data;\n\t\t\tif (data.status !== 200) {\n\t\t\t\treturn Promise.reject({status: data.status, body: data.body, message: data.message})\n\t\t\t}\n\t\t\treturn data.body\n\t\t}, (err) => {\n\t\t\tlet errorMessage = err.message\n\t\t\tlet status = -1\n\t\t\tif (err.response) {\n\t\t\t\tstatus = err.response.status\n\t\t\t\tswitch (err.response.status) {\n\t\t\t\t\tcase 404: {\n\t\t\t\t\t\terrorMessage = '404 not found'\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tcase 500: {\n\t\t\t\t\t\terrorMessage = '500 internal error'\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn Promise.reject({status: status, body: null, message: errorMessage})\n\t\t})\n\t}", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "request(first, url, options = {}) {\n let req;\n // First, check whether the primary argument is an instance of `HttpRequest`.\n if (first instanceof HttpRequest) {\n // It is. The other arguments must be undefined (per the signatures) and can be\n // ignored.\n req = first;\n }\n else {\n // It's a string, so it represents a URL. Construct a request based on it,\n // and incorporate the remaining arguments (assuming `GET` unless a method is\n // provided.\n // Figure out the headers.\n let headers = undefined;\n if (options.headers instanceof HttpHeaders) {\n headers = options.headers;\n }\n else {\n headers = new HttpHeaders(options.headers);\n }\n // Sort out parameters.\n let params = undefined;\n if (!!options.params) {\n if (options.params instanceof HttpParams) {\n params = options.params;\n }\n else {\n params = new HttpParams({ fromObject: options.params });\n }\n }\n // Construct the request.\n req = new HttpRequest(first, url, (options.body !== undefined ? options.body : null), {\n headers,\n params,\n reportProgress: options.reportProgress,\n // By default, JSON is assumed to be returned for all calls.\n responseType: options.responseType || 'json',\n withCredentials: options.withCredentials,\n });\n }\n // Start with an Observable.of() the initial request, and run the handler (which\n // includes all interceptors) inside a concatMap(). This way, the handler runs\n // inside an Observable chain, which causes interceptors to be re-run on every\n // subscription (this also makes retries re-run the handler, including interceptors).\n const events$ = Object(rxjs__WEBPACK_IMPORTED_MODULE_1__[\"of\"])(req).pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"concatMap\"])((req) => this.handler.handle(req)));\n // If coming via the API signature which accepts a previously constructed HttpRequest,\n // the only option is to get the event stream. Otherwise, return the event stream if\n // that is what was requested.\n if (first instanceof HttpRequest || options.observe === 'events') {\n return events$;\n }\n // The requested stream contains either the full response or the body. In either\n // case, the first step is to filter the event stream to extract a stream of\n // responses(s).\n const res$ = events$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"filter\"])((event) => event instanceof HttpResponse));\n // Decide which stream to return.\n switch (options.observe || 'body') {\n case 'body':\n // The requested stream is the body. Map the response stream to the response\n // body. This could be done more simply, but a misbehaving interceptor might\n // transform the response body into a different format and ignore the requested\n // responseType. Guard against this by validating that the response is of the\n // requested type.\n switch (req.responseType) {\n case 'arraybuffer':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is an ArrayBuffer.\n if (res.body !== null && !(res.body instanceof ArrayBuffer)) {\n throw new Error('Response is not an ArrayBuffer.');\n }\n return res.body;\n }));\n case 'blob':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a Blob.\n if (res.body !== null && !(res.body instanceof Blob)) {\n throw new Error('Response is not a Blob.');\n }\n return res.body;\n }));\n case 'text':\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => {\n // Validate that the body is a string.\n if (res.body !== null && typeof res.body !== 'string') {\n throw new Error('Response is not a string.');\n }\n return res.body;\n }));\n case 'json':\n default:\n // No validation needed for JSON responses, as they can be of any type.\n return res$.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[\"map\"])((res) => res.body));\n }\n case 'response':\n // The response stream was requested directly, so return it.\n return res$;\n default:\n // Guard against new future observe types being added.\n throw new Error(`Unreachable: unhandled observe type ${options.observe}}`);\n }\n }", "function jsonpInterceptorFn(req, next) {\n if (req.method === 'JSONP') {\n return (0,_angular_core__WEBPACK_IMPORTED_MODULE_4__.inject)(JsonpClientBackend).handle(req);\n }\n // Fall through for normal HTTP requests.\n return next(req);\n}", "constructor () {\n this._handleRequest = this._handleRequest.bind(this)\n }", "function initInterceptors () {\n axios.interceptors.request.use(\n async req => {\n const newRequest = { ...req }\n\n // get token from secure store\n try {\n const storageToken = await getSecureStoreKey(SECURITY_STORAGE_AUTH_KEY)\n if (token !== storageToken) token = storageToken\n\n if (token != null) {\n newRequest.headers = {\n ...newRequest.headers,\n authorization: `Bearer ${token}`\n }\n }\n } catch (err) {\n }\n\n // if (ENV === 'PRODUCTION' || ENV === 'PREPROD') {\n // newRequest.headers['X-Client-Version'] = CLIENT_VERSION\n // } else {\n // newRequest.headers['X-Client-Version'] = ENV\n // }\n\n return newRequest\n },\n error => Promise.reject(error)\n )\n\n axios.interceptors.response.use(\n res => {},\n async error => {\n const defaultMsg = 'Oops, it looks like something went wrong.'\n const err = error.response\n ? error.response.data\n : {\n type: 'Unknown Server Error',\n msg: defaultMsg,\n raw_error: error\n }\n\n if (!err.msg) err.msg = defaultMsg\n\n if (err.status === 401 && err.slug === 'SESSION_EXPIRED') {\n store.dispatch(actions.expireSession())\n await store.dispatch(await actions.logoutUser())\n }\n\n if (err.status === 403 && err.slug === 'USER_SUSPENDED') {\n const { profile } = store.getState().user\n if (profile && profile.id) {\n await store.dispatch(await actions.logoutUser())\n }\n await store.dispatch(await actions.showMessage('error', err.msg))\n }\n if (error.response.status === 429) {\n store.dispatch(actions.navigateTo('LockedAccount'))\n }\n\n return Promise.reject(err)\n }\n )\n}", "function interceptShindigOsapi() {\n\n var osapi = $r(\"osapi\");\n var $newBatch = osapi.newBatch;\n\n osapi.newBatch = function() {\n var batch = $newBatch.apply(this, arguments);\n osapi.jive.corev3._extendOsapiBatchRequestWithResponseInterceptorSupport(batch);\n return batch;\n };\n\n function defer(fn) {\n return function () {\n var self = this;\n var args = arguments;\n ext.runWhenReady(function () {\n return fn.apply(self, args);\n });\n }\n }\n\n function intercept(interceptor, response) {\n if (interceptor.renderSilent === true) {\n return response;\n }\n return interceptor(response) || response;\n }\n\n osapi.jive = osapi.jive || {};\n osapi.jive.corev3 = osapi.jive.corev3 || {};\n $e(osapi.jive.corev3, {\n _extendOsapiRequestWithResponseInterceptor : function(request, responseInterceptor) {\n request._jive = request._jive || {};\n if (!request._jive.hasOwnProperty(\"responseInterceptor\")) {\n if (request.execute._intercepted !== true) {\n var $execute = request.execute;\n request.execute = defer(function (callback) {\n var di = this._jive.responseInterceptor;\n if (di && di instanceof Function) {\n var callbackIntercept = function (response) {\n var args = Array.prototype.slice.call(arguments);\n args[0] = intercept(di, response) || response;\n return callback.apply(this, args);\n };\n var args = Array.prototype.slice.call(arguments);\n args[0] = callbackIntercept;\n return $execute.apply(this, args);\n }\n else {\n return $execute.apply(this, arguments);\n }\n });\n request.executeAs = function (personURI, callback) {\n this.rpc.runAs = \"uri \" + personURI;\n return this.execute(callback);\n };\n request.execute._intercepted = true;\n }\n }\n request._jive.responseInterceptor = responseInterceptor;\n },\n\n _buildRequestWithStaticResponse : function(response) {\n return {\n _jive: {\n staticResponse:response\n },\n execute: function(callback) {\n callback(response);\n }\n };\n },\n\n _buildRequestWithStaticErrorResponse : function(message) {\n return this._buildRequestWithStaticResponse(osapi.jive.core._createErrorResponse({\n message: message\n }));\n },\n\n _extendOsapiBatchRequestWithResponseInterceptorSupport : function(request) {\n if (request.add._intercepted !== true) {\n var $add = request.add;\n request.add = function(key, request) {\n this._jive = this._jive || {requestCount:0};\n this._jive.allRequests = this._jive.allRequests || [];\n var di = request._jive && request._jive.responseInterceptor;\n if (di && di instanceof Function) {\n this._jive.diContainer = this._jive.diContainer || [];\n var diContainer = this._jive.diContainer;\n diContainer.push({ key: key, responseInterceptor: di, request: request });\n }\n var sr = request._jive && request._jive.staticResponse;\n if (sr) {\n this._jive = this._jive || {};\n this._jive.srContainer = this._jive.srContainer || {};\n var srContainer = this._jive.srContainer;\n srContainer[key] = sr;\n } else {\n this._jive.requestCount++;\n this._jive.allRequests.push(request);\n return $add.apply(this, arguments);\n }\n };\n request.add._intercepted = true;\n }\n\n if (request.execute._intercepted !== true) {\n var $execute = request.execute;\n request.execute = defer( function (callback) {\n if (this._jive && this._jive.diContainer && this._jive.diContainer.length) {\n var diContainer = this._jive.diContainer;\n var srContainer = this._jive.srContainer || {};\n var callbackIntercept = function (response) {\n var restore = [];\n for (var i = 0, l = diContainer.length; i < l; ++i) {\n var key = diContainer[i].key;\n if (response.hasOwnProperty(key) && response[key]) {\n var content = response[key];\n if (content) {\n var di = diContainer[i].responseInterceptor;\n var req = diContainer[i].request;\n content = intercept(di, content) || content;\n // hide the interceptor on the request to\n // prevent it from being called twice\n req._jive.responseInterceptor.renderSilent = true;\n restore.push(req._jive.responseInterceptor);\n response[key] = content;\n }\n }\n }\n for (var k in srContainer) {\n if (srContainer.hasOwnProperty(k)) {\n response[k] = srContainer[k];\n }\n }\n var args = Array.prototype.slice.call(arguments);\n args[0] = response;\n try {\n var result = callback.apply(this, args);\n restoreSilence();\n }\n catch (e) {\n restoreSilence(); // because IE is dumb\n throw e;\n }\n function restoreSilence() {\n for (i = 0, l = restore.length; i < l; ++i) {\n // restore the interceptor on the request so that it\n // may be used again\n delete restore[i].renderSilent;\n }\n }\n\n return result;\n };\n var args = Array.prototype.slice.call(arguments);\n args[0] = callbackIntercept;\n return $execute.apply(this, args);\n }\n else if (this._jive && this._jive.srContainer) {\n // pure static response\n callback(this._jive.srContainer)\n }\n else {\n $execute.apply(this, arguments)\n }\n });\n request.executeAs = function (personURI, callback) {\n var requests = (this._jive && this._jive.allRequests) || [];\n var i, l = requests.length;\n for (i = 0; i < l; i++) {\n var req = requests[i];\n if (!/^jive\\.core\\.(get|put|post|delete)$/.test(req.method)) {\n throw \"executeAs() supports batch requests which contain only core API requests: '\" + req.method + \"' is unsupported\";\n }\n }\n var runAs = \"uri \" + personURI;\n for (i = 0; i < l; i++) {\n requests[i].rpc.runAs = runAs;\n }\n return this.execute(callback);\n };\n request.execute._intercepted = true;\n }\n }\n\n });\n\n function interceptJiveCoreRestCall(propertyName) {\n var fn = osapi.jive.core[propertyName];\n if (typeof fn === \"function\" && fn._intercepted !== true) {\n osapi.jive.core[propertyName] = function () {\n var req = fn.apply(osapi.jive.core, arguments);\n if (req) {\n osapi.jive.corev3._extendOsapiRequestWithResponseInterceptor(req,\n function() {\n return osapi.jive.corev3._interceptData.apply(this, arguments);\n });\n }\n return req;\n };\n osapi.jive.core[propertyName]._intercepted = true;\n }\n }\n\n initIntercept = function() {\n if (osapi.jive.core) {\n interceptJiveCoreRestCall(\"get\");\n interceptJiveCoreRestCall(\"put\");\n interceptJiveCoreRestCall(\"post\");\n interceptJiveCoreRestCall(\"delete\");\n }\n if (typeof opensocial === \"object\" && opensocial.data && opensocial.data.getDataContext && opensocial.data.getDataContext._intercepted !== true) {\n var $dataContext = opensocial.data.getDataContext;\n opensocial.data.getDataContext = function() {\n var ctx = $dataContext.apply(this, arguments);\n if ( ctx.getDataSet._intercepted !== true ) {\n $getDataSet = ctx.getDataSet;\n ctx.getDataSet = function() {\n return interceptData($getDataSet.apply(this, arguments));\n };\n ctx.getDataSet._intercepted = true;\n }\n return ctx;\n };\n opensocial.data.getDataContext._intercepted = true;\n }\n };\n\n registerOnLoadHandler(initIntercept);\n\n }", "function responseHandler(srcResponse, numer)\n{\n camz[numer].headers = srcResponse.headers;\n srcResponse.on('data', function(chunk) {dataHandler(chunk, numer)});\n}", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "middleware (opts={}) {\n let correlationHeader = opts.correlationHeader || this.correlationHeader;\n let formatReq = opts.formatReq || this.formatReq;\n let formatRes = opts.formatRes || this.formatRes;\n let correlationGen = opts.correlationGen || this.correlationGen;\n let requestIdHeader = opts.requestIdHeader || this.requestIdHeader;\n\n return async (ctx, next) => {\n let res = ctx.res;\n let reqTime = new Date();\n let reqId = UUID.v4();\n let classname = (ctx.request.headers[correlationHeader]) ? 'service_request' : 'client_request';\n let correlationId = ctx.request.headers[correlationHeader] || correlationGen();\n ctx.request.headers[correlationHeader] = correlationId;\n ctx.request.headers[requestIdHeader] = correlationId;\n\n let done = (evt) => {\n let resTime = new Date();\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n let logBase = {\n requestId : reqId,\n classname : classname,\n correlationId : correlationId,\n resolutionTime : resTime - reqTime,\n requestTime : reqTime.toString(),\n responseTime : res.toString(),\n formatRes : formatReq,\n formatRes : formatRes,\n };\n\n logBase.message = formatReq(ctx);\n this.log('informational', this.buildReqLog(ctx, logBase));\n let resLevel = (ctx.response.status >= 400 ? 'informational' : 'error');\n logBase.message = formatRes(ctx);\n this.log(resLevel, this.buildResLog(ctx, logBase));\n };\n\n let onFinish = done.bind(null, 'finish');\n let onClose = done.bind(null, 'close');\n res.once('finish', onFinish);\n res.once('close', onClose);\n\n try {\n await next();\n } catch (err) {\n throw err;\n }\n }\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "constructor(init = {}) {\n super(init);\n this.type = HttpEventType.Response;\n this.body = init.body !== undefined ? init.body : null;\n }", "function ExtractResponseInterceptor(data, operation) {\n var extractedData;\n if (operation === 'getList') {\n extractedData = data.list;\n extractedData.meta = data.meta;\n } else {\n extractedData = data;\n }\n return extractedData;\n }", "_onResponse(msg) {\n let _this = this;\n\n let event = {\n type: msg.type,\n url: msg.body.source,\n code: msg.body.code\n };\n\n if (_this._onResponseHandler) {\n _this._onResponseHandler(event);\n }\n }", "function legacyInterceptorFnFactory() {\n let chain = null;\n return (req, handler) => {\n if (chain === null) {\n const interceptors = (0,_angular_core__WEBPACK_IMPORTED_MODULE_4__.inject)(HTTP_INTERCEPTORS, {\n optional: true\n }) ?? [];\n // Note: interceptors are wrapped right-to-left so that final execution order is\n // left-to-right. That is, if `interceptors` is the array `[a, b, c]`, we want to\n // produce a chain that is conceptually `c(b(a(end)))`, which we build from the inside\n // out.\n chain = interceptors.reduceRight(adaptLegacyInterceptorToChain, interceptorChainEndFn);\n }\n return chain(req, handler);\n };\n}", "function HttpRejectionProcessor(){}", "handleResponse(res) {\n if (res instanceof HttpResponse || res instanceof HttpErrorResponse) {\n if (this.tokenService.tokenOptions.apiBase === null || (res.url && res.url.match(this.tokenService.tokenOptions.apiBase))) {\n this.tokenService.getAuthHeadersFromResponse(res);\n }\n }\n }", "function loginInterceptor(data) {\n \n // set some properties on the user from headers that will only be available when logging in\n const loginRedirectUrl = data.headers('X-Mango-Default-URI');\n const lastUpgrade = data.headers('X-Mango-Last-Upgrade');\n \n if (loginRedirectUrl) {\n data.resource.loginRedirectUrl = loginRedirectUrl;\n }\n if (lastUpgrade) {\n data.resource.lastUpgradeTime = parseInt(lastUpgrade, 10);\n }\n \n User.loginInterceptors.forEach(interceptor => interceptor(data));\n\n return data.resource;\n }", "function LoaderInterceptor($rootScope, $q) {\n\n var requestCount = 0;\n var ignoredEndpoints = [];\n\n return {\n request: function (request) {\n requestCount++;\n\n // Check if the url is ignored\n var isIgnored = false;\n angular.forEach(ignoredEndpoints, function (ignoredUrl) {\n if (request && request.url.indexOf(ignoredUrl) !== -1) {\n isIgnored = true;\n }\n });\n\n if (!isIgnored) {\n $rootScope.$broadcast('loader:Show');\n }\n\n return request || $q.when(request);\n },\n response: function (response) {\n if ((--requestCount) === 0) {\n // Hide loader\n $rootScope.$broadcast('loader:Hide');\n }\n\n return response || $q.when(response);\n },\n responseError: function (response) {\n if ((--requestCount) === 0) {\n // Hide loader\n $rootScope.$broadcast('loader:Hide');\n }\n\n return $q.reject(response);\n },\n addIgnoredEndpoint: function (endpointUrl) {\n ignoredEndpoints.push(endpointUrl);\n return ignoredEndpoints;\n }\n };\n\n}", "constructor(){\n super(...arguments);\n this._handlers = {};\n this._proxies = [];\n }", "constructor(http){\n this.http = http;\n }", "function logRequest(req,res,next)\n{\n console.log(`Request ${req.method} ${req.originalUrl} from ${req.ip}`)\n next()\n}", "send(message, transformers) {\n message.interceptors = message.interceptors || [];\n\n var conf = this.tokenAuthConfiguration;\n if(!conf.disabled) {\n message.interceptors.unshift(new RequestInterceptor(this.bearerToken));\n if(conf.renewBearerToken || !this.bearerToken) {\n message.interceptors.unshift(new ResponseInterceptor(this.setBearerToken.bind(this), this.tokenAuthConfiguration.bearerTokenHeaders));\n }\n }\n\n return new HttpClient().send(message, transformers);\n return super.send(message, transformers);\n }", "function addInterceptor(res, callback) {\n const originalEnd = res.end;\n\n res.end = function(data) {\n appendWrites(res, data);\n\n const cacheObject = {\n statusCode: res.statusCode,\n content: res._responseBody ? res._responseBody.toString(\"base64\") : '',\n headers: res._headers\n };\n\n callback(null, cacheObject);\n\n return originalEnd.apply(res, arguments);\n }\n\n const originalWrite = res.write;\n res.write = function (data) {\n appendWrites(res, data);\n\n return originalWrite.apply(res, arguments);\n }\n}", "function Interceptor(nativeOpenWrapper, nativeSendWrapper) {\r\n XMLHttpRequest.prototype.open = function () {\r\n // Code here to intercept XHR\r\n // console.log(this, arguments);\r\n return nativeOpenWrapper.apply(this, arguments);\r\n }\r\n XMLHttpRequest.prototype.send = function () {\r\n this.onloadend = function () {\r\n if (this.capture) {\r\n // console.log(this.responseText);\r\n }\r\n }\r\n // console.log(this, arguments);\r\n var xhr = this,\r\n waiter = setInterval(function () {\r\n if (xhr.readyState && xhr.readyState == 4) {\r\n if(xhr.responseURL != null){\r\n var checkingUrl = xhr.responseURL.split(\"/\");\r\n if( checkingUrl[ checkingUrl.length - 1 ] == \"ConfigDwr.updateArraySize.dwr\" ){\r\n $('#update')[0].click();\r\n }\r\n }\r\n clearInterval(waiter);\r\n }\r\n }, 50);\r\n return nativeSendWrapper.apply(this, arguments);\r\n }\r\n }", "function interceptResponse(parms, res) {\n\n\t// only cache if the last-modified header is set.\n\tif(res.headers['last-modified']) {\n\n\t\tvar cacheObj = {data:''};\n\t\tres.on('end', function() {\n\n\t\t\t// commit to cache\n\t\t\t_.extend(cacheObj, _.pick(res, [\n\t\t\t\t\t'headers', 'rawHeaders', 'httpVersion', 'trailers', 'rawTrailers',\n\t\t\t\t\t'method', 'url']));\n\n\t\t\tcache.set(parms.cacheKey, cacheObj, parms.cacheTtl);\n\n\t\t});\n\n\t\tres.on('data', function(chunk) {\n\t\t\tcacheObj.data += chunk;\n\t\t});\n\n\t}\n\n}", "function loadingInterceptor($rootScope, $q) {\n let _openRequests_ = 0;\n\n return {\n request: config => {\n _openRequests_++;\n $rootScope.$broadcast('loading_show');\n return config || $q.when(config);\n },\n response: response => {\n if (!(--_openRequests_)) {\n $rootScope.$broadcast('loading_hide');\n }\n return response || $q.when(response);\n },\n responseError: response => {\n if (!(--_openRequests_)) {\n $rootScope.$broadcast('loading_hide');\n }\n return $q.reject(response);\n }\n };\n }", "responseForRequest() {\n throw new Error('Not implemented');\n }", "function overrideHttpRequestPrototype () {\n // Save the original function in a 'proxy' variable\n let original = window.XMLHttpRequest.prototype.send;\n\n // Override it\n window.XMLHttpRequest.prototype.send = function() {\n console.info(\"[COVID-COUNTER] Intercepting request...\");\n\n // Appends an event to the stack\n this.addEventListener(\"readystatechange\", function(e) {\n // Check if the response was successful\n if (this.readyState === 4 && this.status === 200) {\n // Check for the wanted API endpoint\n if (this.__zone_symbol__xhrURL.toLowerCase().endsWith(API_ENDPOINT)) {\n // Parse the responseText and send it to the event handler!\n let response = JSON.parse(this.responseText);\n onResponse(response);\n }\n }\n });\n\n // Route back to the original function\n return original.apply(this, [...arguments]);\n };\n}", "function Proxy () {\n log.info('Proxy constructor');\n var self = this;\n\n this.proxy = httpProxy.createProxyServer({});\n this.proxy.on('error', function (err, req/*, proxiedRes */) {\n var res = req.res;\n var logData = {\n tx: true,\n err: err,\n req: req\n };\n log.error(logData, 'proxy.on error');\n /**\n * we need to keep the didError logic. sometimes (not sure why) but we try to proxy the same\n * request twice (in some network cases) and navi will crash saying you can't send on a request\n * that is already ended\n */\n if (!req.didError) {\n req.didError = true;\n var errorUrl = errorPage.generateErrorUrl('unresponsive', {\n shortHash: req.shortHash,\n elasticUrl: req.elasticUrl\n });\n var targetHost = getHostAndAugmentReq(req, errorUrl);\n log.trace(put({\n targetHost: targetHost,\n errorUrl: errorUrl\n }, logData), 'proxy.on error !req.didError');\n self.proxy.web(req, res, { target: targetHost });\n } else {\n log.trace(logData, 'proxy.on error req.didError');\n }\n });\n\n /**\n * Listen to proxy events for timing logs\n */\n this.proxy.on('proxyReq', function () {\n log.trace({\n tx: true\n }, 'proxy.on proxyReq');\n });\n\n this.proxy.on('proxyRes', function (proxyRes, req, proxiedRes) {\n var res = req.res;\n var targetInstanceName = keypather.get(req, 'targetInstance.attrs.name');\n log.trace({\n tx: true,\n targetInstanceName: targetInstanceName,\n res: res\n }, 'proxy.on proxyRes');\n self._addHeadersToRes(req, proxyRes, targetInstanceName);\n self._streamRes(proxyRes, proxiedRes, res, keypather.get(req, 'naviEntry.redirectEnabled'));\n });\n}", "bless(request) {\n // create headers if does not already exist\n if(request.headers == null) request.headers = {}\n // assign authentication bearer token\n request.headers[\"Authorization\"] = \"Bearer \" + this.token;\n return request;\n }", "constructor(http) {\n this.http = http;\n }", "constructor(http) {\n this.http = http;\n }", "function logger(req, res, next) {\n console.log(\n `[${new Date().toISOString()}] ${req.method} to ${req.url} ${req.get('Origin')}` //<-- What goes inside the get request here comes back undefined?\n )\n next();\n }", "function TokenInterceptor($q, $location, localStorageService) {\n return {\n request: function (config) {\n config.headers = config.headers || {};\n\n if (localStorageService.get(\"auth_token\")) {\n config.headers.Authorization = 'Bearer ' + localStorageService.get(\"auth_token\");\n }\n\n return config;\n },\n response: function (response) {\n return response || $q.when(response);\n },\n responseError: function (response) {\n if (response.status === 401) {\n localStorageService.clearAll();\n $location.path(\"/login\");\n }\n return $q.reject(response);\n }\n };\n }", "function log() {\n logger.hit(`${this.req.url} ${this.statusCode} ${this.req.method} ${this.req.body.From} ${this.req.body.Body} ${this[action_symbol]}`, this)\n}", "handle(req) {\n // Quick check to give a better error message when a user attempts to use\n // HttpClient.jsonp() without installing the HttpClientJsonpModule\n if (req.method === 'JSONP') {\n throw new Error(`Attempted to construct Jsonp request without HttpClientJsonpModule installed.`);\n }\n // Everything happens on Observable subscription.\n return new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"]((observer) => {\n // Start by setting up the XHR object with request method, URL, and withCredentials flag.\n const xhr = this.xhrFactory.build();\n xhr.open(req.method, req.urlWithParams);\n if (!!req.withCredentials) {\n xhr.withCredentials = true;\n }\n // Add all the requested headers.\n req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));\n // Add an Accept header if one isn't present already.\n if (!req.headers.has('Accept')) {\n xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');\n }\n // Auto-detect the Content-Type header if one isn't present already.\n if (!req.headers.has('Content-Type')) {\n const detectedType = req.detectContentTypeHeader();\n // Sometimes Content-Type detection fails.\n if (detectedType !== null) {\n xhr.setRequestHeader('Content-Type', detectedType);\n }\n }\n // Set the responseType if one was requested.\n if (req.responseType) {\n const responseType = req.responseType.toLowerCase();\n // JSON responses need to be processed as text. This is because if the server\n // returns an XSSI-prefixed JSON response, the browser will fail to parse it,\n // xhr.response will be null, and xhr.responseText cannot be accessed to\n // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON\n // is parsed by first requesting text and then applying JSON.parse.\n xhr.responseType = ((responseType !== 'json') ? responseType : 'text');\n }\n // Serialize the request body if one is present. If not, this will be set to null.\n const reqBody = req.serializeBody();\n // If progress events are enabled, response headers will be delivered\n // in two events - the HttpHeaderResponse event and the full HttpResponse\n // event. However, since response headers don't change in between these\n // two events, it doesn't make sense to parse them twice. So headerResponse\n // caches the data extracted from the response whenever it's first parsed,\n // to ensure parsing isn't duplicated.\n let headerResponse = null;\n // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest\n // state, and memoizes it into headerResponse.\n const partialFromXhr = () => {\n if (headerResponse !== null) {\n return headerResponse;\n }\n // Read status and normalize an IE9 bug (https://bugs.jquery.com/ticket/1450).\n const status = xhr.status === 1223 ? 204 : xhr.status;\n const statusText = xhr.statusText || 'OK';\n // Parse headers from XMLHttpRequest - this step is lazy.\n const headers = new HttpHeaders(xhr.getAllResponseHeaders());\n // Read the response URL from the XMLHttpResponse instance and fall back on the\n // request URL.\n const url = getResponseUrl(xhr) || req.url;\n // Construct the HttpHeaderResponse and memoize it.\n headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });\n return headerResponse;\n };\n // Next, a few closures are defined for the various events which XMLHttpRequest can\n // emit. This allows them to be unregistered as event listeners later.\n // First up is the load event, which represents a response being fully available.\n const onLoad = () => {\n // Read response state from the memoized partial data.\n let { headers, status, statusText, url } = partialFromXhr();\n // The body will be read out if present.\n let body = null;\n if (status !== 204) {\n // Use XMLHttpRequest.response if set, responseText otherwise.\n body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;\n }\n // Normalize another potential bug (this one comes from CORS).\n if (status === 0) {\n status = !!body ? 200 : 0;\n }\n // ok determines whether the response will be transmitted on the event or\n // error channel. Unsuccessful status codes (not 2xx) will always be errors,\n // but a successful status code can still result in an error if the user\n // asked for JSON data and the body cannot be parsed as such.\n let ok = status >= 200 && status < 300;\n // Check whether the body needs to be parsed as JSON (in many cases the browser\n // will have done that already).\n if (req.responseType === 'json' && typeof body === 'string') {\n // Save the original body, before attempting XSSI prefix stripping.\n const originalBody = body;\n body = body.replace(XSSI_PREFIX, '');\n try {\n // Attempt the parse. If it fails, a parse error should be delivered to the user.\n body = body !== '' ? JSON.parse(body) : null;\n }\n catch (error) {\n // Since the JSON.parse failed, it's reasonable to assume this might not have been a\n // JSON response. Restore the original body (including any XSSI prefix) to deliver\n // a better error response.\n body = originalBody;\n // If this was an error request to begin with, leave it as a string, it probably\n // just isn't JSON. Otherwise, deliver the parsing error to the user.\n if (ok) {\n // Even though the response status was 2xx, this is still an error.\n ok = false;\n // The parse error contains the text of the body that failed to parse.\n body = { error, text: body };\n }\n }\n }\n if (ok) {\n // A successful response is delivered on the event stream.\n observer.next(new HttpResponse({\n body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n // The full body has been received and delivered, no further events\n // are possible. This request is complete.\n observer.complete();\n }\n else {\n // An unsuccessful request is delivered on the error channel.\n observer.error(new HttpErrorResponse({\n // The error in this case is the response body (error from the server).\n error: body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n }\n };\n // The onError callback is called when something goes wrong at the network level.\n // Connection timeout, DNS error, offline, etc. These are actual errors, and are\n // transmitted on the error channel.\n const onError = (error) => {\n const { url } = partialFromXhr();\n const res = new HttpErrorResponse({\n error,\n status: xhr.status || 0,\n statusText: xhr.statusText || 'Unknown Error',\n url: url || undefined,\n });\n observer.error(res);\n };\n // The sentHeaders flag tracks whether the HttpResponseHeaders event\n // has been sent on the stream. This is necessary to track if progress\n // is enabled since the event will be sent on only the first download\n // progerss event.\n let sentHeaders = false;\n // The download progress event handler, which is only registered if\n // progress events are enabled.\n const onDownProgress = (event) => {\n // Send the HttpResponseHeaders event if it hasn't been sent already.\n if (!sentHeaders) {\n observer.next(partialFromXhr());\n sentHeaders = true;\n }\n // Start building the download progress event to deliver on the response\n // event stream.\n let progressEvent = {\n type: HttpEventType.DownloadProgress,\n loaded: event.loaded,\n };\n // Set the total number of bytes in the event if it's available.\n if (event.lengthComputable) {\n progressEvent.total = event.total;\n }\n // If the request was for text content and a partial response is\n // available on XMLHttpRequest, include it in the progress event\n // to allow for streaming reads.\n if (req.responseType === 'text' && !!xhr.responseText) {\n progressEvent.partialText = xhr.responseText;\n }\n // Finally, fire the event.\n observer.next(progressEvent);\n };\n // The upload progress event handler, which is only registered if\n // progress events are enabled.\n const onUpProgress = (event) => {\n // Upload progress events are simpler. Begin building the progress\n // event.\n let progress = {\n type: HttpEventType.UploadProgress,\n loaded: event.loaded,\n };\n // If the total number of bytes being uploaded is available, include\n // it.\n if (event.lengthComputable) {\n progress.total = event.total;\n }\n // Send the event.\n observer.next(progress);\n };\n // By default, register for load and error events.\n xhr.addEventListener('load', onLoad);\n xhr.addEventListener('error', onError);\n xhr.addEventListener('timeout', onError);\n xhr.addEventListener('abort', onError);\n // Progress events are only enabled if requested.\n if (req.reportProgress) {\n // Download progress is always enabled if requested.\n xhr.addEventListener('progress', onDownProgress);\n // Upload progress depends on whether there is a body to upload.\n if (reqBody !== null && xhr.upload) {\n xhr.upload.addEventListener('progress', onUpProgress);\n }\n }\n // Fire the request, and notify the event stream that it was fired.\n xhr.send(reqBody);\n observer.next({ type: HttpEventType.Sent });\n // This is the return from the Observable function, which is the\n // request cancellation handler.\n return () => {\n // On a cancellation, remove all registered event listeners.\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('abort', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onError);\n if (req.reportProgress) {\n xhr.removeEventListener('progress', onDownProgress);\n if (reqBody !== null && xhr.upload) {\n xhr.upload.removeEventListener('progress', onUpProgress);\n }\n }\n // Finally, abort the in-flight request.\n if (xhr.readyState !== xhr.DONE) {\n xhr.abort();\n }\n };\n });\n }", "handle(req) {\n // Quick check to give a better error message when a user attempts to use\n // HttpClient.jsonp() without installing the HttpClientJsonpModule\n if (req.method === 'JSONP') {\n throw new Error(`Attempted to construct Jsonp request without HttpClientJsonpModule installed.`);\n }\n // Everything happens on Observable subscription.\n return new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"]((observer) => {\n // Start by setting up the XHR object with request method, URL, and withCredentials flag.\n const xhr = this.xhrFactory.build();\n xhr.open(req.method, req.urlWithParams);\n if (!!req.withCredentials) {\n xhr.withCredentials = true;\n }\n // Add all the requested headers.\n req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));\n // Add an Accept header if one isn't present already.\n if (!req.headers.has('Accept')) {\n xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');\n }\n // Auto-detect the Content-Type header if one isn't present already.\n if (!req.headers.has('Content-Type')) {\n const detectedType = req.detectContentTypeHeader();\n // Sometimes Content-Type detection fails.\n if (detectedType !== null) {\n xhr.setRequestHeader('Content-Type', detectedType);\n }\n }\n // Set the responseType if one was requested.\n if (req.responseType) {\n const responseType = req.responseType.toLowerCase();\n // JSON responses need to be processed as text. This is because if the server\n // returns an XSSI-prefixed JSON response, the browser will fail to parse it,\n // xhr.response will be null, and xhr.responseText cannot be accessed to\n // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON\n // is parsed by first requesting text and then applying JSON.parse.\n xhr.responseType = ((responseType !== 'json') ? responseType : 'text');\n }\n // Serialize the request body if one is present. If not, this will be set to null.\n const reqBody = req.serializeBody();\n // If progress events are enabled, response headers will be delivered\n // in two events - the HttpHeaderResponse event and the full HttpResponse\n // event. However, since response headers don't change in between these\n // two events, it doesn't make sense to parse them twice. So headerResponse\n // caches the data extracted from the response whenever it's first parsed,\n // to ensure parsing isn't duplicated.\n let headerResponse = null;\n // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest\n // state, and memoizes it into headerResponse.\n const partialFromXhr = () => {\n if (headerResponse !== null) {\n return headerResponse;\n }\n // Read status and normalize an IE9 bug (https://bugs.jquery.com/ticket/1450).\n const status = xhr.status === 1223 ? 204 : xhr.status;\n const statusText = xhr.statusText || 'OK';\n // Parse headers from XMLHttpRequest - this step is lazy.\n const headers = new HttpHeaders(xhr.getAllResponseHeaders());\n // Read the response URL from the XMLHttpResponse instance and fall back on the\n // request URL.\n const url = getResponseUrl(xhr) || req.url;\n // Construct the HttpHeaderResponse and memoize it.\n headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });\n return headerResponse;\n };\n // Next, a few closures are defined for the various events which XMLHttpRequest can\n // emit. This allows them to be unregistered as event listeners later.\n // First up is the load event, which represents a response being fully available.\n const onLoad = () => {\n // Read response state from the memoized partial data.\n let { headers, status, statusText, url } = partialFromXhr();\n // The body will be read out if present.\n let body = null;\n if (status !== 204) {\n // Use XMLHttpRequest.response if set, responseText otherwise.\n body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;\n }\n // Normalize another potential bug (this one comes from CORS).\n if (status === 0) {\n status = !!body ? 200 : 0;\n }\n // ok determines whether the response will be transmitted on the event or\n // error channel. Unsuccessful status codes (not 2xx) will always be errors,\n // but a successful status code can still result in an error if the user\n // asked for JSON data and the body cannot be parsed as such.\n let ok = status >= 200 && status < 300;\n // Check whether the body needs to be parsed as JSON (in many cases the browser\n // will have done that already).\n if (req.responseType === 'json' && typeof body === 'string') {\n // Save the original body, before attempting XSSI prefix stripping.\n const originalBody = body;\n body = body.replace(XSSI_PREFIX, '');\n try {\n // Attempt the parse. If it fails, a parse error should be delivered to the user.\n body = body !== '' ? JSON.parse(body) : null;\n }\n catch (error) {\n // Since the JSON.parse failed, it's reasonable to assume this might not have been a\n // JSON response. Restore the original body (including any XSSI prefix) to deliver\n // a better error response.\n body = originalBody;\n // If this was an error request to begin with, leave it as a string, it probably\n // just isn't JSON. Otherwise, deliver the parsing error to the user.\n if (ok) {\n // Even though the response status was 2xx, this is still an error.\n ok = false;\n // The parse error contains the text of the body that failed to parse.\n body = { error, text: body };\n }\n }\n }\n if (ok) {\n // A successful response is delivered on the event stream.\n observer.next(new HttpResponse({\n body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n // The full body has been received and delivered, no further events\n // are possible. This request is complete.\n observer.complete();\n }\n else {\n // An unsuccessful request is delivered on the error channel.\n observer.error(new HttpErrorResponse({\n // The error in this case is the response body (error from the server).\n error: body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n }\n };\n // The onError callback is called when something goes wrong at the network level.\n // Connection timeout, DNS error, offline, etc. These are actual errors, and are\n // transmitted on the error channel.\n const onError = (error) => {\n const { url } = partialFromXhr();\n const res = new HttpErrorResponse({\n error,\n status: xhr.status || 0,\n statusText: xhr.statusText || 'Unknown Error',\n url: url || undefined,\n });\n observer.error(res);\n };\n // The sentHeaders flag tracks whether the HttpResponseHeaders event\n // has been sent on the stream. This is necessary to track if progress\n // is enabled since the event will be sent on only the first download\n // progerss event.\n let sentHeaders = false;\n // The download progress event handler, which is only registered if\n // progress events are enabled.\n const onDownProgress = (event) => {\n // Send the HttpResponseHeaders event if it hasn't been sent already.\n if (!sentHeaders) {\n observer.next(partialFromXhr());\n sentHeaders = true;\n }\n // Start building the download progress event to deliver on the response\n // event stream.\n let progressEvent = {\n type: HttpEventType.DownloadProgress,\n loaded: event.loaded,\n };\n // Set the total number of bytes in the event if it's available.\n if (event.lengthComputable) {\n progressEvent.total = event.total;\n }\n // If the request was for text content and a partial response is\n // available on XMLHttpRequest, include it in the progress event\n // to allow for streaming reads.\n if (req.responseType === 'text' && !!xhr.responseText) {\n progressEvent.partialText = xhr.responseText;\n }\n // Finally, fire the event.\n observer.next(progressEvent);\n };\n // The upload progress event handler, which is only registered if\n // progress events are enabled.\n const onUpProgress = (event) => {\n // Upload progress events are simpler. Begin building the progress\n // event.\n let progress = {\n type: HttpEventType.UploadProgress,\n loaded: event.loaded,\n };\n // If the total number of bytes being uploaded is available, include\n // it.\n if (event.lengthComputable) {\n progress.total = event.total;\n }\n // Send the event.\n observer.next(progress);\n };\n // By default, register for load and error events.\n xhr.addEventListener('load', onLoad);\n xhr.addEventListener('error', onError);\n // Progress events are only enabled if requested.\n if (req.reportProgress) {\n // Download progress is always enabled if requested.\n xhr.addEventListener('progress', onDownProgress);\n // Upload progress depends on whether there is a body to upload.\n if (reqBody !== null && xhr.upload) {\n xhr.upload.addEventListener('progress', onUpProgress);\n }\n }\n // Fire the request, and notify the event stream that it was fired.\n xhr.send(reqBody);\n observer.next({ type: HttpEventType.Sent });\n // This is the return from the Observable function, which is the\n // request cancellation handler.\n return () => {\n // On a cancellation, remove all registered event listeners.\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n if (req.reportProgress) {\n xhr.removeEventListener('progress', onDownProgress);\n if (reqBody !== null && xhr.upload) {\n xhr.upload.removeEventListener('progress', onUpProgress);\n }\n }\n // Finally, abort the in-flight request.\n if (xhr.readyState !== xhr.DONE) {\n xhr.abort();\n }\n };\n });\n }", "handle(req) {\n // Quick check to give a better error message when a user attempts to use\n // HttpClient.jsonp() without installing the HttpClientJsonpModule\n if (req.method === 'JSONP') {\n throw new Error(`Attempted to construct Jsonp request without HttpClientJsonpModule installed.`);\n }\n // Everything happens on Observable subscription.\n return new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"]((observer) => {\n // Start by setting up the XHR object with request method, URL, and withCredentials flag.\n const xhr = this.xhrFactory.build();\n xhr.open(req.method, req.urlWithParams);\n if (!!req.withCredentials) {\n xhr.withCredentials = true;\n }\n // Add all the requested headers.\n req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));\n // Add an Accept header if one isn't present already.\n if (!req.headers.has('Accept')) {\n xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');\n }\n // Auto-detect the Content-Type header if one isn't present already.\n if (!req.headers.has('Content-Type')) {\n const detectedType = req.detectContentTypeHeader();\n // Sometimes Content-Type detection fails.\n if (detectedType !== null) {\n xhr.setRequestHeader('Content-Type', detectedType);\n }\n }\n // Set the responseType if one was requested.\n if (req.responseType) {\n const responseType = req.responseType.toLowerCase();\n // JSON responses need to be processed as text. This is because if the server\n // returns an XSSI-prefixed JSON response, the browser will fail to parse it,\n // xhr.response will be null, and xhr.responseText cannot be accessed to\n // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON\n // is parsed by first requesting text and then applying JSON.parse.\n xhr.responseType = ((responseType !== 'json') ? responseType : 'text');\n }\n // Serialize the request body if one is present. If not, this will be set to null.\n const reqBody = req.serializeBody();\n // If progress events are enabled, response headers will be delivered\n // in two events - the HttpHeaderResponse event and the full HttpResponse\n // event. However, since response headers don't change in between these\n // two events, it doesn't make sense to parse them twice. So headerResponse\n // caches the data extracted from the response whenever it's first parsed,\n // to ensure parsing isn't duplicated.\n let headerResponse = null;\n // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest\n // state, and memoizes it into headerResponse.\n const partialFromXhr = () => {\n if (headerResponse !== null) {\n return headerResponse;\n }\n // Read status and normalize an IE9 bug (https://bugs.jquery.com/ticket/1450).\n const status = xhr.status === 1223 ? 204 : xhr.status;\n const statusText = xhr.statusText || 'OK';\n // Parse headers from XMLHttpRequest - this step is lazy.\n const headers = new HttpHeaders(xhr.getAllResponseHeaders());\n // Read the response URL from the XMLHttpResponse instance and fall back on the\n // request URL.\n const url = getResponseUrl(xhr) || req.url;\n // Construct the HttpHeaderResponse and memoize it.\n headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });\n return headerResponse;\n };\n // Next, a few closures are defined for the various events which XMLHttpRequest can\n // emit. This allows them to be unregistered as event listeners later.\n // First up is the load event, which represents a response being fully available.\n const onLoad = () => {\n // Read response state from the memoized partial data.\n let { headers, status, statusText, url } = partialFromXhr();\n // The body will be read out if present.\n let body = null;\n if (status !== 204) {\n // Use XMLHttpRequest.response if set, responseText otherwise.\n body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;\n }\n // Normalize another potential bug (this one comes from CORS).\n if (status === 0) {\n status = !!body ? 200 : 0;\n }\n // ok determines whether the response will be transmitted on the event or\n // error channel. Unsuccessful status codes (not 2xx) will always be errors,\n // but a successful status code can still result in an error if the user\n // asked for JSON data and the body cannot be parsed as such.\n let ok = status >= 200 && status < 300;\n // Check whether the body needs to be parsed as JSON (in many cases the browser\n // will have done that already).\n if (req.responseType === 'json' && typeof body === 'string') {\n // Save the original body, before attempting XSSI prefix stripping.\n const originalBody = body;\n body = body.replace(XSSI_PREFIX, '');\n try {\n // Attempt the parse. If it fails, a parse error should be delivered to the user.\n body = body !== '' ? JSON.parse(body) : null;\n }\n catch (error) {\n // Since the JSON.parse failed, it's reasonable to assume this might not have been a\n // JSON response. Restore the original body (including any XSSI prefix) to deliver\n // a better error response.\n body = originalBody;\n // If this was an error request to begin with, leave it as a string, it probably\n // just isn't JSON. Otherwise, deliver the parsing error to the user.\n if (ok) {\n // Even though the response status was 2xx, this is still an error.\n ok = false;\n // The parse error contains the text of the body that failed to parse.\n body = { error, text: body };\n }\n }\n }\n if (ok) {\n // A successful response is delivered on the event stream.\n observer.next(new HttpResponse({\n body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n // The full body has been received and delivered, no further events\n // are possible. This request is complete.\n observer.complete();\n }\n else {\n // An unsuccessful request is delivered on the error channel.\n observer.error(new HttpErrorResponse({\n // The error in this case is the response body (error from the server).\n error: body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n }\n };\n // The onError callback is called when something goes wrong at the network level.\n // Connection timeout, DNS error, offline, etc. These are actual errors, and are\n // transmitted on the error channel.\n const onError = (error) => {\n const { url } = partialFromXhr();\n const res = new HttpErrorResponse({\n error,\n status: xhr.status || 0,\n statusText: xhr.statusText || 'Unknown Error',\n url: url || undefined,\n });\n observer.error(res);\n };\n // The sentHeaders flag tracks whether the HttpResponseHeaders event\n // has been sent on the stream. This is necessary to track if progress\n // is enabled since the event will be sent on only the first download\n // progerss event.\n let sentHeaders = false;\n // The download progress event handler, which is only registered if\n // progress events are enabled.\n const onDownProgress = (event) => {\n // Send the HttpResponseHeaders event if it hasn't been sent already.\n if (!sentHeaders) {\n observer.next(partialFromXhr());\n sentHeaders = true;\n }\n // Start building the download progress event to deliver on the response\n // event stream.\n let progressEvent = {\n type: HttpEventType.DownloadProgress,\n loaded: event.loaded,\n };\n // Set the total number of bytes in the event if it's available.\n if (event.lengthComputable) {\n progressEvent.total = event.total;\n }\n // If the request was for text content and a partial response is\n // available on XMLHttpRequest, include it in the progress event\n // to allow for streaming reads.\n if (req.responseType === 'text' && !!xhr.responseText) {\n progressEvent.partialText = xhr.responseText;\n }\n // Finally, fire the event.\n observer.next(progressEvent);\n };\n // The upload progress event handler, which is only registered if\n // progress events are enabled.\n const onUpProgress = (event) => {\n // Upload progress events are simpler. Begin building the progress\n // event.\n let progress = {\n type: HttpEventType.UploadProgress,\n loaded: event.loaded,\n };\n // If the total number of bytes being uploaded is available, include\n // it.\n if (event.lengthComputable) {\n progress.total = event.total;\n }\n // Send the event.\n observer.next(progress);\n };\n // By default, register for load and error events.\n xhr.addEventListener('load', onLoad);\n xhr.addEventListener('error', onError);\n xhr.addEventListener('timeout', onError);\n xhr.addEventListener('abort', onError);\n // Progress events are only enabled if requested.\n if (req.reportProgress) {\n // Download progress is always enabled if requested.\n xhr.addEventListener('progress', onDownProgress);\n // Upload progress depends on whether there is a body to upload.\n if (reqBody !== null && xhr.upload) {\n xhr.upload.addEventListener('progress', onUpProgress);\n }\n }\n // Fire the request, and notify the event stream that it was fired.\n xhr.send(reqBody);\n observer.next({ type: HttpEventType.Sent });\n // This is the return from the Observable function, which is the\n // request cancellation handler.\n return () => {\n // On a cancellation, remove all registered event listeners.\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('abort', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onError);\n if (req.reportProgress) {\n xhr.removeEventListener('progress', onDownProgress);\n if (reqBody !== null && xhr.upload) {\n xhr.upload.removeEventListener('progress', onUpProgress);\n }\n }\n // Finally, abort the in-flight request.\n if (xhr.readyState !== xhr.DONE) {\n xhr.abort();\n }\n };\n });\n }", "handle(req) {\n // Quick check to give a better error message when a user attempts to use\n // HttpClient.jsonp() without installing the HttpClientJsonpModule\n if (req.method === 'JSONP') {\n throw new Error(`Attempted to construct Jsonp request without HttpClientJsonpModule installed.`);\n }\n // Everything happens on Observable subscription.\n return new rxjs__WEBPACK_IMPORTED_MODULE_1__[\"Observable\"]((observer) => {\n // Start by setting up the XHR object with request method, URL, and withCredentials flag.\n const xhr = this.xhrFactory.build();\n xhr.open(req.method, req.urlWithParams);\n if (!!req.withCredentials) {\n xhr.withCredentials = true;\n }\n // Add all the requested headers.\n req.headers.forEach((name, values) => xhr.setRequestHeader(name, values.join(',')));\n // Add an Accept header if one isn't present already.\n if (!req.headers.has('Accept')) {\n xhr.setRequestHeader('Accept', 'application/json, text/plain, */*');\n }\n // Auto-detect the Content-Type header if one isn't present already.\n if (!req.headers.has('Content-Type')) {\n const detectedType = req.detectContentTypeHeader();\n // Sometimes Content-Type detection fails.\n if (detectedType !== null) {\n xhr.setRequestHeader('Content-Type', detectedType);\n }\n }\n // Set the responseType if one was requested.\n if (req.responseType) {\n const responseType = req.responseType.toLowerCase();\n // JSON responses need to be processed as text. This is because if the server\n // returns an XSSI-prefixed JSON response, the browser will fail to parse it,\n // xhr.response will be null, and xhr.responseText cannot be accessed to\n // retrieve the prefixed JSON data in order to strip the prefix. Thus, all JSON\n // is parsed by first requesting text and then applying JSON.parse.\n xhr.responseType = ((responseType !== 'json') ? responseType : 'text');\n }\n // Serialize the request body if one is present. If not, this will be set to null.\n const reqBody = req.serializeBody();\n // If progress events are enabled, response headers will be delivered\n // in two events - the HttpHeaderResponse event and the full HttpResponse\n // event. However, since response headers don't change in between these\n // two events, it doesn't make sense to parse them twice. So headerResponse\n // caches the data extracted from the response whenever it's first parsed,\n // to ensure parsing isn't duplicated.\n let headerResponse = null;\n // partialFromXhr extracts the HttpHeaderResponse from the current XMLHttpRequest\n // state, and memoizes it into headerResponse.\n const partialFromXhr = () => {\n if (headerResponse !== null) {\n return headerResponse;\n }\n // Read status and normalize an IE9 bug (https://bugs.jquery.com/ticket/1450).\n const status = xhr.status === 1223 ? 204 : xhr.status;\n const statusText = xhr.statusText || 'OK';\n // Parse headers from XMLHttpRequest - this step is lazy.\n const headers = new HttpHeaders(xhr.getAllResponseHeaders());\n // Read the response URL from the XMLHttpResponse instance and fall back on the\n // request URL.\n const url = getResponseUrl(xhr) || req.url;\n // Construct the HttpHeaderResponse and memoize it.\n headerResponse = new HttpHeaderResponse({ headers, status, statusText, url });\n return headerResponse;\n };\n // Next, a few closures are defined for the various events which XMLHttpRequest can\n // emit. This allows them to be unregistered as event listeners later.\n // First up is the load event, which represents a response being fully available.\n const onLoad = () => {\n // Read response state from the memoized partial data.\n let { headers, status, statusText, url } = partialFromXhr();\n // The body will be read out if present.\n let body = null;\n if (status !== 204) {\n // Use XMLHttpRequest.response if set, responseText otherwise.\n body = (typeof xhr.response === 'undefined') ? xhr.responseText : xhr.response;\n }\n // Normalize another potential bug (this one comes from CORS).\n if (status === 0) {\n status = !!body ? 200 : 0;\n }\n // ok determines whether the response will be transmitted on the event or\n // error channel. Unsuccessful status codes (not 2xx) will always be errors,\n // but a successful status code can still result in an error if the user\n // asked for JSON data and the body cannot be parsed as such.\n let ok = status >= 200 && status < 300;\n // Check whether the body needs to be parsed as JSON (in many cases the browser\n // will have done that already).\n if (req.responseType === 'json' && typeof body === 'string') {\n // Save the original body, before attempting XSSI prefix stripping.\n const originalBody = body;\n body = body.replace(XSSI_PREFIX, '');\n try {\n // Attempt the parse. If it fails, a parse error should be delivered to the user.\n body = body !== '' ? JSON.parse(body) : null;\n }\n catch (error) {\n // Since the JSON.parse failed, it's reasonable to assume this might not have been a\n // JSON response. Restore the original body (including any XSSI prefix) to deliver\n // a better error response.\n body = originalBody;\n // If this was an error request to begin with, leave it as a string, it probably\n // just isn't JSON. Otherwise, deliver the parsing error to the user.\n if (ok) {\n // Even though the response status was 2xx, this is still an error.\n ok = false;\n // The parse error contains the text of the body that failed to parse.\n body = { error, text: body };\n }\n }\n }\n if (ok) {\n // A successful response is delivered on the event stream.\n observer.next(new HttpResponse({\n body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n // The full body has been received and delivered, no further events\n // are possible. This request is complete.\n observer.complete();\n }\n else {\n // An unsuccessful request is delivered on the error channel.\n observer.error(new HttpErrorResponse({\n // The error in this case is the response body (error from the server).\n error: body,\n headers,\n status,\n statusText,\n url: url || undefined,\n }));\n }\n };\n // The onError callback is called when something goes wrong at the network level.\n // Connection timeout, DNS error, offline, etc. These are actual errors, and are\n // transmitted on the error channel.\n const onError = (error) => {\n const { url } = partialFromXhr();\n const res = new HttpErrorResponse({\n error,\n status: xhr.status || 0,\n statusText: xhr.statusText || 'Unknown Error',\n url: url || undefined,\n });\n observer.error(res);\n };\n // The sentHeaders flag tracks whether the HttpResponseHeaders event\n // has been sent on the stream. This is necessary to track if progress\n // is enabled since the event will be sent on only the first download\n // progerss event.\n let sentHeaders = false;\n // The download progress event handler, which is only registered if\n // progress events are enabled.\n const onDownProgress = (event) => {\n // Send the HttpResponseHeaders event if it hasn't been sent already.\n if (!sentHeaders) {\n observer.next(partialFromXhr());\n sentHeaders = true;\n }\n // Start building the download progress event to deliver on the response\n // event stream.\n let progressEvent = {\n type: HttpEventType.DownloadProgress,\n loaded: event.loaded,\n };\n // Set the total number of bytes in the event if it's available.\n if (event.lengthComputable) {\n progressEvent.total = event.total;\n }\n // If the request was for text content and a partial response is\n // available on XMLHttpRequest, include it in the progress event\n // to allow for streaming reads.\n if (req.responseType === 'text' && !!xhr.responseText) {\n progressEvent.partialText = xhr.responseText;\n }\n // Finally, fire the event.\n observer.next(progressEvent);\n };\n // The upload progress event handler, which is only registered if\n // progress events are enabled.\n const onUpProgress = (event) => {\n // Upload progress events are simpler. Begin building the progress\n // event.\n let progress = {\n type: HttpEventType.UploadProgress,\n loaded: event.loaded,\n };\n // If the total number of bytes being uploaded is available, include\n // it.\n if (event.lengthComputable) {\n progress.total = event.total;\n }\n // Send the event.\n observer.next(progress);\n };\n // By default, register for load and error events.\n xhr.addEventListener('load', onLoad);\n xhr.addEventListener('error', onError);\n xhr.addEventListener('timeout', onError);\n // Progress events are only enabled if requested.\n if (req.reportProgress) {\n // Download progress is always enabled if requested.\n xhr.addEventListener('progress', onDownProgress);\n // Upload progress depends on whether there is a body to upload.\n if (reqBody !== null && xhr.upload) {\n xhr.upload.addEventListener('progress', onUpProgress);\n }\n }\n // Fire the request, and notify the event stream that it was fired.\n xhr.send(reqBody);\n observer.next({ type: HttpEventType.Sent });\n // This is the return from the Observable function, which is the\n // request cancellation handler.\n return () => {\n // On a cancellation, remove all registered event listeners.\n xhr.removeEventListener('error', onError);\n xhr.removeEventListener('load', onLoad);\n xhr.removeEventListener('timeout', onError);\n if (req.reportProgress) {\n xhr.removeEventListener('progress', onDownProgress);\n if (reqBody !== null && xhr.upload) {\n xhr.upload.removeEventListener('progress', onUpProgress);\n }\n }\n // Finally, abort the in-flight request.\n if (xhr.readyState !== xhr.DONE) {\n xhr.abort();\n }\n };\n });\n }" ]
[ "0.70661414", "0.68868506", "0.68868506", "0.68868506", "0.68868506", "0.68868506", "0.6664952", "0.65963316", "0.6553913", "0.649558", "0.64951473", "0.6475253", "0.6437685", "0.64230907", "0.6414247", "0.63993824", "0.63648355", "0.63594586", "0.6279924", "0.6275586", "0.6219295", "0.62005115", "0.6175583", "0.61677766", "0.6138087", "0.6109352", "0.609788", "0.60611534", "0.60511446", "0.6050582", "0.6020028", "0.5960969", "0.5950256", "0.59444577", "0.5933644", "0.5904041", "0.5904041", "0.5904041", "0.5904041", "0.5904041", "0.587751", "0.57828945", "0.5782571", "0.5773272", "0.5764598", "0.5739793", "0.5734525", "0.5674996", "0.56648934", "0.5600976", "0.5587655", "0.5587655", "0.55867743", "0.5571361", "0.55506897", "0.55351704", "0.55221564", "0.55221564", "0.55221564", "0.55221564", "0.55221564", "0.5520493", "0.5516147", "0.55011016", "0.5499631", "0.54949665", "0.5492666", "0.5483628", "0.5480426", "0.5480426", "0.5480426", "0.5480426", "0.5480426", "0.54647493", "0.5459338", "0.54586077", "0.5443947", "0.54428196", "0.54251385", "0.5418511", "0.5415573", "0.53893405", "0.53877705", "0.53799546", "0.5377154", "0.53749233", "0.53703964", "0.53702277", "0.5365159", "0.535766", "0.5336891", "0.5331315", "0.53290075", "0.53290075", "0.53134584", "0.531131", "0.5308241", "0.5297862", "0.5297862", "0.5297862", "0.5297862" ]
0.0
-1
isSubmited: boolean = false;
function ForgotPasswordComponent(fb, userService, router) { this.fb = fb; this.userService = userService; this.router = router; this.data = []; this.isSubmited = false; this.msgs = []; this.forgotPasswordForm = this.fb.group({ email: [null, __WEBPACK_IMPORTED_MODULE_1__angular_forms__["Validators"].required] }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set isSubmit(value) {\n this.data.set('submit', value);\n }", "set isSubmit(value) {\n this.data.set('submit', value);\n }", "enableSubmit() {\n this.wasChange = true;\n }", "enableSubmit() {\n this._disableSubmit = false;\n }", "function enableSubmitEvent() {\r\n $(\"#submit\").prop(\"\", !canSubmit()); \r\n}", "enableSubmit() {\n\t\tlet enabled = this.project.name.length > 0 && this.project.id.length > 0 && this.project.platforms.length > 0 && this.state.locationExists === false;\n\t\tif (this.state.submitButtonEnabled !== enabled) {\n\t\t\tthis.state.submitButtonEnabled = enabled;\n\t\t\tetch.update(this);\n\t\t}\n\t}", "enableButton() {\n this.setState({\n canSubmit: true,\n });\n }", "_shouldSubmitMessage() {\n if (this.message) this.__shouldSubmitMessage = true;\n }", "function toggleSubmit() {\n\t'use strict';\n \n} // End of toggleSubmit() function.", "isValid() {\n return this.validation.isValid && !this.props.posting\n }", "handleFormSubmit() {\n // Show spinner\n this.isSaving = true;\n }", "formSubmit() {\n return !(this.state.steps[0].Name === '' || this.state.steps[0].args === '' || this.state.steps[0].jar === '' )\n }", "enableSubmit() {\n\t\tlet enabled = this.login.username.length > 0 && this.login.password.length > 0;\n\t\tif (this.state.submitButtonEnabled !== enabled) {\n\t\t\tthis.state.submitButtonEnabled = enabled;\n\t\t\tetch.update(this);\n\t\t}\n\t}", "function submitPressed() {\n \n}", "function refreshSubmitButtonState() {\n disableSubmit(!formIsValid());\n}", "doSubmit(isSubmitButton, submit) {\n const { \n handleSubmit, onSubmit, change, reset\n } = this.props;\n\n change('conceptSubmission.hasSubmitted', submit);\n\n handleSubmit(values => {\n const trimmedText = values.conceptSubmission.text.trim();\n if (isSubmitButton && submit && !trimmedText.length) {\n return false;\n }\n const newValues = merge({}, values, {\n conceptSubmission: { \n hasSubmitted: submit,\n text: trimmedText\n }\n });\n\n return onSubmit(newValues);\n })();\n // handleSubmit();\n reset();\n }", "postClick() {\n this.setState({postForm: !this.state.postForm})\n }", "get allowsPosting()\n\t{\n\t\treturn true;\n\t}", "function toggleSubmit() {\n 'use strict';\n\n} // End of toggleSubmit() function.", "preventSubmitIfAlreadyInProgress() {\n }", "disableButton() {\n this.setState({\n canSubmit: false,\n });\n }", "function onlySubmit(){\r\n disableButtons() // make sure you can only press the save button once\r\n document.getElementById('evaluationForm').submit();\r\n }", "preventSubmitIfUploading() {\n }", "submit() {}", "function canSubmitForm()\n{\n return !isOriginDecodePending && !isDestinationDecodePending && !isDirectionsPending;\n}", "onSubmitReview(event, index) {\n console.log(\"do you see me?\")\n // change boolean of state is_review_submitted to T\n this.setState({\n // change to true, not ! because only 1 submission needed\n is_rating_submitted: true,\n })\n }", "isUploading () {\n // return <Boolean>\n console.log(\"isUploading called\")\n }", "function toggleSubmit () {\n if (configuration.submit && configuration.disableSubmit) {\n nod.getElements(configuration.submit).forEach(function (submitBtn) {\n submitBtn.disabled = !areAll(nod.constants.VALID);\n });\n }\n }", "submit() {\n }", "onSubmit() {\n this._submit.classList.add('button--disabled');\n location.reload();\n if (this.isValid())\n this.props.submit ? this.props.submit(this.form) : null;\n }", "emptyCardFormSubmit() {\n return false;\n }", "function toggleButton() {\n if (formIsValid) {\n submitBtn.disabled = false\n } else {\n submitBtn.disabled = true\n }\n}", "submitForm() {\n this.setState({form_err: true});\n }", "function enableSubmitButton() {\n show(\"validate\");\n hide(\"formIsUnvalide\");\n}", "function submitController(){\n if (errors.nombre|| errors.primerEscrito || errors.primerParcial || errors.segundoEscrito || errors.segundoParcial || errors.tercerEscrito || errors.faltas) {\n submitButton.toggleAttribute('disabled', true)\n } else {\n submitButton.toggleAttribute('disabled', false)\n }\n}", "preventSubmitUnlessValid() {\n }", "function toggleSubmission() {\n\n let form = document.getElementById('newMessageForm');\n if (form.style.display === 'none') return form.style.display = 'block';\n else form.style.display = 'none';\n}", "[form.mutation.FINISHED] (state) {\n state.submitted = false\n }", "function submitonce()\n{\n\t_formSubmitted = true;\n\n\t// If there are any editors warn them submit is coming!\n\t$.each(weEditors, function () { this.doSubmit(); });\n}", "function Button_Click(e)\r\n{\r\n\t//trace(\"Button_Click\");\r\n\tvar res = e.Submit();\r\n\ttrace( \"Submit res=\" + res);\r\n\t\r\n\t//Place above code in if statment below if you want to only submit once\t\r\n/*\tif ( !e.IsSubmitted() )\r\n\t{\t\r\n\t//\tconsole.log(\"!\"+ e+\".IsSubmitted()\");\r\n\t}*/\r\n}", "function updateSubmitable() {\n const able = nameInput.value.length >= 2 && avatarFile &&\n avatarFile.byteLength > 0;\n submit.disabled = !able;\n }", "get skip_submission() {\n return this._skip_submission;\n }", "toggle() {\n this.save({ done: !this.get(\"done\") });\n }", "function submit_fillter(){\n\n\t}", "handleSubmit(evt) {\n evt.preventDefault();\n this.props.onSubmit(this.state);\n this.setState({\n title: '',\n creator: '',\n genre: '',\n episodes: '',\n description: '',\n trailer_url: '',\n poster_url: 'https://static.thenounproject.com/png/187803-200.png'\n })\n this.props.toggle('createModal');\n }", "function enableSubmit(){\n submitSection.show()\n errorSection.hide()\n }", "function enableSubmit() {\n submitButton.removeAttribute('disabled');\n }", "checkReadyForSubmit(){\n if(this.checkAnswersReady() && this.checkAddressReady() && this.checkMembership()){\n return true;\n }\n else{\n return false;\n }\n }", "submitExtra() {\n }", "handleSubmit(event, user) {\n event.preventDefault(); \n DBPost.save(this.state, user.uid).then((ready) => { \n //Cleanup form when post is successful ...\n this.setState((prevState, props) => {\n return {\n title: '',\n content: ''\n }\n }); \n });\n this.props.toggle();\n }", "function enableSubmitTrigger() {\n var tstk;\n tstk = new TSTranslateKhmer(FormApp.getActiveForm()).setFormTrigger('checkResponses');\n FormApp.getUi().alert('Form Submit Trigger has been enabled.');\n}", "setCreatePost(e, boolValue) {\n this.setState({\n createPost: boolValue\n });\n }", "setCompleted() {\nreturn this.isComplete = true;\n}", "function checkActivateSubmit(){\n if(validLibFile &&\n document.inputForm.username.value &&\n document.inputForm.matchThreshold.value!='default' && \n validTopTracks()){\n $(document.getElementById(\"submitBtn\")).attr(\"disabled\", false);\n }\n else {\n $(document.getElementById(\"submitBtn\")).attr(\"disabled\", true);\n }\n}", "function handleSubmitButton () {\n $('#quiz-form').submit(function (event) {\n event.preventDefault();\n console.log('js-submit-btn was clicked.');\n if (store.submitBtnClicked === false) {\n store.submitBtnClicked = true;\n console.log(store.submitBtnClicked);\n checkCorrectAnswer();\n updateCounter();\n }\n });\n}", "if (!this.state.saving) {\n this.handleToggle()\n }", "function showSubmitButton() {\n if(CLICKED) {\n submitButton.style().set('shown', true);\n }\n}", "function submitonce(theform)\n{\n\tsmf_formSubmitted = true;\n}", "function disableSubmit() {\n submitButton.setAttribute('disabled', 'disabled');\n }", "function disableSubmit() {\n document.getElementById(\"submit\").disabled = true;\n}", "handleSubmit() {\n return this.state;\n }", "[form.mutation.SUBMITTED] (state) {\n state.submitted = true\n state.notification = null\n state.errors = []\n state.success = null\n }", "review() {\n if (this.complete) {\n this.complete = !this.complete;\n }\n }", "submitCallback(event) {\n this.setState({\n signInCheck: true\n });\n }", "function isSubmitAction(action) {\n return action.type === 'submit';\n }", "function enableSubmit() {\n\t\t$('#submit-album-btn').prop(\"disabled\",false);\n\t}", "handleSubmitToDMS(){\n this.msgpaSelected = true;\n this.handleSave();\n }", "hasValidForm() {\n return this.formConfig !== false;\n }", "handleSubmit(e) {\n e.preventDefault();\n\n this.props.handleSubmit(this.state)\n\n // resets score form after user submits final score\n this.setState({\n team_one_score: \"\",\n team_two_score: \"\",\n team_one_name: this.props.team_one_name,\n team_two_name: this.props.team_two_name,\n saved: true\n })\n\n // hide the saved message after 2 seconds\n setTimeout(() => this.setState({ saved: false }), 2000);\n }", "function DbAddButton() {\n uploadToDb = true;\n OnSubmit();\n}", "fallback() {\n this.form.submit();\n }", "fallback() {\n this.form.submit();\n }", "function updateSubmitButtonState(form) {\n var disableSubmit = false;\n var submitButton = form.find('button[type=submit]');\n\n form.find('input[required], select[required]').each(function() {\n if (!$(this).val()) {\n disableSubmit = true;\n return false;\n }\n });\n\n disableSubmit ? submitButton.attr('disabled', '') : submitButton.removeAttr('disabled');\n }", "onSubmit() {\n console.log(\"submit form\");\n }", "valid() {\r\n return true\r\n }", "function submit() {\n updateMember(props.match.params.id, {\n userid: values.userId,\n firstname: values.fName,\n lastname: values.lName,\n mobilenumber: values.mobNo,\n homeaddress: values.homeAddr,\n email: values.email,\n password: values.password,\n });\n\n setShow(false);\n }", "onSubmitClicked() {\n this.onSubmit({\n query: this.ui\n });\n }", "function successfulSubmit() {\n console.log(\"Successful submit\");\n\n // Publish a \"form submitted\" event\n $.publish(\"successfulSubmit\");\n\n // Hide the form and show the thanks\n $('#form').slideToggle();\n $('#thanks').slideToggle();\n\n if($('#address-search-prompt').is(\":hidden\")) {\n $('#address-search-prompt').slideToggle();\n }\n if($('#address-search').is(\":visible\")) {\n $('#address-search').slideToggle();\n }\n\n // Reset the form for the next submission.\n resetForm();\n }", "function directEditFormSubmit( fm)\r\n{\r\n directEditCloseAll();\r\n return self.btnClicked != 'Cancel' &&\r\n self.btnClicked != 'Back';\r\n}", "handleDataLoaded() {\r\n this.setState({submitted: true});\r\n }", "submit() {\r\n\r\n this.inputsCheck();\r\n this.submitBtn.click(() => {\r\n this.pushToLocal();\r\n this.clearForm();\r\n\r\n })\r\n }", "function uSubmit(inp)\n{\n if (uUseApplets)\n {\n retVal = uLastClick;\n uLastClick = false;\n return(retVal);\n }\n else\n {\n return true;\n }\n}", "showAddForm() {\n this.setState({\n shouldShowAddForm: true,\n });\n }", "handleSubmit() {\n const { values } = this.formApi.getState()\n\n this.setState({ submitting: true })\n\n fetch(this.apiRoute('posts'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ application: values }),\n }).then(response => console.info(response.ok \n ? msg('submission successful')\n : msg('submission failed')\n )).then(() => this.setState({ submitting: false }))\n }", "function\n\tenableFieldsetSubmit(element)\n\t{ \n\n\t\tvar submitButton = element.closest('.submit-container').querySelector('.trigger-submit-fieldset');\n\t\t\tsubmitButton.disabled = !element.checked;\n\t}", "set skip_submission(value) {\n this._skip_submission = value;\n }", "function submitButtonPressed()\n{\n if(validateColumn())\n submit();\n \n}", "isValid() {\n return true;\n }", "isValid() {\n return true;\n }", "function disableSubmitButton() {\n\tdocument.getElementById(\"submit-button\").disabled = true;\n\tdocument.getElementById(\"save-button\").style.visibility = \"visible\";\n\tdocument.getElementById(\"submission-message\").style.visibility = \"hidden\";\n\n}", "function beforeAssetSubmit(formData, jqForm, options) {\n\n return true;\n }", "handleAddSubmit() {}", "function on_user_hit_submit()\r\n{\r\n $(\"#user_hit_submit\").val(\"1\")\r\n $(\"#submit_button\").attr('disabled', 'disabled')\r\n $(\"#submit_button2\").attr('disabled', 'disabled')\r\n $(\"#submit_button\").val(\"Please wait...\")\r\n $(\"#submit_button2\").val(\"Please wait...\")\r\n var btn = document.getElementById(\"submit_button\")\r\n btn.form.submit()\r\n\t\r\n}", "function toggleNewPost(){\n Session.set('writingPost', writingPost = !writingPost);\n}", "handleSubmit() {\n this.submitForm();\n }", "function onFormSubmit(event) {\n event.preventDefault();\n let user\n}", "togglePostField() {\n this.setState({ toggleInput: !this.state.toggleInput });\n }", "submit() {\n if (this.state.good === 'good') {\n return {\n response: {\n key: this.props.info.name,\n value: this.state.value\n },\n ready: true\n };\n } else {\n this.state.good = 'watch';\n return {\n ready: false\n };\n }\n }", "function isFormUpdateEventHandler( event ){\n const form = event.target.closest(\"form\");\n const isFormUpdate = document.createElement(\"input\");\n isFormUpdate.type = \"hidden\";\n isFormUpdate.name = \"is_form_update\";\n isFormUpdate.value = 'True'\n form.appendChild(isFormUpdate);\n form.querySelectorAll('[type=submit]')[0].click();\n}", "static postUpdate() {\n return false;\n }", "_testSubmitMessage() {\n if (this.__shouldSubmitMessage) this._submitMessage();\n this.__shouldSubmitMessage = false;\n }" ]
[ "0.754355", "0.754355", "0.72813183", "0.7166593", "0.69735515", "0.69401044", "0.6938561", "0.6898109", "0.6886757", "0.68463147", "0.68433774", "0.6742062", "0.6720877", "0.6702317", "0.6676985", "0.66761696", "0.659592", "0.65885967", "0.6578654", "0.65744793", "0.65628463", "0.65113896", "0.6500483", "0.6477368", "0.64545786", "0.6422309", "0.64165044", "0.6412185", "0.6409669", "0.63360345", "0.63259006", "0.63008016", "0.6274132", "0.62586665", "0.62546223", "0.6241287", "0.6234212", "0.6182228", "0.6170615", "0.6157307", "0.6115999", "0.61121434", "0.60923034", "0.6065924", "0.60564137", "0.60393083", "0.60370076", "0.6036891", "0.60254294", "0.6024722", "0.6012936", "0.5998388", "0.5985787", "0.59831715", "0.59698653", "0.5949323", "0.59452456", "0.5934902", "0.5933766", "0.59331334", "0.59306836", "0.59281766", "0.592317", "0.5920216", "0.5917581", "0.5898913", "0.5897852", "0.588676", "0.58846873", "0.5876334", "0.5864422", "0.5864422", "0.58580095", "0.5855203", "0.58548516", "0.5854605", "0.58537537", "0.584345", "0.5840601", "0.5839584", "0.58374566", "0.5826162", "0.5819285", "0.5806452", "0.5799804", "0.57981366", "0.57852113", "0.57759345", "0.57759345", "0.57748127", "0.57740015", "0.5773672", "0.5764697", "0.5760617", "0.5759985", "0.5752479", "0.57520413", "0.57475686", "0.57410824", "0.57403004", "0.57389474" ]
0.0
-1
vuex v3.1.0 (c) 2019 Evan You
function r(t){var e=Number(t.version.split(".")[0]);if(e>=2)t.mixin({beforeCreate:r});else{var n=t.prototype._init;t.prototype._init=function(t){void 0===t&&(t={}),t.init=t.init?[r].concat(t.init):r,n.call(this,t)}}function r(){var t=this.$options;t.store?this.$store="function"===typeof t.store?t.store():t.store:t.parent&&t.parent.$store&&(this.$store=t.parent.$store)}}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getFieldVuex() {\n return store.getters.dataField;\n }", "function vuexInit(){var options=this.$options;// store injection\n\tif(options.store){this.$store=options.store;}else if(options.parent&&options.parent.$store){this.$store=options.parent.$store;}}", "function U(He){Le&&(He._devtoolHook=Le,Le.emit('vuex:init',He),Le.on('vuex:travel-to-state',function(Ne){He.replaceState(Ne)}),He.subscribe(function(Ne,je){Le.emit('vuex:mutation',Ne,je)}))}", "getProfileVuex() {\n return store.getters.dataProfile;\n }", "function vuexInit() {\n\t var options = this.$options;\n\t var store = options.store;\n\t var vuex = options.vuex;\n\t // store injection\n\t\n\t if (store) {\n\t this.$store = store;\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store;\n\t }\n\t // vuex option handling\n\t if (vuex) {\n\t if (!this.$store) {\n\t console.warn('[vuex] store not injected. make sure to ' + 'provide the store option in your root component.');\n\t }\n\t var state = vuex.state;\n\t var getters = vuex.getters;\n\t var actions = vuex.actions;\n\t // handle deprecated state option\n\t\n\t if (state && !getters) {\n\t console.warn('[vuex] vuex.state option will been deprecated in 1.0. ' + 'Use vuex.getters instead.');\n\t getters = state;\n\t }\n\t // getters\n\t if (getters) {\n\t options.computed = options.computed || {};\n\t for (var key in getters) {\n\t defineVuexGetter(this, key, getters[key]);\n\t }\n\t }\n\t // actions\n\t if (actions) {\n\t options.methods = options.methods || {};\n\t for (var _key in actions) {\n\t options.methods[_key] = makeBoundAction(this.$store, actions[_key], _key);\n\t }\n\t }\n\t }\n\t }", "function vuexInit () {\n\t var options = this.$options;\n\t // store injection\n\t if (options.store) {\n\t this.$store = options.store;\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store;\n\t }\n\t }", "function vuexInit () {\n\t var options = this.$options;\n\t // store injection\n\t if (options.store) {\n\t this.$store = options.store;\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store;\n\t }\n\t }", "function vuexInit () {\n\t var options = this.$options;\n\t // store injection\n\t if (options.store) {\n\t this.$store = options.store;\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store;\n\t }\n\t }", "function vuexInit () {\n\t var options = this.$options\n\t // store injection\n\t if (options.store) {\n\t this.$store = options.store\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store\n\t }\n\t }", "function vuexInit () {\n\t var options = this.$options;\n\t // store injection\n\t if (options.store) {\n\t this.$store = typeof options.store === 'function'\n\t ? options.store()\n\t : options.store;\n\t } else if (options.parent && options.parent.$store) {\n\t this.$store = options.parent.$store;\n\t }\n\t }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\r\n var options = this.$options;\r\n // store injection\r\n if (options.store) {\r\n this.$store = typeof options.store === 'function'\r\n ? options.store()\r\n : options.store;\r\n } else if (options.parent && options.parent.$store) {\r\n this.$store = options.parent.$store;\r\n }\r\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexlocal() {\n return store => {\n // 判断是否有本地缓存如果有就取本地缓存的如果没有就取自身初始值\n let local = JSON.parse(localStorage.getItem('myVuex')) || store.replaceState(state)\n store.replaceState(local); // 替换state的数据\n store.subscribe((mutation,state) => { // 监听\n // 替换之前先取一次防止数据丢失\n let newstate = JSON.parse(JSON.stringify(state))\n localStorage.setItem('myVuex',JSON.stringify(newstate))\n })\n }\n}", "loadVuex() {\n let keys = Object.keys(settings)\n keys.forEach(this.__loadVuexModule)\n }", "getTokenVuex() {\n return store.getters.jwt;\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function' ? options.store() : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function' ? options.store() : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function' ? options.store() : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function' ? options.store() : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit() {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function' ? options.store() : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function t(e){var l=Number(e.version.split(\".\")[0]);if(l>=2)e.mixin({beforeCreate:t});else{var a=e.prototype._init;e.prototype._init=function(e){void 0===e&&(e={}),e.init=e.init?[t].concat(e.init):t,a.call(this,e)}}function t(){var e=this.$options;e.store?this.$store=\"function\"===typeof e.store?e.store():e.store:e.parent&&e.parent.$store&&(this.$store=e.parent.$store)}}", "users() {\n return this.$store.getters.users\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }", "function vuexInit () {\n var options = this.$options;\n // store injection\n if (options.store) {\n this.$store = typeof options.store === 'function'\n ? options.store()\n : options.store;\n } else if (options.parent && options.parent.$store) {\n this.$store = options.parent.$store;\n }\n }" ]
[ "0.7099906", "0.6993732", "0.6736782", "0.6719839", "0.66230166", "0.661622", "0.661622", "0.661622", "0.6585128", "0.6483413", "0.6353763", "0.6346337", "0.6339407", "0.6339407", "0.6339407", "0.6339407", "0.6339407", "0.6328541", "0.6301164", "0.62952876", "0.62822306", "0.62456834", "0.62456834", "0.62456834", "0.62456834", "0.62456834", "0.62410665", "0.62409353", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191", "0.6223191" ]
0.0
-1
! vuerouter v3.0.2 (c) 2018 Evan You
function r(t,e){0}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "private public function m246() {}", "private internal function m248() {}", "function jj(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"source.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function TM(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"source.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function BO(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"source.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function version(){ return \"0.13.0\" }", "function Es(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"source.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function fyv(){\n \n }", "function Qw(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "transient private internal function m185() {}", "function yh(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"graticule.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "vampireWithName(name) {\n \n }", "function iP(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"source.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function Uk(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "upgrade() {}", "updated() {}", "protected internal function m252() {}", "function cO(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"source.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function vT(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"layer.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "transient final protected internal function m174() {}", "function SigV4Utils() { }", "function Wx(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "constructor() {\n \n\n \n \n\n \n\n \n }", "added(vrobject){}", "transient protected internal function m189() {}", "function ow(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function Ak(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "transient private protected internal function m182() {}", "function Bv(e){let{basename:t,children:n,window:r}=e,l=X.exports.useRef();l.current==null&&(l.current=gv({window:r}));let o=l.current,[i,u]=X.exports.useState({action:o.action,location:o.location});return X.exports.useLayoutEffect(()=>o.listen(u),[o]),X.exports.createElement(Fv,{basename:t,children:n,location:i.location,navigationType:i.action,navigator:o})}", "function VI(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"layer.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function Rb(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function comportement (){\n\t }", "function jx(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function dp(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function Ek(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function PD(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "__previnit(){}", "function uf(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"layer.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function Hr(e,t){\"undefined\"!==typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "function hA(t,e,n,i,r,o,a,s){var u=(\"function\"===typeof n?n.options:n)||{};return u.__file=\"geom.vue\",u.render||(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0,r&&(u.functional=!0)),u._scopeId=i,u}", "function Bevy() {}", "function JV(e,t){\"undefined\"!=typeof console&&(console.warn(\"[vue-i18n] \"+e),t&&console.warn(t.stack))}", "transient final private internal function m170() {}", "function $S(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"geom.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "function vI(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"style.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "init() {\n }", "function Vt(){this.__data__=[]}", "function VO(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};VO.installed||(VO.installed=!0,t.use(i,e),t.use(r,e),t.use(o,e),t.use(a,e),t.use(s,e),t.use(u,e),t.use(l,e),t.use(c,e),t.use(d,e),t.use(h,e),t.use(f,e),t.use(p,e),t.use(m,e),t.use(v,e),t.use(g,e),t.use(_,e),t.use(y,e),t.use(b,e),t.use(x,e),t.use(w,e),t.use(A,e),t.use(M,e),t.use(S,e),t.use(T,e),t.use(k,e),t.use(O,e),t.use(C,e),t.use(L,e),t.use(E,e),t.use(D,e),t.use(j,e),t.use(I,e),t.use(P,e),t.use(Y,e),t.use(F,e),t.use(R,e),t.use(N,e),t.use(B,e),t.use($,e),t.use(z,e),t.use(H,e),t.use(V,e),t.use(G,e))}", "function ea(){}", "transient final private protected internal function m167() {}", "static get tag(){return\"hal-9000\"}", "static final private internal function m106() {}", "function vinewx(t=\"untitled\",s=!1){return new class{constructor(t,s){this.name=t,this.debug=s,this.isQX=\"undefined\"!=typeof $task,this.isLoon=\"undefined\"!=typeof $loon,this.isSurge=\"undefined\"!=typeof $httpClient&&!this.isLoon,this.isNode=\"function\"==typeof require,this.isJSBox=this.isNode&&\"undefined\"!=typeof $jsbox,this.node=(()=>this.isNode?{request:\"undefined\"!=typeof $request?void 0:require(\"request\"),fs:require(\"fs\")}:null)(),this.cache=this.initCache(),this.log(`INITIAL CACHE:\\n${JSON.stringify(this.cache)}`),Promise.prototype.delay=function(t){return this.then(function(s){return((t,s)=>new Promise(function(e){setTimeout(e.bind(null,s),t)}))(t,s)})}}get(t){return this.isQX?(\"string\"==typeof t&&(t={url:t,method:\"GET\"}),$task.fetch(t)):new Promise((s,e)=>{this.isLoon||this.isSurge?$httpClient.get(t,(t,i,o)=>{t?e(t):s({status:i.status,headers:i.headers,body:o})}):this.node.request(t,(t,i,o)=>{t?e(t):s({...i,status:i.statusCode,body:o})})})}post(t){return this.isQX?(\"string\"==typeof t&&(t={url:t}),t.method=\"POST\",$task.fetch(t)):new Promise((s,e)=>{this.isLoon||this.isSurge?$httpClient.post(t,(t,i,o)=>{t?e(t):s({status:i.status,headers:i.headers,body:o})}):this.node.request.post(t,(t,i,o)=>{t?e(t):s({...i,status:i.statusCode,body:o})})})}initCache(){if(this.isQX)return JSON.parse($prefs.valueForKey(this.name)||\"{}\");if(this.isLoon||this.isSurge)return JSON.parse($persistentStore.read(this.name)||\"{}\");if(this.isNode){const t=`${this.name}.json`;return this.node.fs.existsSync(t)?JSON.parse(this.node.fs.readFileSync(`${this.name}.json`)):(this.node.fs.writeFileSync(t,JSON.stringify({}),{flag:\"wx\"},t=>console.log(t)),{})}}persistCache(){const t=JSON.stringify(this.cache);this.log(`FLUSHING DATA:\\n${t}`),this.isQX&&$prefs.setValueForKey(t,this.name),(this.isLoon||this.isSurge)&&$persistentStore.write(t,this.name),this.isNode&&this.node.fs.writeFileSync(`${this.name}.json`,t,{flag:\"w\"},t=>console.log(t))}write(t,s){this.log(`SET ${s} = ${JSON.stringify(t)}`),this.cache[s]=t,this.persistCache()}read(t){return this.log(`READ ${t} ==> ${JSON.stringify(this.cache[t])}`),this.cache[t]}delete(t){this.log(`DELETE ${t}`),delete this.cache[t],this.persistCache()}notify(t,s,e,i){const o=\"string\"==typeof i?i:void 0,n=e+(null==o?\"\":`\\n${o}`);this.isQX&&(void 0!==o?$notify(t,s,e,{\"open-url\":o}):$notify(t,s,e,i)),this.isSurge&&$notification.post(t,s,n),this.isLoon&&$notification.post(t,s,e),this.isNode&&(this.isJSBox?require(\"push\").schedule({title:t,body:s?s+\"\\n\"+e:e}):console.log(`${t}\\n${s}\\n${n}\\n\\n`))}log(t){this.debug&&console.log(t)}info(t){console.log(t)}error(t){console.log(\"ERROR: \"+t)}wait(t){return new Promise(s=>setTimeout(s,t))}done(t={}){this.isQX||this.isLoon||this.isSurge?$done(t):this.isNode&&!this.isJSBox&&\"undefined\"!=typeof $context&&($context.headers=t.headers,$context.statusCode=t.statusCode,$context.body=t.body)}}(t,s)}", "function Mv(){var t=this;ci()(this,{$source:{enumerable:!0,get:function(){return t.$olObject}},$map:{enumerable:!0,get:function(){return t.$services&&uu()(t.$services)}},$view:{enumerable:!0,get:function(){return t.$services&&t.$services.view}},$sourceContainer:{enumerable:!0,get:function(){return t.$services&&t.$services.sourceContainer}}})}", "static private protected internal function m118() {}", "function test_candu_graphs_datastore_vsphere6() {}", "install(Vue, options) {\n Vue.VERSION = 'v0.0.1';\n\n let userOptions = {...defaultOptions, ...options};\n // console.log(userOptions)\n\n // create a mixin\n Vue.mixin({\n // created() {\n // console.log(Vue.VERSION);\n // },\n\n\n });\n Vue.prototype.$italicHTML = function (text) {\n return '<i>' + text + '</i>';\n }\n Vue.prototype.$boldHTML = function (text) {\n return '<b>' + text + '</b>';\n }\n\n // define a global filter\n Vue.filter('preview', (value) => {\n if (!value) {\n return '';\n }\n return value.substring(0, userOptions.cutoff) + '...';\n })\n\n Vue.filter('localname', (value) => {\n if (!value) {\n return '';\n }\n var ln = value;\n if(value!= undefined){\n if ( value.lastIndexOf(\"#\") != -1) { ln = value.substr(value.lastIndexOf(\"#\")).substr(1)}\n else{ ln = value.substr(value.lastIndexOf(\"/\")).substr(1) }\n ln = ln.length == 0 ? value : ln\n }\n return ln\n })\n\n // add a custom directive\n Vue.directive('focus', {\n // When the bound element is inserted into the DOM...\n inserted: function (el) {\n // Focus the element\n el.focus();\n }\n })\n\n }", "function zC(t,e,n,r,i,o,a,s){var l=(\"function\"===typeof n?n.options:n)||{};return l.__file=\"layer.vue\",l.render||(l.render=t.render,l.staticRenderFns=t.staticRenderFns,l._compiled=!0,i&&(l.functional=!0)),l._scopeId=r,l}", "initialize() {\n\n }", "constructor() {\n \n }", "constructor() {\n \n }", "constructor() {\n \n }", "constructor() {\n \n }", "constructor() {\n \n }", "constructor() {\n \n }" ]
[ "0.60415715", "0.5918748", "0.5844924", "0.5757533", "0.5714492", "0.5661645", "0.56571835", "0.557702", "0.5551288", "0.5537155", "0.5529827", "0.5528053", "0.5526852", "0.5525806", "0.5488529", "0.54618627", "0.5449665", "0.54413414", "0.54372483", "0.5416988", "0.5402368", "0.5359994", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5358521", "0.5357274", "0.5356657", "0.5340301", "0.5334878", "0.5317844", "0.53159195", "0.5309284", "0.5306016", "0.53026706", "0.52886844", "0.5281244", "0.5279597", "0.52663416", "0.5244771", "0.52349037", "0.52343255", "0.52198535", "0.52117383", "0.52076083", "0.5193825", "0.5187614", "0.5184394", "0.51773465", "0.51674145", "0.5161929", "0.5159454", "0.51559514", "0.51529914", "0.5121676", "0.51167536", "0.5107705", "0.50999266", "0.5099077", "0.50876456", "0.5077823", "0.50757855", "0.5075198", "0.5075198", "0.5075198", "0.5075198", "0.5075198", "0.5075198" ]
0.0
-1
Apply the icon and edge overlay for notebooks
function applyOverlay(overlay) { image.scan(0, 0, image.bitmap.width, image.bitmap.height, (x, y, idx) => { if(overlay.data[idx+3]) { image.bitmap.data[idx] = overlay.data[idx]; image.bitmap.data[idx+1] = overlay.data[idx+1]; image.bitmap.data[idx+2] = overlay.data[idx+2]; } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "getIcon() {\n return \"document-cook\";\n }", "function setDesktopIcons(){\t}", "function adjustIconColorDocument() {\n $('.oi-icon').each(function(e) {\n if(!$(this).hasClass('colored')) {\n $(this).css('fill', '#3E2F24');\n $(this).addClass('colored');\n }\n });\n }", "function MatIconLocation() {}", "updateDriveSpecificIcons() {}", "updateDriveSpecificIcons() {}", "function IconOptions() {}", "updateExpandIcon() {}", "function addIconsToMasthead () {\n\t\t// Add the new right-align container and put the icons and the search container into it.\n\t\tmastheadLinklist.iconsonly.$el = $('<div class=\"ibm-masthead-rightside\">'+ mastheadLinklist.iconsonly.html + '</div>').prepend($(\"#ibm-search-module\")).insertAfter(\"#ibm-menu-links\");\n\t\t$profileMenu = mastheadLinklist.iconsonly.$el.find(\".ibm-masthead-item-signin\");\n\n\t\tconvertSearchSubmitToButton();\n\t}", "_createAppearanceTabIcons() {\n\n // We have to add these events to the Gtk.DrawingAreas to make them actually\n // clickable. Else it would not be possible to select the tabs.\n const tabEvents = Gdk.EventMask.BUTTON_PRESS_MASK | Gdk.EventMask.BUTTON_RELEASE_MASK;\n\n // Draw six lines representing the wedge separators.\n let tabIcon = this._builder.get_object('wedges-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.translate(size / 2, size / 2);\n ctx.rotate(2 * Math.PI / 12);\n\n for (let i = 0; i < 6; i++) {\n ctx.moveTo(size / 5, 0);\n ctx.lineTo(size / 2, 0);\n ctx.rotate(2 * Math.PI / 6);\n }\n\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n ctx.setLineWidth(2);\n ctx.stroke();\n\n return false;\n });\n\n // Draw on circle representing the center item.\n tabIcon = this._builder.get_object('center-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.translate(size / 2, size / 2);\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n ctx.arc(0, 0, size / 4, 0, 2 * Math.PI);\n ctx.fill();\n\n return false;\n });\n\n // Draw six circles representing child items.\n tabIcon = this._builder.get_object('children-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.translate(size / 2, size / 2);\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n\n for (let i = 0; i < 6; i++) {\n ctx.rotate(2 * Math.PI / 6);\n ctx.arc(size / 3, 0, size / 10, 0, 2 * Math.PI);\n ctx.fill();\n }\n\n return false;\n });\n\n // Draw six groups of five grandchildren each. The grandchild at the back-navigation\n // position is skipped.\n tabIcon = this._builder.get_object('grandchildren-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.translate(size / 2, size / 2);\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n\n for (let i = 0; i < 6; i++) {\n ctx.rotate(2 * Math.PI / 6);\n\n ctx.save()\n ctx.translate(size / 3, 0);\n ctx.rotate(Math.PI);\n\n for (let j = 0; j < 5; j++) {\n ctx.rotate(2 * Math.PI / 6);\n ctx.arc(size / 10, 0, size / 20, 0, 2 * Math.PI);\n ctx.fill();\n }\n\n ctx.restore();\n }\n\n return false;\n });\n\n // Draw a line and some circles representing a trace.\n tabIcon = this._builder.get_object('trace-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n\n ctx.moveTo(0.2 * size, 0.2 * size);\n ctx.lineTo(0.4 * size, 0.6 * size);\n ctx.lineTo(0.9 * size, 0.7 * size);\n\n ctx.setLineWidth(2);\n ctx.stroke();\n\n ctx.arc(0.2 * size, 0.2 * size, 0.15 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n ctx.arc(0.4 * size, 0.6 * size, 0.1 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n ctx.arc(0.9 * size, 0.7 * size, 0.1 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n return false;\n });\n\n // Draw three dots indicating the advanced settings.\n tabIcon = this._builder.get_object('advanced-tab-icon');\n tabIcon.add_events(tabEvents);\n tabIcon.connect('draw', (widget, ctx) => {\n const size = Math.min(widget.get_allocated_width(), widget.get_allocated_height());\n const color = widget.get_style_context().get_color(Gtk.StateFlags.NORMAL);\n\n ctx.setSourceRGBA(color.red, color.green, color.blue, color.alpha);\n\n ctx.arc(0.15 * size, 0.5 * size, 0.1 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n ctx.arc(0.5 * size, 0.5 * size, 0.1 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n ctx.arc(0.85 * size, 0.5 * size, 0.1 * size, 0, 2 * Math.PI);\n ctx.fill();\n\n return false;\n });\n }", "function mapper_page_paint_icons() {\n\n if( glyph_url != null ) return;\n\n if(true) { \n glyph_post = \"/dynamapper/icons/weather-clear.png\";\n var feature = {};\n feature[\"kind\"] = \"icon\";\n feature[\"image\"] = glyph_post;\n feature[\"iconSize\"] = [ 32, 32 ];\n feature[\"iconAnchor\"] = [ 9, 34 ];\n feature[\"iconWindowAnchor\"] = [ 9, 2 ];\n mapper_inject_feature(feature);\n }\n\n if(true) {\n glyph_person = \"/dynamapper/icons/emblem-favorite.png\";\n var feature = {};\n feature[\"kind\"] = \"icon\";\n feature[\"image\"] = glyph_person;\n feature[\"iconSize\"] = [ 32, 32 ];\n feature[\"iconAnchor\"] = [ 9, 34 ];\n feature[\"iconWindowAnchor\"] = [ 9, 2 ];\n mapper_inject_feature(feature);\n }\n\n if(true) {\n glyph_url = \"/dynamapper/icons/emblem-important.png\";\n var feature = {};\n feature[\"kind\"] = \"icon\";\n feature[\"image\"] = glyph_url;\n feature[\"iconSize\"] = [ 32, 32 ];\n feature[\"iconAnchor\"] = [ 9, 34 ];\n feature[\"iconWindowAnchor\"] = [ 9, 2 ];\n mapper_inject_feature(feature);\n }\n}", "fixLeaftletCssBug() { \n delete L.Icon.Default.prototype._getIconUrl;\n\n L.Icon.Default.mergeOptions({\n iconRetinaUrl: marker2x,\n iconUrl: marker1x,\n shadowUrl: markerShadow\n });\n }", "function mouseEnterMicroblogIcon(e) {\n // Change the cursor style as a UI indicator.\n map.getCanvas().style.cursor = \"pointer\";\n\n // get the coordinates and description of the microblog_icon\n var coordinates = e.features[0].geometry.coordinates.slice();\n var description = e.features[0].properties.description;\n\n // Ensure that if the map is zoomed out such that multiple\n // copies of the feature are visible, the popup appears\n // over the copy being pointed to.\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n // Populate the popup and set its coordinates\n // based on the feature found.\n microblogIconPopup.setLngLat(coordinates).setHTML(description).addTo(map);\n }", "function load_icon(event) {\n\n // we need to do two steps:\n // 1. draw the image object to the canvas\n // 2. loop the canvas pixels and set pixel editor background colors\n\n var canvas = document.getElementById('preview-canvas');\n var ctx = canvas.getContext(\"2d\");\n\n ctx.drawImage(event.target, 0, 0); // \"event.target\" is an Image object that can be drawn to the canvas\n for (var i=0; i<16; i++) { // loop through all the pixels\n for (var j=0; j<16; j++) {\n // getImageData returns a flat list with rgba (a=alpha) values\n // so rgba holds [r,g,b,a]\n var rgba = ctx.getImageData(j, i, 1, 1).data;\n // set backgroundColor property in editor table\n document.getElementById(\"pixel-\"+i+\"-\"+j).style.backgroundColor = \"rgb(\"+rgba[0]+\",\"+rgba[1]+\",\"+rgba[2]+\")\";\n }\n }\n document.getElementById(\"save-title\").value = event.target.title;\n}", "_getSVGHandler(e){let root=this,temp=document.createElement(\"div\"),getID=function(element,alt){if(null===element.getAttribute(\"id\"))element.setAttribute(\"id\",alt);return element.getAttribute(\"id\")},setAriaLabelledBy=function(source,target,prefix){// adds title and desc elements to target and sets the aria-labelledby attribute\nlet svgElem=function(nodename){source=null!==source?source:root;//adds title or desc element to target\nlet attr=\"title\"===nodename?\"label\":nodename,query=source.querySelector(\"#\"+attr);var label=target.querySelector(nodename);//if the target doesn't have the element, add it\nif(null===label){label=document.createElement(nodename);target.prepend(label)}//populates the element with data from the source element\nif(null!==source.getAttribute(attr)){label.innerHTML=source.getAttribute(attr)}else if(null!==query&&\"\"!==query.innerHTML){label.innerHTML=query.innerHTML}//returns the new element's id\nreturn getID(label,prefix+\"-\"+attr)};//set aria-labelledby to the id's for title and descriptions\ntarget.setAttribute(\"aria-labelledby\",svgElem(\"desc\")+\" \"+svgElem(\"label\"))};//set up main svg and append to document\ntemp.innerHTML=e.detail.response;let svg=temp.querySelector(\"svg\"),svgid=getID(svg,\"svg-\"+Date.now()),hdata=dom(root).querySelectorAll(\"lrndesign-imagemap-hotspot\");setAriaLabelledBy(root,svg,svgid);this.shadowRoot.querySelector(\"#svg\").appendChild(svg);for(let i=0;i<hdata.length;i++){let hid=hdata[i].getAttribute(\"hotspot-id\"),hotspot=svg.querySelector(\"#\"+hid),clone=svg.cloneNode(!0);//clone svg for print versions and show hotspot as selected\nsetAriaLabelledBy(hdata[i],clone,hid);hdata[i].appendChild(clone);hdata[i].querySelector(\"#\"+hid).classList.add(\"selected\");hdata[i].setParentHeading(root.shadowRoot.querySelector(\"#heading\"));for(let j=0;j<hdata.length;j++){hdata[i].querySelector(\"#\"+hdata[j].getAttribute(\"hotspot-id\")).classList.add(\"hotspot\")}//configure hotspot on main (interactive) svg\nlet hbutton=document.createElement(\"button\");hbutton.setAttribute(\"tabindex\",0);hbutton.setAttribute(\"aria-label\",hdata[i].label);root.shadowRoot.querySelector(\"#buttons\").appendChild(hbutton);hbutton.addEventListener(\"focus\",function(){hotspot.classList.add(\"focus\")});hbutton.addEventListener(\"blur\",function(){hotspot.classList.remove(\"focus\")});hotspot.classList.add(\"hotspot\");hotspot.addEventListener(\"click\",e=>{this.openHotspot(hotspot,hdata[i])});hbutton.addEventListener(\"keyup\",e=>{if(13===e.keyCode||32===e.keyCode){if(!hotspot.classList.contains(\"selected\")){this.openHotspot(hotspot,hdata[i])}}})}}", "updateDriveSpecificIcons() {\n const metadata = this.parentTree_.metadataModel.getCache(\n [this.dirEntry_], ['shared', 'isMachineRoot', 'isExternalMedia']);\n\n const icon = this.querySelector('.icon');\n icon.classList.toggle('shared', !!(metadata[0] && metadata[0].shared));\n\n if (metadata[0] && metadata[0].isMachineRoot) {\n icon.setAttribute(\n 'volume-type-icon', VolumeManagerCommon.RootType.COMPUTER);\n }\n\n if (metadata[0] && metadata[0].isExternalMedia) {\n icon.setAttribute(\n 'volume-type-icon', VolumeManagerCommon.RootType.EXTERNAL_MEDIA);\n }\n }", "configureIconLib() {\n if (this.preserveDefaults) {\n this.iconLibrary = this.$thisvui.iconLib;\n } else {\n let parent = this.$parent;\n let pIconLib = parent && parent.$props ? parent.$props.iconLib : null;\n this.iconLibrary = this.iconLib\n ? this.iconLib\n : parent && pIconLib\n ? pIconLib\n : this.$thisvui.iconLib;\n }\n }", "function fullIcon(data) {\n return { ...exports.iconDefaults, ...data };\n}", "createIcon() {\n const iconUri = `file://${Me.path}/icons/icon.svg`;\n const iconFile = Gio.File.new_for_uri(iconUri);\n const gicon = new Gio.FileIcon({ file: iconFile });\n const icon = new St.Icon({\n gicon: gicon,\n style_class: 'system-status-icon'\n });\n this.add_child(icon);\n }", "function show_as_image(e) {\n var me = $(e.target)\n , at = me.parents(sel_svgs)\n ;\n e.preventDefault(); // don't scroll to top\n me.parents('.actions').find('a').css('color', '');\n me.css('color', '#000');\n\n at.find(sel_num).hide(); // hide line numbers\n at.find(sel_raw).children('svg:first').show().siblings().hide(); // show svg\n}", "function pin(event, icon){\n\tevent.stopPropagation();\n}", "function load_custombb () {\n document.querySelectorAll('span[style=\"color:resimg\"]').forEach(e => {\n $(e).replaceWith(`<img src=\"https://${e.innerHTML}\"></img>`);\n });\n document.querySelectorAll('span[style=\"color:reshighlight\"]').forEach(e => {\n $(e).replaceWith(`<mark>${e.innerHTML}</mark>`);\n });\n document.querySelectorAll('span[style=\"color:resleft\"]').forEach(e => {\n $(e).replaceWith(`<p align=\"left\">${e.innerHTML}</p>`);\n });\n document.querySelectorAll('span[style=\"color:resright\"]').forEach(e => {\n $(e).replaceWith(`<p align=\"right\">${e.innerHTML}</p>`);\n });\n document.querySelectorAll('a[href^=\"https://gist.github.com/\"]').forEach(e => {\n var url = encodeURI('data:text/html;charset=utf-8,<body><script src=\"' + $(e).attr(\"href\") + \".js\" + '\"></script></body>');\n $(e).append(`<br><iframe src='` + url + `' width=\"100%\" height=\"400\" scrolling=\"auto\" frameborder=\"no\" align=\"center\"></iframe>`);\n });\n }", "function update_icon()\n {\n const icon = bookmarks.is_unlocked() ? \"unlocked-bookmarks.svg\" :\n \"locked-bookmarks.svg\";\n const path = `/icons/main/${icon}`;\n browser.browserAction.setIcon({\n path:\n {\n \"16\": path,\n \"32\": path,\n \"48\": path,\n \"64\": path,\n \"96\": path,\n \"128\": path,\n \"256\": path\n }\n });\n }", "function crossIconAdd() {\n let cross = document.createElement(\"div\");\n styleCrossIcon(cross);\n cross.innerText = \"❌\";\n return cross;\n}", "renderIcons() {\n const { fileId, altered, fileName, selectedFileId } = this.props\n const icon = (fileId === selectedFileId) ? 'folder open outline' : 'folder outline'\n\n return (\n <span>\n {altered ? (\n <Icon color=\"blue\" size=\"large\" name=\"save\"\n onClick={(e) => this.onSaveFile(fileId)} />\n ) : null\n }\n <Icon color=\"blue\" size=\"large\" name={icon} />\n </span>\n )\n }", "get flagIcon() {\n return FLAGS + \"/\" + this.popoverRegion.code + \".png\";\n }", "function updateIcon () {\n browser.browserAction.setIcon({\n path: currentBookmark\n ? {\n 19: '../public/star-filled-19.png',\n 38: '../public/star-filled-38.png'\n }\n : {\n 19: '../public/star-empty-19.png',\n 38: '../public/star-empty-38.png'\n },\n tabId: currentTab.id\n })\n browser.browserAction.setTitle({\n // Screen readers can see the title\n title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!',\n tabId: currentTab.id\n })\n}", "function iconLocation() { // Icon display\n\t\t\n\t\t// Heavy Traffic Icon\n\t\tvar htIconpoint = {\n\t\t\ttype: \"point\", // autocasts as new Point()\n longitude: 103.875029,\n latitude: 1.280973 \n }; \n var htTitle = \"<b>Heavy Traffic</b>\"\n var htContent = \"<center>Heavy Traffic in MCE </center>\"\n \n\t var htIconPictureSymbol = {\n\t\t\ttype: \"picture-marker\",\n url: \"heavytraffic.png\", //Lower Delta Rd Exit (AYE)\n width: \"22\",\n height: \"22\"\n }\n\t htIconPictureGraphic = new Graphic({\n\t\tgeometry: htIconpoint,\n\t\tsymbol: htIconPictureSymbol,\n popupTemplate: {\n // autocasts as new PopupTemplate()\n title: htTitle,\n content: htContent \n }\n }); \n\n\t\t// Unattended Vehicle Icon\n\t\tvar unVIconpoint = {\n\t\t\ttype: \"point\", // autocasts as new Point()\n longitude: 103.897955,\n latitude: 1.297171 \n }; \n\t var unVIconPictureSymbol = {\n\t\t\ttype: \"picture-marker\",\n url: \"unattvehicle.png\", //Stil Rd 5th Exit (ECP)\n width: \"22\",\n height: \"22\"\n }\n\n var unTitle = \"<b>Unattended vehicle</b>\"\n var unContent = \"<center>Unattended vehicle ECP - Stil Rd 5th Exit </center>\"\n\t unVIconPictureGraphic = new Graphic({\n geometry: unVIconpoint,\n symbol: unVIconPictureSymbol,\n popupTemplate: {\n title: unTitle,\n content: unContent \n }\n });\t\t\n\t\t \n\t\t// Road Work Icon\n\t\tvar rwIconpoint = {\n\t\t\ttype: \"point\", // autocasts as new Point()\n longitude: 103.934441,\n latitude: 1.330996 \n }; \n var rwTitle = \"<b>Roadworks<b>\";\n var rwContent = \"<center>Roadworks on PIE Bedok North Ave 3</center>\";\n var rwIconPictureSymbol = {\n\t\t type: \"picture-marker\",\n url: \"roadwork.png\", //Sungei Tengah Exit(KJE)\n width: \"22\",\n height: \"22\"\n }\n\t rwIconPictureGraphic = new Graphic({\n\t\tgeometry: rwIconpoint,\n symbol: rwIconPictureSymbol,\n popupTemplate: {\n // autocasts as new PopupTemplate()\n title: rwTitle,\n content: rwContent \n }\n });\t\t\n\t\n\t// Accident Icon\n\t\tvar accIconpoint = {\n\t\t\ttype: \"point\", // autocasts as new Point()\n longitude: 103.727822,\n latitude: 1.374733 \n }; \n\t var accIconPictureSymbol = {\n\t\t\ttype: \"picture-marker\",\n url: \"accident.png\", //Seletar Link (TPE)\n width: \"22\",\n height: \"22\"\n }\n\n var accTitle = \"<b>Accident<b>\";\n var accContent = \"<center>Accident on KJE Sungei Tengah Exit</center>\";\n\t accIconPictureGraphic = new Graphic({\n\t\tgeometry: accIconpoint,\n symbol: accIconPictureSymbol,\n popupTemplate: {\n title: accTitle,\n content: accContent \n }\n });\n\n//New incident Accident Icon created after the \n\t\tvar accIconpoint1 = {\n\t\t\t\ttype: \"point\", // autocasts as new Point()\n\t\t\t\tlongitude: 103.858249, //103.858056,\n\t latitude: 1.378062 \n\t }; \n\t\t var accIconPictureSymbol1 = {\n\t\t\t\ttype: \"picture-marker\",\n\t url: \"accident.png\", //Seletar Link (TPE)\n\t width: \"22\",\n\t height: \"22\",\n\t }\n\n\t var accTitle = \"<b>Accident<b>\";\n\t var accContent = \"<center>Accident on KJE Sungei Tengah Exit</center>\";\n\t\t accIconPictureGraphic1 = new Graphic({\n\t\t\tgeometry: accIconpoint1,\n\t symbol: accIconPictureSymbol1,\n\t popupTemplate: {\n\t title: accTitle,\n\t content: accContent \n\t }\n\t });\n\n//New incident Mobile road work Icon created after the\t\t \n\t\t\tvar rwIconpoint1 = {\n\t\t\t\t\ttype: \"point\", // autocasts as new Point()\n\t\t longitude: 103.92464,\n\t\t latitude: 1.3113622 \n\t\t }; \n\t\t var rwTitle = \"<b>Roadworks<b>\";\n\t\t var rwContent = \"<center>Roadworks on PIE Bedok North Ave 3</center>\";\n\t\t var rwIconPictureSymbol1 = {\n\t\t\t\t type: \"picture-marker\",\n\t\t url: \"roadwork.png\", //Sungei Tengah Exit(KJE)\n\t\t width: \"22\",\n\t\t height: \"22\"\n\t\t }\n\t\t\t rwIconPictureGraphic1 = new Graphic({\n\t\t\t\tgeometry: rwIconpoint1,\n\t\t symbol: rwIconPictureSymbol1,\n\t\t popupTemplate: {\n\t\t // autocasts as new PopupTemplate()\n\t\t title: rwTitle,\n\t\t content: rwContent \n\t\t }\n\t});\t \n\n\t\t \n\t// breakdown Icon\n\t\tvar bdIconpoint = {\n\t\t\ttype: \"point\", // autocasts as new Point()\n longitude: 103.881117,\n latitude: 1.401208 \n }; \n\t var bdIconPictureSymbol = {\n\t\t\ttype: \"picture-marker\",\n url: \"breakdown.png\", //Bedok North Ave 3(PIE)\n width: \"22\",\n height: \"22\"\n }\n \n var bdTitle = \"<b>Breakdown<b>\";\n var bdContent = \"<center>Breakdown\t(TPE) - Seletar Link </center>\";\n\t bdIconPictureGraphic = new Graphic({\n\t\tgeometry: bdIconpoint,\n symbol: bdIconPictureSymbol, \n popupTemplate: {\n title: bdTitle,\n content: bdContent \n }\n });\t\t \t \n\t\tview.graphics.addMany([htIconPictureGraphic, unVIconPictureGraphic,rwIconPictureGraphic,accIconPictureGraphic,bdIconPictureGraphic,accIconPictureGraphic1,rwIconPictureGraphic1]);\n }", "addHighlighTooltip () {\n }", "function optOnIconMouseDownListener(e) { // tabulator.Icon.src.icon_opton needed?\n var target = thisOutline.targetOf(e);\n var p = target.parentNode;\n termWidget.replaceIcon(p.parentNode,\n tabulator.Icon.termWidgets.optOn,\n tabulator.Icon.termWidgets.optOff, optOffIconMouseDownListener);\n p.parentNode.parentNode.removeAttribute('optional');\n }", "function displayInfoBox(node) {\n\t\tvar nodeName = node.attr(\"name\")\n var infoX = infoBoxWidth/2*0.6 \n var infoY = infoBoxHeight/2*1.05\n\t\tvar infoBox = svg.append(\"g\")\n\t\tinfoBox\n .attr(\"class\", \"popup\")\n .attr(\"transform\", function(d) {return \"translate(\" + infoX + \",\" + infoY + \")\";})\n\n\t\tinfoBox\n .append(\"text\")\n .attr(\"y\", function(d) {return -infoBoxHeight/2 + fontSize + 2*lineSpace;})\n .attr(\"text-anchor\", \"middle\")\n .text(nodeName)\n .attr(\"font-size\", fontSize + 8 + \"px\")\n\n \tinfoBox.append(\"rect\")\n .attr('id', 'performancebar')\n .attr(\"width\", infoBoxWidth*0.99)\n .style(\"fill\", \"red\")\n .style(\"stroke\", \"red\")\n .attr(\"y\", boxHeight/0)\n .attr(\"height\", 0)\n\t\n\t\n var imgOffsetX = -infoBoxWidth/2 * 0.95\n var imgOffsetY = -infoBoxHeight/2 + fontSize+8 + 2*lineSpace\n\t\tinfoBox\n .append(\"svg:image\")\n \t.attr(\"xlink:href\", \"sample_patches/\"+nodeName+\".png\")\n .attr(\"width\", infoBoxWidth*0.99)\n .attr(\"height\", infoBoxHeight*0.99)\n .attr(\"transform\", function(d) {return \"translate(\" + imgOffsetX + \",\" + imgOffsetY + \")\";})\n\t}", "function writerIconClick() {\n\tvar x = document.getElementById('writerwindow');\n\tx.style.display = \"block\";\n\n\t// makes current window the top window\n\tvar windows = document.getElementsByClassName('drsElement');\n\tvar i = windows.length;\n\twhile (i--) {\n\t\twindows[i].style.zIndex = \"3\";\n\t}\n\tx.style.zIndex = \"4\";\n\tx.focus();\n}", "function clickMicroblogIcon(e) {\n var room = e.features[0].properties.room;\n var microblog = null;\n for (var i = 0; i < microblogs.length; i++) {\n if (room === microblogs[i].room) {\n microblog = microblogs[i];\n }\n }\n\n MicroblogService.getMicroblog(microblog.room).then(\n function (microblog) {\n var modalInstance = $uibModal.open({\n animation: true,\n templateUrl: \"microblog.html\",\n controller: \"MicroblogController\",\n resolve: {\n microblogToOpen: function () {\n return microblog;\n },\n },\n });\n modalInstance.result.then(function (data) {});\n },\n function (err) {},\n );\n }", "function tooltipIcons(id) {\n hoverTooltip(id, 'smileys');\n hoverTooltip(id, 'save');\n}", "function readCodeHighlightIcon(routine, step){\r\n let elipseColor = \"#006060\";\r\n\r\n readCodeEllipseStack[routine][step].background = elipseColor;\r\n\r\n\r\n\r\n}", "get iconButton() {\n return {\n type: \"rich-text-editor-icon-picker\",\n };\n }", "function InfoBarWindow(){}", "function createIcon(bg_color, opacity, textAlign, text_margin_top, font_color, font_size, data, data_suffix, old_data) {\r\n\r\n //if a sensor is determined to have old data, we color it gray and make it semitransparent\r\n if(old_data) {\r\n font_color = '#2a2a2a';\r\n bg_color = '#808080';\r\n opacity = '0.85';\r\n }\r\n\r\n icon = L.divIcon({ \r\n className: \"my-custom-pin\",\r\n iconAnchor: [15, 15],\r\n labelAnchor: [0, 0],\r\n popupAnchor: [0, -15],\r\n html: `<svg width=\"30px\" viewBox=\"0 0 60 60\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\r\n <circle cx=\"30\" cy=\"30\" r=\"28\" opacity=\"${opacity}\" stroke-width=\"1\" stroke=\"black\" fill=\"${bg_color}\" shape-rendering=\"geometricPrecision\"/>\r\n <text x=\"50%\" y=\"50%\" text-anchor=\"middle\" fill=\"${font_color}\" font-size=\"1.9em\" dy=\".4em\">${data}${data_suffix}</text>\r\n </svg>`\r\n });\r\n\r\n return icon;\r\n}", "_getIconContext() {\n return {\n index: this.index,\n active: this.active,\n optional: this.optional\n };\n }", "function updateBrowserIcon() {\n if (browserIconCtx) chromeBrowserAction.setIcon({ imageData: { \"38\": browserIconCtx.getImageData(0, 0, 38, 38) } });\n }", "function renderIcons() {\r\n\t\te.renderIcon('#logo', 'logo');\r\n\t\t//e.renderIcon('#loading_msglogo','logo');\r\n\t\te.renderIcon('.menu_icon', 'user_management');\r\n\t\te.renderIcon('.menu_click', 'user_management');\r\n\t\te.renderIcon('.notification', 'notification');\r\n\t\te.renderIcon('header .analysis_status .analysis_icon', 'analysis');\r\n\t\te.renderFontIcon('.input_clear_icon', 'ic-close-sm');\r\n\t\te.renderFontIcon('.search_icon', 'ic-search');\r\n\t\te.renderIcon('#add_bookmark', 'bookmarks');\r\n\t\te.renderIcon('#add_bookmark1', 'bookmarks');\r\n\t\te.renderFontIcon('.tag_icon', 'ic-tags');\r\n\t\t$(document).foundation();\r\n\t\tg.init();\r\n\t}", "function showBrokenImageIcon() {\n\t\t\teditor.contentStyles.push(\n\t\t\t\t'img:-moz-broken {' +\n\t\t\t\t\t'-moz-force-broken-image-icon:1;' +\n\t\t\t\t\t'min-width:24px;' +\n\t\t\t\t\t'min-height:24px' +\n\t\t\t\t'}'\n\t\t\t);\n\t\t}", "function showBrokenImageIcon() {\n\t\t\teditor.contentStyles.push(\n\t\t\t\t'img:-moz-broken {' +\n\t\t\t\t\t'-moz-force-broken-image-icon:1;' +\n\t\t\t\t\t'min-width:24px;' +\n\t\t\t\t\t'min-height:24px' +\n\t\t\t\t'}'\n\t\t\t);\n\t\t}", "function showBrokenImageIcon() {\n\t\t\teditor.contentStyles.push(\n\t\t\t\t'img:-moz-broken {' +\n\t\t\t\t\t'-moz-force-broken-image-icon:1;' +\n\t\t\t\t\t'min-width:24px;' +\n\t\t\t\t\t'min-height:24px' +\n\t\t\t\t'}'\n\t\t\t);\n\t\t}", "function addIcon(element){\n var image_path = \"/archibus/schema/ab-core/graphics/icons/tick-white.png\";\n var src = image_path;\n \n var img = document.createElement(\"img\");\n img.setAttribute(\"src\", src);\n img.setAttribute(\"border\", \"0\");\n \n img.setAttribute(\"align\", \"middle\");\n img.setAttribute(\"valign\", \"right\");\n \n element.appendChild(img);\n}", "function addExtraButtons () {\n\tmw.toolbar.addButtons(\n\t{\n\t\t'imageId': 'button-redirect',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_redirect.png', \n\t\t'speedTip': 'Redirect',\n\t\t'tagOpen': '#REDIRECT[[',\n\t\t'tagClose': ']]',\n\t\t'sampleText': 'Target page name'\n\t},\n\t{\n\t\t'imageId': 'button-strike',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_strike.png', \n\t\t'speedTip': 'Strike',\n\t\t'tagOpen': '<s>',\n\t\t'tagClose': '</s>',\n\t\t'sampleText': 'Strike-through text'\n\t},\n\t{\n\t\t'imageId': 'button-enter',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_enter.png', \n\t\t'speedTip': 'Line break',\n\t\t'tagOpen': '<br/>',\n\t\t'tagClose': '',\n\t\t'sampleText': ''\n\t}, \n\t\t'imageId': 'button-hide-comment',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_hide_comment.png', \n\t\t'speedTip': 'Insert hidden Comment',\n\t\t'tagOpen': '<!-- ',\n\t\t'tagClose': ' -->',\n\t\t'sampleText': 'Comment'\n\t}, \n\t{\n\t\t'imageId': 'button-blockquote',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_blockquote.png',\n\t\t'speedTip': 'Insert block of quoted text',\n\t\t'tagOpen': '<blockquote>\\n',\n\t\t'tagClose': '\\n</blockquote>',\n\t\t'sampleText': 'Block quote'\n\t},\n\t{\n\t\t'imageId': 'button-insert-table',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_insert_table.png',\n\t\t'speedTip': 'Insert a table',\n\t\t'tagOpen': '{| class=\"wikitable\"\\n|',\n\t\t'tagClose': '\\n|}',\n\t\t'sampleText': '-\\n! header 1\\n! header 2\\n! header 3\\n|-\\n| row 1, cell 1\\n| row 1, cell 2\\n| row 1, cell 3\\n|-\\n| row 2, cell 1\\n| row 2, cell 2\\n| row 2, cell 3'\n\t},\n\t{\n\t\t'imageId': 'button-insert-reflink',\n\t\t'imageFile': '//static3.wikia.nocookie.net/psiepsilon/images/c/c9/Button_reflink.png',\n\t\t'speedTip': 'Insert a reference',\n\t\t'tagOpen': '<ref>',\n\t\t'tagClose': '</ref>',\n\t\t'sampleText': 'Insert footnote text here'\n\t}\n\t);\n}", "function makeIcons(app) {\n if (HIDDEN_ROLES.indexOf(app.manifest.role) !== -1) {\n return;\n }\n\n if (app.manifest.entry_points) {\n for (var i in app.manifest.entry_points) {\n icons.push(new Icon(app, i));\n }\n } else {\n icons.push(new Icon(app));\n }\n }", "function addTitleIcons() {\n if (skin == 'monaco' || skin == 'monobook' || skin == 'oasis') {\n var insertTarget;\n \n switch (skin) {\n case 'monobook':\n insertTarget = $('#firstHeading');\n break;\n case 'monaco':\n insertTarget = $('#article > h1.firstHeading');\n break;\n case 'oasis':\n if (wgAction != 'submit' && wgNamespaceNumber != 112) {\n insertTarget = $('#WikiaPageHeader');\n }\n break;\n }\n \n if (insertTarget) {\n $('#va-titleicons').css('display', 'block').prependTo(insertTarget);\n }\n }\n}", "function setup_extensionIcon() {\n // Rules for page-matching; tells Chrome when to enable extension icon\n let rule1 = {\n conditions: [\n // TODO: Make conditions more accurate, like the contextPatterns below\n new chrome.declarativeContent.PageStateMatcher({\n pageUrl: {hostSuffix: 'steampowered.com'}\n }),\n new chrome.declarativeContent.PageStateMatcher({\n pageUrl: {hostSuffix: 'steamcommunity.com'}\n })\n ],\n actions: [\n new chrome.declarativeContent.ShowPageAction() // Un-grayscale the logo\n ]\n };\n\n // onInstalled is called when the extension is installed or updated\n chrome.runtime.onInstalled.addListener(function () {\n chrome.declarativeContent.onPageChanged.removeRules(undefined, function () { // Remove old rules...\n chrome.declarativeContent.onPageChanged.addRules([rule1]); // ...before adding new ones.\n });\n });\n}", "function displayLeaf(el) {\n el.removeClassName('nodisplay');\n img = el.previous().select('img')[0];\n img.writeAttribute('src', img.src.replace('fold', 'collapse'));\n}", "showLevelIcons() {\n easy.render();\n medium.render();\n hard.render();\n }", "show() {\n // applyTextTheme\n image(this.image, this.x, this.y, this.width, this.height)\n }", "function CustomInfosetExtensionHandler() {\n\n\t$.level = 1; // Debugging level\n\t/**\n\t The context in which this sample can run.\n\t @type String\n\t*/\n\tthis.requiredContext = \"\\tNeed to be running in context of Bridge\\n\";\n\n\t/**\n\t The image for the button icon\n @type String\n\t*/\n\tthis.buttonIcon = new File($.fileName).parent.fsName + \"/resources/editIcon.png\";\n\t\t\n}", "setActionIconsDefault() {\n this.talkIcon.setFrame(4)\n this.swordIcon.setFrame(2)\n this.bowIcon.setFrame(0)\n }", "function markerStyle() {\n iconStyle = [new ol.style.Style({\n image: new ol.style.Icon(({\n scale: 0.25,\n src: 'images/marker-editor.png'\n }))\n })];\n return iconStyle;\n }", "generateIcons() {\n const terminalBase = Core.atlas.find(this.name);\n const terminalDisplay = Core.atlas.find(this.name + \"-display-icon\");\n return [terminalBase, terminalDisplay];\n }", "function toggleIcon(grayedOut) {\n\t\tvar head = top.document.getElementsByTagName(\"head\");\n\t\tif (head) {\n\t\t\tvar icon = document.createElement('link');\n\t\t\ticon.type = 'image/x-icon';\n\t\t\ticon.rel = 'shortcut icon';\n\n\t\t\tif (grayedOut) {\n\t\t\t\t// Grayscale.\n\t\t\t\ticon.href = 'data:image/x-icon;base64,AAABAAQAICAAAAEACACoCAAARgAAABAQAAABAAgAaAUAAO4IAAAgIAAAAQAgAKgQAABWDgAAEBAAAAEAIABoBAAA/h4AACgAAAAgAAAAQAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQIBAAYEAwAAAgQABQUFAAkCAQAMBgMAAAYJAAkJCQAODAoADQ0OAAALEgAGDBEAAg4XAAAPGQAAEh4AEhISABQTEwAWFhYAGRkZAB4eHgAADiAAABQiAA0YIAAUHCIACSM0ACEhIQAkJCQAKSkpAC4uLgA2Mi8AMjIyADY2NgA5OTkAPT09AAAtSwAIMU0AADFRAAA4XQAAQGwAG0xsAABEcAAPSnIAAEx/AEFBQQBFRUUASEZFAElJSQBNTU0AUVFRAFVVVQBaWloAXV1dAGFiYgBlZWUAaWlpAG5ubgBxcXEAdXV1AHl5eQB9fX0AAE+FAABVjQAQVYMAGlyIAABYkwAOXZEACF2WAABdmwAAX58AGmOUAAZjoQARaqQAGWuhAAByvgAJeMIAAHvNABJ+xgAcf8MAAYHXAAeC1AAKg9UAAIbcABWV3gAAieMAAIrkAAiW8QAAl/gAAJf/AACZ/gAEmP8AAJ3/AAua+gAAof8ABaH/AASk/wAMo/8ACKT/AGbH/wB/zP8AgYGBAIWFhQCHiIgAiIiIAI2NjQCRkZEAlZWVAJmZmQCenp4AoaGhAKWlpQCoqKgAra2tAKyusACxsbIAtra2ALm5uQC9vb0AuOb/AMHBwQDGxsYAycnJAM/MywDPz88A0tLSANTU1ADZ2dkA3d3dAN/g4ADj4+MA6enpAPHx8QD09PQA+fn5AP7+/gDwwwAA/9IRAP/YMQD/3VEA/+RxAP/qkQD/8LEA//bRAP///wAAAAAALxQAAFAiAABwMAAAkD4AALBNAADPWwAA8GkAAP95EQD/ijEA/51RAP+vcQD/wZEA/9KxAP/l0QD///8AAAAAAC8DAABQBAAAcAYAAJAJAACwCgAAzwwAAPAOAAD/IBIA/z4xAP9cUQD/enEA/5eRAP+2sQD/1NEA////AAAAAAAvAA4AUAAXAHAAIQCQACsAsAA2AM8AQADwAEkA/xFaAP8xcAD/UYYA/3GcAP+RsgD/scgA/9HfAP///wAAAAAALwAgAFAANgBwAEwAkABiALAAeADPAI4A8ACkAP8RswD/Mb4A/1HHAP9x0QD/kdwA/7HlAP/R8AD///8AAAAAACwALwBLAFAAaQBwAIcAkAClALAAxADPAOEA8ADwEf8A8jH/APRR/wD2cf8A95H/APmx/wD70f8A////AAAAAAAbAC8ALQBQAD8AcABSAJAAYwCwAHYAzwCIAPAAmRH/AKYx/wC0Uf8AwnH/AM+R/wDcsf8A69H/AP///wAAAAAACAAvAA4AUAAVAHAAGwCQACEAsAAmAM8ALADwAD4R/wBYMf8AcVH/AIxx/wCmkf8Av7H/ANrR/wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAaCAAAAAAAAAAACBswAAAAAAAAAAAAAAAAAAAALAgAAAAAAAAAAAAAAAAAAAAACCwAAAAAAAAAAAAAHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfAAAAAAAAMAAAAAAAAAAAAAAAADhkAAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAhhIUwAAAAAAAAAAAAAAAALwAAAAAAABQAAAAAAAAACnyPj34aAAAAAAAAAA8DAAAAADMBAAAhfzsEAAAAAABoj4+Pj2sAAAAAAAAnUiMAAAAyLAQACHiPj2wQAAAAMoaPj4+EMAAAAAAHQVtdTAsAACEsBAE8j4+Pj28IABqBj4+PjzkAAAAAA0RbW1lbPgMAISwDCniPj4+Pj2kKb4+Pj49wAgAAAAA9W1lZW19RDQAhLAQDE2qPj4+PhXeFj4+PfRIAAAAAKVtbWVthSBcBACEsBAAAADmGj4+Pj4+Pj4MgAAAAACVXW1lZXj8CAAAAIS8IAAAAADyPj4+Pj4+POQAAAAAWVVtYW15CAQAAAAAhMREKBAIAAGiPj4+Pj20DAAAAB0pbWVlbRwIAAAAAACEzGxMRCgQDaY+Pj4+PbQMAAABBXVlZWVtFAwAAAAAAITYfHBoTCWWPj4+Pj4+GOAAAJltbWVlZWVs+AAAAAAAhOS0hHRtlho+Pj4+Pj4+CHhVVW1lZW1tYW1krAwAAACE7My8ycI+Pj4+PeYaPj496TltZWVtNXFtZW1lFFgMAIWY3N3+Pj4+Pj3AcdI+Pj492WlhdSwpAYVlZW1tPDgAhaTw5dI+Pj494LRwwgo+Pj49jWVYZAAhJYVlZX0MBACFsamdkgI+PeTQvLyA8ho+Pj4ZiKgUEAAhGYF9QDAAAIXRvbGlvg3U6NzY0MS9wj4+Pj3ESERAIAgYoUyQAAAA2AHBybmxuaGVkOzg3MzWAj4+CLhsbFBMQCQYYBAAAAwAAeHR1cm9tbGpoZDs6NmaFj2QiIiAdHBoTEQkICAQ4AAAAfHR4d3Nxbm1raWdkOXJ0MzIxLywhHx0bGhMaZgAAAAAAAHl1eHd1c3BtbGpoZDw5ODUzMjAtLCAdZAAAAAAAAAAAAAB9d3V1dXRyb21raGdkOzk3NDI2bgAAAAAAAAAAAAAAAAAAAH55dXJycG5sa2hnaG13AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////n///4AB//wAAD/wAAAPwAAAA4AAAAGAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAGAAAABwAAAA/AAAA/8AAA//4AB////////////KAAAABAAAAAgAAAAAQAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQoABAcKAAAFDgAACA0ACAgIAAgKDAAPDw8AEhAOABQQDQAADhgAAhAZABAQEAAWEhAAEBQXABUVFQAZGRkAHx4dAAAYKAAMHywAJSUlACkpKQAvLy8AMjIyADY2NgA5OTkAPDw8AAArSAACOV4ABTteAAk+YgAAR3YAAEt9AAZPfwAKTnoAQEBAAEdHRwBMR0MASEhIAFJSUgBWVlYAWVlZAF1dXQBiYmIAZmZmAGpqagBycnIAdXV1AHl5eQABXp8AD2afAABkqAAAa7EAEHO0AEeDrAAAg9kAB4neAACb+wAAmf0ABZn8AAGd/gAAof8AAaX/AHLL/wCDg4MAh4eHAJGRkQCXl5cAmZmZAKGhoQCkpKQAqqelAK2trQCxsbEAtbW1ALq6ugDDw8MAycnJAM7OzgDV1dUA2traAN3d3QDk5OQA7OztAPLw7wD09PQA+vr6APj//wD+/v4APf8xAFv/UQB5/3EAmP+RALX/sQDU/9EA////AAAAAAAULwAAIlAAADBwAAA9kAAATLAAAFnPAABn8AAAeP8RAIr/MQCc/1EArv9xAMD/kQDS/7EA5P/RAP///wAAAAAAJi8AAEBQAABacAAAdJAAAI6wAACpzwAAwvAAANH/EQDY/zEA3v9RAOP/cQDp/5EA7/+xAPb/0QD///8AAAAAAC8mAABQQQAAcFsAAJB0AACwjgAAz6kAAPDDAAD/0hEA/9gxAP/dUQD/5HEA/+qRAP/wsQD/9tEA////AAAAAAAvFAAAUCIAAHAwAACQPgAAsE0AAM9bAADwaQAA/3kRAP+KMQD/nVEA/69xAP/BkQD/0rEA/+XRAP///wAAAAAALwMAAFAEAABwBgAAkAkAALAKAADPDAAA8A4AAP8gEgD/PjEA/1xRAP96cQD/l5EA/7axAP/U0QD///8AAAAAAC8ADgBQABcAcAAhAJAAKwCwADYAzwBAAPAASQD/EVoA/zFwAP9RhgD/cZwA/5GyAP+xyAD/0d8A////AAAAAAAvACAAUAA2AHAATACQAGIAsAB4AM8AjgDwAKQA/xGzAP8xvgD/UccA/3HRAP+R3AD/seUA/9HwAP///wAAAAAALAAvAEsAUABpAHAAhwCQAKUAsADEAM8A4QDwAPAR/wDyMf8A9FH/APZx/wD3kf8A+bH/APvR/wD///8AAAAAABsALwAtAFAAPwBwAFIAkABjALAAdgDPAIgA8ACZEf8ApjH/ALRR/wDCcf8Az5H/ANyx/wDr0f8A////AAAAAAAIAC8ADgBQABUAcAAbAJAAIQCwACYAzwAsAPAAPhH/AFgx/wBxUf8AjHH/AKaR/wC/sf8A2tH/AP///wAAAAAAADApJiYpMAAAAAAAAAAAFQAAAAAAAAAAFQAAAAAWAAAAAAAnKQAAAAAAFgApABQMAAAPUlMUAAABEgApFA9PSgwARF9VGAAENDcKFBQoX19GKV9fLQAAMz4+HRQVBS5YX1ZfSAAAID48IgIUGAIAMF9fURAAGzk9IQAAFCYQADBfX1ENAzc9PCAAABQrGkFWX1ZfRzE9Ozw5HwEUMENfX0svWF8/Oh4yPj4cFERCU1AqGUlfVzYABjU4CxRORkhCLywsU1QlEAgOEwAsAE5KSEVCMEZEJCMXEQkoAAAAAE5LSUZCQC8rKEAAAAAAAAAAAABQTkxNAAAAAAAA+B8AAOAHAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAADgBwAA/D8AACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWAAAAMgAAAFIAAABrAAAAfAAAAIEAAACBAAAAfAAAAGsAAABSAAAAMgAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAADMAAAB2AAAAsQAAAN0AAAD4AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD4AAAA3QAAALEAAAB2AAAAMwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAGcAAAC+AAAA9gAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD2AAAAvgAAAGcAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAFsAAADQAAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8BAQH/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANAAAABbAAAABQAAAAAAAAAAAAAAAAAAABsAAACxAAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/bm5u/39/f/8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAACxAAAAGwAAAAAAAAAJAAAAtAAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/zo6Ov/09PT/+Pj4/0xMTP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAC0AAAACQAAAFkBAQH/AAAA/wAAAP8AAAD/Hx8f/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8PDw//z8/P////////////2dnZ/yAgIP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/ABIe/wACA/8AAAD/AAAA/wAAAP8AAABZBQUFqAMDA/8AAAD/AAAA/zk5Of/c3Nz/eHh4/wUFBf8AAAD/AAAA/wAAAP8AAAD/AAAA/4+Pj///////////////////////l5eX/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wBAbP8Ahtz/AC1L/wAAAP8AAAD/AAAA/wAAAKgKCgrGBAQE/wAAAP8JCQn/w8PD////////////n5+f/w8PD/8AAAD/AAAA/wAAAP9VVVX/+/v7//////////////////T09P9LS0v/AAAA/wAAAP8AAAD/AAAA/wAFCP8AWJP/AJz//wCh//8Ae83/AAsS/wAAAP8AAAD/AAAAxgoKCsUEBAT/AQEB/35+fv//////////////////////qKio/wkJCf8AAAD/ICAg/+Pj4///////////////////////cHBw/wAAAP8AAAD/AAAA/wAAAP8AAQH/AF2b/wCf//8Am///AJn//wCe//8AVY7/AAIE/wAAAP8AAADFCgoKxQICAv8MDAz/x8fH////////////////////////////kJCQ/w0NDf+np6f//////////////////////6ysrP8EBAT/AAAA/wAAAP8AAAD/AAAA/wBPhf8Anf//AJr//wCZ//8Amv//BKT//wqD1f8CDhf/AAAA/wAAAMUKCgrFBAQE/wEBAf8aGhr/lZWV///////////////////////6+vr/wcHB//r6+v/////////////////U1NT/FxcX/wAAAP8AAAD/AAAA/wAAAP8ARHD/AJz//wCb//8Amf//AJv//wai//8RaqT/DRgg/wIBAf8AAAD/AAAAxQsLC8UFBQX/AAAA/wAAAP8AAAD/cXFx//z8/P//////////////////////////////////////8fHx/zc3N/8AAAD/AAAA/wAAAP8AAAD/ADFR/wCX+P8AnP//AJn//wCa//8Gof//EFWD/wgDAv8AAAD/AAAA/wAAAP8AAADFExMTxQkJCf8BAQH/AAAA/wAAAP8AAAD/fX19//////////////////////////////////////9ycnL/AAAA/wAAAP8AAAD/AAAA/wAVI/8AieP/AJ7//wCZ//8Amv//BaL//w5dkf8GAQD/AAAA/wAAAP8AAAD/AAAA/wAAAMUeHh7GFBQU/wsLC/8GBgb/AwMD/wAAAP8AAAD/jY2N////////////////////////////o6Oj/wEBAf8AAAD/AAAA/wAAAP8ABwv/AHK+/wCf//8Amf//AJn//wCf//8GY6H/BgQD/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAAxSwsLMcjIyP/GBgY/xMTE/8ODg7/BgYG/wICAv+RkZH///////////////////////////+hoaH/AgIC/wAAAP8AAAD/AAAA/wBYk/8AoP//AJr//wCZ//8Amf//AJ7//wBfn/8AAgP/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAADFOjo6yDMzM/8oKCj/IiIi/xgYGP8LCwv/hYWF//////////////////////////////////39/f9ubm7/AAAA/wAAAP8AOF3/AJv+/wCb//8Amf//AJn//wCZ//8Amf//AJv//wBVjP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAMVJSUnIRERE/zk5Of8sLCz/JCQk/4WFhf/8/Pz//////////////////////////////////////+rq6v82Mi//AA4g/wCK5P8Anf//AJn//wCZ//8An///AJr//wCZ//8Am///AJn8/wBMf/8AAQL/AAAA/wAAAP8AAAD/AAAAxVlZWcpYWFj/S0tL/1RUVP+tra3////////////////////////////Ly8v//Pz8/////////////////8/My/8cf8P/AJv//wCZ//8Amf//A5z//xJ+xv8Lmvr/AJv//wCZ//8Am///AJr//wBfn/8AFCH/AAID/wAAAP8AAADFaGhoy2pqav9oaGj/3d3d////////////////////////////rq6u/ygoKP+4uLj//////////////////////7jm//8EmP//AJf//wCh//8JeML/Dg0P/xpciP8JpP//AJr//wCZ//8Am///AJ7//wGB1/8ADxn/AAAA/wAAAMV4eHjNfn5+/3BwcP+4uLj//////////////////////8fHx/9ERET/KSkp/01NTf/p6en//////////////////////3/M//8Amv//CJbx/wkjNP8AAAD/CwkJ/xlrof8Ipf//AJr//wCZ//8Co///CF2W/wICA/8AAAD/AAAAxoeHh8yUlJT/hoaG/4ODg//f39/////////////IyMj/Xl5e/0tLS/9ISEj/Nzc3/319ff/8/Pz//////////////////P7//2bH//8PSnL/CgEA/wQEBP8BAAD/CwkI/xpjlP8Mo///AKP//weC1P8GDBH/AAAA/wAAAP8AAADEkpKSpqioqP+cnJz/kJCQ/6ioqP/x8fH/vb29/3V1df9oaGj/ZWVl/1xcXP9TU1P/R0dH/66urv//////////////////////rK6w/xcXF/8UExP/EBAQ/wsLC/8FAwP/DAYD/xtMbP8Vld7/CDFN/wAAAP8AAAD/AAAA/wAAAJqwsLBQqqqq/7Kysv+mpqb/n5+f/6SkpP+MjIz/hoaG/4CAgP94eHj/b29v/2dnZ/9bW1v/YGFh/9/g4P///////////+jo6P9IRkX/JSUk/yQkJP8dHR3/GBgY/xISEv8LCgr/DQcD/xQcIv8FBQX/AAAA/wAAAP8AAAD+AAAAQenp6QWoqKiju7u7/7y8vP+xsbH/qKio/6Kiov+bm5v/k5OT/4uLi/+Dg4P/e3t7/3Nzc/9lZWX/h4iI//j5+f/+/v7/gYGB/zs7O/88PDz/NTU1/y4uLv8nJyf/ICAg/xoaGv8TExP/DgwK/woKCf8ICAj/BgYG/wMDA5MAAAABAAAAAOPj4w+0tLSXubm5+MTExP+/v7//tra2/6+vr/+np6f/oKCg/5iYmP+QkJD/iIiI/4CAgP9ycnL/srKz/7e3t/9aWlr/V1dX/1BQUP9ISEj/QUFB/zk5Of8yMjL/Kysr/yQkJP8hISH/Gxsb/xcXF/IeHh6HBgYGBwAAAAAAAAAAAAAAAAAAAADOzs49tLS0sry8vP/Gxsb/w8PD/7u7u/+zs7P/q6ur/6Ojo/+bm5v/lJSU/4yMjP+Dg4P/fHx8/3Jycv9ra2v/Y2Nj/1tbW/9TU1P/TU1N/0ZGRv8/Pz//Nzc3/ywsLPs6OjqkdXV1MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADu7u4Dz8/PSLy8vKG6urrlvr6+/7+/v/+9vb3/uLi4/7CwsP+oqKj/oKCg/5eXl/+Pj4//iIiI/4GBgf95eXn/cXFx/2lpaf9eXl7/VFRU/1JSUt9mZmaWmZmZPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPj4xrOzs5Wv7+/kri4uMK1tbXmsrKy+a+vr/+srKz/pqam/5+fn/+YmJj/jo6O/4WFhfiAgIDjgYGBvY2NjYqqqqpNz8/PEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8fHxBebm5hja2towzs7OScbGxlrGxsZfwsLCXsDAwFjFxcVH0dHRLN/f3xXu7u4CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA///////AA//8AAA/8AAAD8AAAAOAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAB4AAAB/AAAB/+AAB//8AD//////8oAAAAEAAAACAAAAABACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAEsAAACEAAAApwAAALcAAAC3AAAApwAAAIQAAABLAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAdQAAANYAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANYAAAB1AAAAEAAAAAAAAAApAAAA0AAAAP8AAAD/AAAA/wAAAP8AAAD/UlJS/1paWv8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANAAAAApAQEBpgAAAP8mJib/Dw8P/wAAAP8AAAD/FhYW/+Tk5P/t7e3/JCQk/wAAAP8AAAD/AAYL/wAYKP8AAAD/AAAApgICAtoUFBT/1dXV/7e3t/8QEBD/AAAA/5qamv//////9PT0/zMzM/8AAAD/AAgN/wBrsf8Ag9r/AA4Y/wAAANoAAADbVVVV////////////pKSk/1paWv/+/v7//////2pqav8AAAD/AAID/wBkqP8Apf//A6X//wU7Xv8AAADbBQUF2ggICP9ycnL//Pz8///////6+vr//////66urv8CAgL/AAAA/wBLff8Aov//A57+/wpOev8EBwr/AAAA2hQUFNoDAwP/AAAA/3Z2dv///////////93d3f8XFxf/AAAA/wArSP8Am/v/AKH//wZPf/8CAAD/AAAA/wAAANotLS3cGRkZ/wMDA/94eHj////////////b29v/FhIQ/wAFDv8Ag9n/AKH//wCe//8AS33/AAAA/wAAAP8AAADaS0tL3Tw8PP+Hh4f/+/v7///////7+/v//////6qnpf8BXp//AKD//wWZ/P8Cnf//AJr8/wBHdv8ABQn/AAAA2mVlZd+Xl5f///////////+5ubn/dnZ2//39/f//////csv//wCY//8JPmL/D2af/wKm//8Aov//Ajle/wAAANuLi4vdkpKS/+zs7P/Y2Nj/XV1d/zk5Of+zs7P///////j///9Hg6z/AAAA/wgKDP8Qc7T/B4ne/wIQGf8AAADYsLCwoaampv+tra3/kJCQ/3Z2dv9lZWX/Z2dn/+3t7v/y8O//TEdD/xoaGf8SEA7/EBQX/wwfLP8AAAD/AAAAmefn5yK+vr7EtLS0/62trf+goKD/kJCQ/3h4eP+jo6P/mZmZ/0dHR/9AQED/MTEx/x8eHf8UEA3/GxsbvQMDAxwAAAAA9PT0CNbW1mPDw8PIurq6+7CwsP+kpKT/k5OT/4ODg/90dHT/YWFh/1RUVPpdXV3Dj4+PXHt7ewUAAAAAAAAAAAAAAAAAAAAA9vb2BePj4znS0tJzw8PDmbi4uKupqamxp6enm7KysnDNzc018/PzAwAAAAAAAAAAAAAAAOAHrEGAAaxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBgAGsQeAHrEE=';\n\t\t\t} else {\n\t\t\t\t// Color.\n\t\t\t\ticon.href = 'data:image/x-icon;base64,AAABAAQAICAAAAEACACoCAAARgAAABAQAAABAAgAaAUAAO4IAAAgIAAAAQAgAKgQAABWDgAAEBAAAAEAIABoBAAA/h4AACgAAAAgAAAAQAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQIBAAYEAwAAAgQABQUFAAkCAQAMBgMAAAYJAAkJCQAODAoADQ0OAAALEgAGDBEAAg4XAAAPGQAAEh4AEhISABQTEwAWFhYAGRkZAB4eHgAADiAAABQiAA0YIAAUHCIACSM0ACEhIQAkJCQAKSkpAC4uLgA2Mi8AMjIyADY2NgA5OTkAPT09AAAtSwAIMU0AADFRAAA4XQAAQGwAG0xsAABEcAAPSnIAAEx/AEFBQQBFRUUASEZFAElJSQBNTU0AUVFRAFVVVQBaWloAXV1dAGFiYgBlZWUAaWlpAG5ubgBxcXEAdXV1AHl5eQB9fX0AAE+FAABVjQAQVYMAGlyIAABYkwAOXZEACF2WAABdmwAAX58AGmOUAAZjoQARaqQAGWuhAAByvgAJeMIAAHvNABJ+xgAcf8MAAYHXAAeC1AAKg9UAAIbcABWV3gAAieMAAIrkAAiW8QAAl/gAAJf/AACZ/gAEmP8AAJ3/AAua+gAAof8ABaH/AASk/wAMo/8ACKT/AGbH/wB/zP8AgYGBAIWFhQCHiIgAiIiIAI2NjQCRkZEAlZWVAJmZmQCenp4AoaGhAKWlpQCoqKgAra2tAKyusACxsbIAtra2ALm5uQC9vb0AuOb/AMHBwQDGxsYAycnJAM/MywDPz88A0tLSANTU1ADZ2dkA3d3dAN/g4ADj4+MA6enpAPHx8QD09PQA+fn5AP7+/gDwwwAA/9IRAP/YMQD/3VEA/+RxAP/qkQD/8LEA//bRAP///wAAAAAALxQAAFAiAABwMAAAkD4AALBNAADPWwAA8GkAAP95EQD/ijEA/51RAP+vcQD/wZEA/9KxAP/l0QD///8AAAAAAC8DAABQBAAAcAYAAJAJAACwCgAAzwwAAPAOAAD/IBIA/z4xAP9cUQD/enEA/5eRAP+2sQD/1NEA////AAAAAAAvAA4AUAAXAHAAIQCQACsAsAA2AM8AQADwAEkA/xFaAP8xcAD/UYYA/3GcAP+RsgD/scgA/9HfAP///wAAAAAALwAgAFAANgBwAEwAkABiALAAeADPAI4A8ACkAP8RswD/Mb4A/1HHAP9x0QD/kdwA/7HlAP/R8AD///8AAAAAACwALwBLAFAAaQBwAIcAkAClALAAxADPAOEA8ADwEf8A8jH/APRR/wD2cf8A95H/APmx/wD70f8A////AAAAAAAbAC8ALQBQAD8AcABSAJAAYwCwAHYAzwCIAPAAmRH/AKYx/wC0Uf8AwnH/AM+R/wDcsf8A69H/AP///wAAAAAACAAvAA4AUAAVAHAAGwCQACEAsAAmAM8ALADwAD4R/wBYMf8AcVH/AIxx/wCmkf8Av7H/ANrR/wD///8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8PAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADAaCAAAAAAAAAAACBswAAAAAAAAAAAAAAAAAAAALAgAAAAAAAAAAAAAAAAAAAAACCwAAAAAAAAAAAAAHQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAfAAAAAAAAMAAAAAAAAAAAAAAAADhkAAAAAAAAAAAAAAAAMAAAADAAAAAAAAAAAAAAAAAhhIUwAAAAAAAAAAAAAAAALwAAAAAAABQAAAAAAAAACnyPj34aAAAAAAAAABEDAAAAADMDAAAhfzsEAAAAAABoj4+Pj2sAAAAAAAAtaR8AAAAyLAQACHiPj2wQAAAAMoaPj4+EMAAAAAAENW9wZQkAACEsBAE8j4+Pj28IABqBj4+PjzkAAAAABDZvb29vNAMAISwDCniPj4+Pj2kKb4+Pj49wAQAAAAAyb29vb3BoEAAhLAQDE2qPj4+PhXeFj4+PfRIAAAAAL29vbm9wORMDACEsBAAAADmGj4+Pj4+Pj4MgAAAAACBub29ucDMCAAAAIS8IAAAAADyPj4+Pj4+POQAAAAASam9ub3A2AwAAAAAhMREKBAEAAGiPj4+Pj20DAAAABDxvbm9vOAIAAAAAACEzGxMRCgQDaY+Pj4+PbQMAAAA1cG9ub282AQAAAAAAITYfHBoTCWWPj4+Pj4+GOAAAIm9vb25vbm80AAAAAAAhOS0hHRtlho+Pj4+Pj4+CHxBqb25vb29ub28xAwAAACE7My8ycI+Pj4+PeYaPj496Z29vbm9nb29vb243EgMAIWY3N3+Pj4+Pj3AcdI+Pj4+Cbm5wZAo1cW5vb29oEAAhaTw5dI+Pj494LRwwgo+Pj498bm0bAAg5cG9ucDYDACFsamdkgI+PeTQvLyA8ho+Pj4Z6MQMEAAg3cHBoCgAAIXRvbGlvg3U6NzY0MS9wj4+Pj3ASERAIAQQxbB8AAAA2AHBybmxuaGVkOzg3MzWAj4+CLRsbFBMQCQQUBAAAAwAAeHR1cm9tbGpoZDs6NmaFj2QiIiAdHBoTEQkICAQ4AAAAfHR4d3Nwbm1raWdkOXJ0MzIxLywhHx0bGhMaZgAAAAAAAHl1eHd1c3BtbGpoZDw5ODUzMjAtLCAdZAAAAAAAAAAAAAB9d3V1dXRyb21raGdkOzk3NDI2bgAAAAAAAAAAAAAAAAAAAH55dXJycG5sa2hnaG13AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP///////n///4AB//wAAD/wAAAPwAAAA4AAAAGAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAGAAAABwAAAA/AAAA/8AAA//4AB////////////KAAAABAAAAAgAAAAAQAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQoABAcKAAAFDgAACA0ACAgIAAgKDAAPDw8AEhAOABQQDQAADhgAAhAZABAQEAAWEhAAEBQXABUVFQAZGRkAHx4dAAAYKAAMHywAJSUlACkpKQAvLy8AMjIyADY2NgA5OTkAPDw8AAArSAACOV4ABTteAAk+YgAAR3YAAEt9AAZPfwAKTnoAQEBAAEdHRwBMR0MASEhIAFJSUgBWVlYAWVlZAF1dXQBiYmIAZmZmAGpqagBycnIAdXV1AHl5eQABXp8AD2afAABkqAAAa7EAEHO0AEeDrAAAg9kAB4neAACb+wAAmf0ABZn8AAGd/gAAof8AAaX/AHLL/wCDg4MAh4eHAJGRkQCXl5cAmZmZAKGhoQCkpKQAqqelAK2trQCxsbEAtbW1ALq6ugDDw8MAycnJAM7OzgDV1dUA2traAN3d3QDk5OQA7OztAPLw7wD09PQA+vr6APj//wD+/v4APf8xAFv/UQB5/3EAmP+RALX/sQDU/9EA////AAAAAAAULwAAIlAAADBwAAA9kAAATLAAAFnPAABn8AAAeP8RAIr/MQCc/1EArv9xAMD/kQDS/7EA5P/RAP///wAAAAAAJi8AAEBQAABacAAAdJAAAI6wAACpzwAAwvAAANH/EQDY/zEA3v9RAOP/cQDp/5EA7/+xAPb/0QD///8AAAAAAC8mAABQQQAAcFsAAJB0AACwjgAAz6kAAPDDAAD/0hEA/9gxAP/dUQD/5HEA/+qRAP/wsQD/9tEA////AAAAAAAvFAAAUCIAAHAwAACQPgAAsE0AAM9bAADwaQAA/3kRAP+KMQD/nVEA/69xAP/BkQD/0rEA/+XRAP///wAAAAAALwMAAFAEAABwBgAAkAkAALAKAADPDAAA8A4AAP8gEgD/PjEA/1xRAP96cQD/l5EA/7axAP/U0QD///8AAAAAAC8ADgBQABcAcAAhAJAAKwCwADYAzwBAAPAASQD/EVoA/zFwAP9RhgD/cZwA/5GyAP+xyAD/0d8A////AAAAAAAvACAAUAA2AHAATACQAGIAsAB4AM8AjgDwAKQA/xGzAP8xvgD/UccA/3HRAP+R3AD/seUA/9HwAP///wAAAAAALAAvAEsAUABpAHAAhwCQAKUAsADEAM8A4QDwAPAR/wDyMf8A9FH/APZx/wD3kf8A+bH/APvR/wD///8AAAAAABsALwAtAFAAPwBwAFIAkABjALAAdgDPAIgA8ACZEf8ApjH/ALRR/wDCcf8Az5H/ANyx/wDr0f8A////AAAAAAAIAC8ADgBQABUAcAAbAJAAIQCwACYAzwAsAPAAPhH/AFgx/wBxUf8AjHH/AKaR/wC/sf8A2tH/AP///wAAAAAAADApJiYpMAAAAAAAAAAAFQAAAAAAAAAAFQAAAAAWAAAAAAAnKQAAAAAAFgApABQMAAAPUlMUAAAFEAApFA9PSgwARF9VGQAFL0IHFBQoX19GKV9fLQAALUhIIxQVBS5YX1ZfSAAAJ0hHJwUUGAUAMF9fURAAFkZIKAAAFCYQADBfX1EMBUJIRycAABQrGkFWX1ZfRixIRkdHJwIUMENfX0svWF9ORiQtSEgaFERCU1AqGUlfWEEABjBDDBRORkhCLywsU1QkEAcPEQAsAE5KSEVCMEZEJCMXEQcoAAAAAE5LSUZCQC8rKEAAAAAAAAAAAABQTkxNAAAAAAAA+B8AAOAHAACAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIABAADgBwAA/D8AACgAAAAgAAAAQAAAAAEAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWAAAAMgAAAFIAAABrAAAAfAAAAIEAAACBAAAAfAAAAGsAAABSAAAAMgAAABYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAADMAAAB2AAAAsQAAAN0AAAD4AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD4AAAA3QAAALEAAAB2AAAAMwAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFAAAAGcAAAC+AAAA9gAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD2AAAAvgAAAGcAAAAUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABQAAAFsAAADQAAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8BAQH/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANAAAABbAAAABQAAAAAAAAAAAAAAAAAAABsAAACxAAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/bm5u/39/f/8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAACxAAAAGwAAAAAAAAAJAAAAtAAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/zo6Ov/09PT/+Pj4/0xMTP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAC0AAAACQAAAFkBAQH/AAAA/wAAAP8AAAD/Hx8f/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8PDw//z8/P////////////2dnZ/yAgIP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/ExMT/wICAv8AAAD/AAAA/wAAAP8AAABZBQUFqAMDA/8AAAD/AAAA/zk5Of/c3Nz/eHh4/wUFBf8AAAD/AAAA/wAAAP8AAAD/AAAA/4+Pj///////////////////////l5eX/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/0ZGRv+RkZH/MTEx/wAAAP8AAAD/AAAA/wAAAKgKCgrGBAQE/wAAAP8JCQn/w8PD////////////n5+f/w8PD/8AAAD/AAAA/wAAAP9VVVX/+/v7//////////////////T09P9LS0v/AAAA/wAAAP8AAAD/AAAA/wUFBf9gYGD/qKio/6urq/+Ghob/CwsL/wAAAP8AAAD/AAAAxgoKCsUEBAT/AQEB/35+fv//////////////////////qKio/wkJCf8AAAD/ICAg/+Pj4///////////////////////cHBw/wAAAP8AAAD/AAAA/wAAAP8AAAD/ZWVl/6qqqv+np6f/pqam/6mpqf9cXFz/AgIC/wAAAP8AAADFCgoKxQICAv8MDAz/x8fH////////////////////////////kJCQ/w0NDf+np6f//////////////////////6ysrP8EBAT/AAAA/wAAAP8AAAD/AAAA/1ZWVv+pqan/p6en/6ampv+np6f/ra2t/46Ojv8PDw//AAAA/wAAAMUKCgrFBAQE/wEBAf8aGhr/lZWV///////////////////////6+vr/wcHB//r6+v/////////////////U1NT/FxcX/wAAAP8AAAD/AAAA/wAAAP9JSUn/qKio/6enp/+mpqb/p6en/6ysrP9xcXH/GRkZ/wEBAf8AAAD/AAAAxQsLC8UFBQX/AAAA/wAAAP8AAAD/cXFx//z8/P//////////////////////////////////////8fHx/zc3N/8AAAD/AAAA/wAAAP8AAAD/NTU1/6Ojo/+oqKj/pqam/6enp/+srKz/W1tb/wMDA/8AAAD/AAAA/wAAAP8AAADFExMTxQkJCf8BAQH/AAAA/wAAAP8AAAD/fX19//////////////////////////////////////9ycnL/AAAA/wAAAP8AAAD/AAAA/xYWFv+UlJT/qamp/6ampv+np6f/rKys/2NjY/8BAQH/AAAA/wAAAP8AAAD/AAAA/wAAAMUeHh7GFBQU/wsLC/8GBgb/AwMD/wAAAP8AAAD/jY2N////////////////////////////o6Oj/wEBAf8AAAD/AAAA/wAAAP8HBwf/fHx8/6qqqv+mpqb/pqam/6qqqv9ra2v/AwMD/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAAxSwsLMcjIyP/GBgY/xMTE/8ODg7/BgYG/wICAv+RkZH///////////////////////////+hoaH/AgIC/wAAAP8AAAD/AAAA/2BgYP+qqqr/p6en/6ampv+mpqb/qamp/2dnZ/8CAgL/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAADFOjo6yDMzM/8oKCj/IiIi/xgYGP8LCwv/hYWF//////////////////////////////////39/f9ubm7/AAAA/wAAAP88PDz/p6en/6enp/+mpqb/pqam/6ampv+mpqb/p6en/1xcXP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAMVJSUnIRERE/zk5Of8sLCz/JCQk/4WFhf/8/Pz//////////////////////////////////////+rq6v8xMTH/ERER/5WVlf+pqan/pqam/6ampv+qqqr/p6en/6ampv+np6f/paWl/1JSUv8BAQH/AAAA/wAAAP8AAAD/AAAAxVlZWcpYWFj/S0tL/1RUVP+tra3////////////////////////////Ly8v//Pz8/////////////////8zMzP+IiIj/p6en/6ampv+mpqb/qKio/4eHh/+np6f/p6en/6ampv+np6f/p6en/2dnZ/8VFRX/AgIC/wAAAP8AAADFaGhoy2pqav9oaGj/3d3d////////////////////////////rq6u/ygoKP+4uLj//////////////////////+jo6P+mpqb/paWl/6urq/+BgYH/DQ0N/2FhYf+urq7/p6en/6ampv+np6f/qamp/4yMjP8QEBD/AAAA/wAAAMV4eHjNfn5+/3BwcP+4uLj//////////////////////8fHx/9ERET/KSkp/01NTf/p6en//////////////////////9LS0v+np6f/oaGh/yUlJf8AAAD/CQkJ/3Jycv+urq7/p6en/6ampv+srKz/ZGRk/wICAv8AAAD/AAAAxoeHh8yUlJT/hoaG/4ODg//f39/////////////IyMj/Xl5e/0tLS/9ISEj/Nzc3/319ff/8/Pz//////////////////v7+/83Nzf9PT0//AQEB/wQEBP8AAAD/CAgI/2lpaf+tra3/rKys/42Njf8MDAz/AAAA/wAAAP8AAADEkpKSpqioqP+cnJz/kJCQ/6ioqP/x8fH/vb29/3V1df9oaGj/ZWVl/1xcXP9TU1P/R0dH/66urv//////////////////////rq6u/xcXF/8TExP/EBAQ/wsLC/8DAwP/BQUF/1BQUP+cnJz/NDQ0/wAAAP8AAAD/AAAA/wAAAJqwsLBQqqqq/7Kysv+mpqb/n5+f/6SkpP+MjIz/hoaG/4CAgP94eHj/b29v/2dnZ/9bW1v/YGBg/9/f3////////////+jo6P9FRUX/JCQk/yQkJP8dHR3/GBgY/xISEv8KCgr/BgYG/xwcHP8FBQX/AAAA/wAAAP8AAAD+AAAAQenp6QWoqKiju7u7/7y8vP+xsbH/qKio/6Kiov+bm5v/k5OT/4uLi/+Dg4P/e3t7/3Nzc/9lZWX/h4eH//j4+P/+/v7/gYGB/zs7O/88PDz/NTU1/y4uLv8nJyf/ICAg/xoaGv8TExP/CwsL/wkJCf8ICAj/BgYG/wMDA5MAAAABAAAAAOPj4w+0tLSXubm5+MTExP+/v7//tra2/6+vr/+np6f/oKCg/5iYmP+QkJD/iIiI/4CAgP9ycnL/srKy/7e3t/9aWlr/V1dX/1BQUP9ISEj/QUFB/zk5Of8yMjL/Kysr/yQkJP8hISH/Gxsb/xcXF/IeHh6HBgYGBwAAAAAAAAAAAAAAAAAAAADOzs49tLS0sry8vP/Gxsb/w8PD/7u7u/+zs7P/q6ur/6Ojo/+bm5v/lJSU/4yMjP+Dg4P/fHx8/3Jycv9ra2v/Y2Nj/1tbW/9TU1P/TU1N/0ZGRv8/Pz//Nzc3/ywsLPs6OjqkdXV1MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADu7u4Dz8/PSLy8vKG6urrlvr6+/7+/v/+9vb3/uLi4/7CwsP+oqKj/oKCg/5eXl/+Pj4//iIiI/4GBgf95eXn/cXFx/2lpaf9eXl7/VFRU/1JSUt9mZmaWmZmZPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAOPj4xrOzs5Wv7+/kri4uMK1tbXmsrKy+a+vr/+srKz/pqam/5+fn/+YmJj/jo6O/4WFhfiAgIDjgYGBvY2NjYqqqqpNz8/PEwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8fHxBebm5hja2towzs7OScbGxlrGxsZfwsLCXsDAwFjFxcVH0dHRLN/f3xXu7u4CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA///////AA//8AAA/8AAAD8AAAAOAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAB4AAAB/AAAB/+AAB//8AD//////8oAAAAEAAAACAAAAABACAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADgAAAEsAAACEAAAApwAAALcAAAC3AAAApwAAAIQAAABLAAAADgAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAdQAAANYAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANYAAAB1AAAAEAAAAAAAAAApAAAA0AAAAP8AAAD/AAAA/wAAAP8AAAD/UlJS/1paWv8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAANAAAAApAQEBpgAAAP8mJib/Dw8P/wAAAP8AAAD/FhYW/+Tk5P/t7e3/JCQk/wAAAP8AAAD/BgYG/xoaGv8AAAD/AAAApgICAtoUFBT/1dXV/7e3t/8QEBD/AAAA/5qamv//////9PT0/zMzM/8AAAD/CAgI/3R0dP+Ojo7/Dw8P/wAAANoAAADbVVVV////////////pKSk/1paWv/+/v7//////2pqav8AAAD/AgIC/21tbf+tra3/rq6u/z8/P/8AAADbBQUF2ggICP9ycnL//Pz8///////6+vr//////66urv8CAgL/AAAA/1FRUf+srKz/qamp/1NTU/8HBwf/AAAA2hQUFNoDAwP/AAAA/3Z2dv///////////93d3f8XFxf/AAAA/y4uLv+mpqb/q6ur/1VVVf8AAAD/AAAA/wAAANotLS3cGRkZ/wMDA/94eHj////////////b29v/ERER/wcHB/+Ojo7/q6ur/6mpqf9RUVH/AAAA/wAAAP8AAADaS0tL3Tw8PP+Hh4f/+/v7///////7+/v//////6ampv9nZ2f/qqqq/6ampv+pqan/pqam/01NTf8FBQX/AAAA2mVlZd+Xl5f///////////+5ubn/dnZ2//39/f//////0NDQ/6ampv9CQkL/bW1t/66urv+srKz/Pj4+/wAAANuLi4vdkpKS/+zs7P/Y2Nj/XV1d/zk5Of+zs7P///////7+/v+IiIj/AAAA/woKCv97e3v/lJSU/xEREf8AAADYsLCwoaampv+tra3/kJCQ/3Z2dv9lZWX/Z2dn/+3t7f/v7+//RkZG/xkZGf8PDw//FBQU/yAgIP8AAAD/AAAAmefn5yK+vr7EtLS0/62trf+goKD/kJCQ/3h4eP+jo6P/mZmZ/0dHR/9AQED/MTEx/x0dHf8PDw//GxsbvQMDAxwAAAAA9PT0CNbW1mPDw8PIurq6+7CwsP+kpKT/k5OT/4ODg/90dHT/YWFh/1RUVPpdXV3Dj4+PXHt7ewUAAAAAAAAAAAAAAAAAAAAA9vb2BePj4znS0tJzw8PDmbi4uKupqamxp6enm7KysnDNzc018/PzAwAAAAAAAAAAAAAAAOAHrEGAAaxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBAACsQQAArEEAAKxBgAGsQeAHrEE=';\n\t\t\t}\n\t\t\thead[0].appendChild(icon);\n\t\t}\n\n\t\thead = top.document.getElementById(\"logodesc\");\n\t\tif (head) {\n\t\t\thead.parentNode.removeChild(head);\n\t\t}\n\t}", "_show_places_icon(show_icon) {\n\t\tthis.places_indicator = Main.panel.statusArea['places-menu'];\n\t\tif (this.places_indicator && is_shell_version_40) {\n\t\t\tthis.places_indicator.remove_child(this.places_indicator.get_first_child());\n\t\t\tif (show_icon) {\n\t\t\t\tthis.places_icon = new St.Icon({icon_name: PLACES_ICON_NAME, style_class: 'system-status-icon'});\n\t\t\t\tthis.places_indicator.add_child(this.places_icon);\n\t\t\t} else {\n\t\t\t\tthis.places_label = new St.Label({text: _('Places'), y_expand: true, y_align: Clutter.ActorAlign.CENTER});\n\t\t\t\tthis.places_indicator.add_child(this.places_label);\n\t\t\t}\n\t\t}\n\t\tif (this.places_indicator && !is_shell_version_40) {\n\t\t\tthis.places_box = this.places_indicator.get_first_child();\n\t\t\tthis.places_box.remove_child(this.places_box.get_first_child());\n\t\t\tif (show_icon) {\n\t\t\t\tthis.places_icon = new St.Icon({icon_name: PLACES_ICON_NAME, style_class: 'system-status-icon'});\n\t\t\t\tthis.places_box.insert_child_at_index(this.places_icon, 0);\n\t\t\t} else {\n\t\t\t\tthis.places_label = new St.Label({text: _('Places'), y_expand: true, y_align: Clutter.ActorAlign.CENTER});\n\t\t\t\tthis.places_box.insert_child_at_index(this.places_label, 0);\n\t\t\t}\n\t\t}\n\t}", "function IoIosAddCircleOutline (props) {\n return Object(_lib__WEBPACK_IMPORTED_MODULE_0__[\"GenIcon\"])({\"tag\":\"svg\",\"attr\":{\"viewBox\":\"0 0 512 512\"},\"child\":[{\"tag\":\"path\",\"attr\":{\"d\":\"M346.5 240H272v-74.5c0-8.8-7.2-16-16-16s-16 7.2-16 16V240h-74.5c-8.8 0-16 6-16 16s7.5 16 16 16H240v74.5c0 9.5 7 16 16 16s16-7.2 16-16V272h74.5c8.8 0 16-7.2 16-16s-7.2-16-16-16z\"}},{\"tag\":\"path\",\"attr\":{\"d\":\"M256 76c48.1 0 93.3 18.7 127.3 52.7S436 207.9 436 256s-18.7 93.3-52.7 127.3S304.1 436 256 436c-48.1 0-93.3-18.7-127.3-52.7S76 304.1 76 256s18.7-93.3 52.7-127.3S207.9 76 256 76m0-28C141.1 48 48 141.1 48 256s93.1 208 208 208 208-93.1 208-208S370.9 48 256 48z\"}}]})(props);\n}", "function myTnInit( $e, item, GOMidx ) {\n var st='position:absolute;top:50%;left:50%;padding:10px;'\n $e.find('.nGY2GThumbnailSub').append('<button style=\"'+st+'\" type=\"button\" class=\"ngy2info\" data-ngy2action=\"info\">photo info</button>');\n TnSetFavorite( item);\n}", "function TiAdjustBrightness (props) {\n return Object(_lib__WEBPACK_IMPORTED_MODULE_0__[\"GenIcon\"])({\"tag\":\"svg\",\"attr\":{\"version\":\"1.2\",\"baseProfile\":\"tiny\",\"viewBox\":\"0 0 24 24\"},\"child\":[{\"tag\":\"path\",\"attr\":{\"d\":\"M12 6.934l1-2.934c.072-.213.078-.452 0-.682-.188-.553-.789-.848-1.341-.659-.553.189-.847.788-.659 1.341l1 2.934zM4 11c-.213-.072-.452-.078-.682 0-.553.188-.848.789-.659 1.341.189.553.788.847 1.341.659l2.934-1-2.934-1zM12 17.066l-1 2.934c-.072.213-.078.452 0 .682.188.553.789.848 1.341.659.553-.189.847-.788.659-1.341l-1-2.934zM21.341 11.657c-.188-.553-.788-.848-1.341-.659l-2.934 1 2.934 1c.213.072.452.078.682 0 .552-.188.847-.789.659-1.341zM5.636 7.05l2.781 1.367-1.367-2.781c-.1-.202-.265-.375-.482-.482-.524-.258-1.157-.042-1.415.482-.257.523-.041 1.157.483 1.414zM5.153 17.432c-.257.523-.041 1.156.482 1.414.523.257 1.157.041 1.414-.482l1.367-2.781-2.781 1.367c-.201.099-.374.263-.482.482zM18.363 16.949l-2.781-1.367 1.367 2.781c.1.202.264.375.482.482.523.257 1.156.041 1.414-.482s.042-1.157-.482-1.414zM18.844 6.566c.258-.524.042-1.157-.481-1.415-.523-.257-1.157-.041-1.414.482l-1.369 2.783 2.782-1.368c.202-.1.375-.264.482-.482zM12 7.5c-2.481 0-4.5 2.019-4.5 4.5s2.019 4.5 4.5 4.5 4.5-2.019 4.5-4.5-2.019-4.5-4.5-4.5z\"}}]})(props);\n}", "function SVGWrap() {}", "function addAuditMark(e, r) {\n var t = document.createElement(\"img\");\n if (r) {\n t.src = \"/green.svg\";\n } else {\n t.src = \"/red.svg\";\n }\n e.appendChild(t);\n }", "function Icon(el,config){if(el&&el.tagName!='svg'){el=angular.element('<svg xmlns=\"http://www.w3.org/2000/svg\">').append(el.cloneNode(true))[0];}// Inject the namespace if not available...\n\tif(!el.getAttribute('xmlns')){el.setAttribute('xmlns',\"http://www.w3.org/2000/svg\");}this.element=el;this.config=config;this.prepare();}", "function widget(el) {\n svg = el\n .datum(geogrify)\n .select(\"svg\")\n .attr(\"viewBox\", \"0 0 \" + width + \" \" + height)\n .call(tooltip)\n ;\n if(~browser.indexOf(\"ie\")) {\n svg\n .attr(\"preserveAspectRatio\", \"xMidYMin slice\")\n .style({\n width: \"100%\"\n , height: \"1px\"\n , overflow: \"visible\"\n })\n .style(\"padding-bottom\", (100 * height / width) + \"%\")\n ;\n }\n svg\n .attr(\"role\", \"img\")\n .attr(\"aria-labelledby\", \"title\")\n .append(\"title\")\n .attr(\"id\", \"title\")\n .text(\"Map of the USA\")\n ;\n svg\n .attr(\"aria-describedby\", \"desc\")\n .append(\"desc\")\n .attr(\"id\", \"desc\")\n .text(\n \"An interactive map of the United States. \"\n + \"Each state changes color to reflect its category or process.\"\n )\n ;\n svg\n .append(\"defs\")\n ;\n svg\n .append(\"g\")\n .attr(\"id\", \"visual\")\n .attr(\"transform\"\n , \"translate(\" + margin.top + \",\" + margin.left + \")\"\n )\n ;\n draw();\n resize();\n }", "async updateSidebarPlaces() {\n let clusters = await this.getFixedSizeGrid(1);\n this.ui.emptyPlaces()\n for (let cluster of clusters) {\n if (!cluster.clusterIcon_.url_)\n continue\n\n this.ui.addPhoto({\n latitude: cluster.center_.lat(),\n longitude: cluster.center_.lng(),\n count: get(['clusterIcon_', 'sums_', 'text'], cluster),\n cover: Photo.resize(cluster.clusterIcon_.url_, 512)\n })\n }\n }", "async updateSidebarPlaces() {\n let clusters = await this.getFixedSizeGrid(1);\n this.ui.emptyPlaces()\n for (let cluster of clusters) {\n if (!cluster.clusterIcon_.url_)\n continue\n\n this.ui.addPhoto({\n latitude: cluster.center_.lat(),\n longitude: cluster.center_.lng(),\n count: get(['clusterIcon_', 'sums_', 'text'], cluster),\n cover: Photo.resize(cluster.clusterIcon_.url_, 512)\n })\n }\n }", "function make_desc(ind){\r\n size_marker_icon(ind);\r\n }", "function showOpenNotes() {\n openNotes.forEach(function (note) {\n const noteButton = createButton(note);\n\n noteButton.style.height = noteButton.style.width = imageHeight / 7 + 'px';\n noteButton.style.margin = 2 + 'px';\n\n fretboardDiv.insertBefore(noteButton, fretboardDiv.firstChild);\n });\n}", "function addOriginIcon(popuptext, marker) {\n const newOriginPoint = document.createElement('div')\n const originPointsContainer = document.getElementById('origin-points-icons')\n newOriginPoint.setAttribute('id',`originMarker-${marker._leaflet_id}`)\n newOriginPoint.innerHTML = `<p>${popuptext}</p>`\n originPointsContainer.append(newOriginPoint)\n\n newOriginPoint.addEventListener('mouseover', function(e) {\n // newOriginPoint.innerHTML += `<style>#origin-points-icons > div {background-image: url(https://vignette.wikia.nocookie.net/creation/images/7/7e/Red_x.png/revision/latest?cb=20160323201834)}</style>`\n })\n\n deleteOriginIcon(newOriginPoint, marker)\n }", "function applyExtendedVersion() {\n\t\t//show avoid areas\n\t\t$('#avoidAreas').show();\n\t\t\n\t\t//show import/export features\n\t\t$('#exportImport').show();\n\t\t\n\t\t//show accessibility analysis\n\t\t$('#accessibilityAnalysis').show();\n\t}", "function activateInspectionToolButton(){\n updateUndoButton();\n detectAndLogInspectionInfo();\n applyMarkup();\n removeWidgetRegionDecorations();\n var inspectorButton = $(\"#perc-region-tool-inspector\");\n inspectorButton.addClass('buttonPressed');\n inspectorButton.css(\"background-position\", \"0px -68px\");\n var iframeContents = _iframe.contents();\n //Add events to html widget content.\n var iframeJQuery = window.frames[0].jQuery;\n\n // Gray out all region puffs\n iframeContents.find('.perc-region-puff').addClass('perc-region-puff-gray');\n iframeContents.find('.perc-new-splitted-region').removeClass('perc-region-puff-gray');\n\n var highligtherDiv = iframeContents.find(\"#itool-placeholder-highlighter\");\n if (highligtherDiv.length < 1) {\n iframeContents.find(\".perc-region:first\").append(\"<div id='itool-placeholder-highlighter' style='display:none;position:absolute;z-index:60000;opacity:0.8;filter:alpha(opacity=80);'></div>\");\n highligtherDiv = iframeContents.find(\"#itool-placeholder-highlighter\");\n }\n\n //Add events to non inspectable events\n addNonInspectableEvents(iframeContents, iframeJQuery, highligtherDiv);\n //Add events to inspectable elements\n addInspectableEvents(iframeContents, iframeJQuery, highligtherDiv);\n\n iframeContents.find(\".perc-region:first\").addClass('perc-itool-custom-cursor').on('mouseleave',function(){\n highligtherDiv.hide();\n iframeContents.find(\".perc-itool-highlighter\").removeClass(\"perc-itool-highlighter\");\n });\n\n _layoutFunctions.removeDropsSortingResizing(true);\n\n }", "function updateIcon() {\n browser.browserAction.setIcon({\n path: currentBookmark ? {\n 19: \"icons/star-filled-19.png\",\n 38: \"icons/star-filled-38.png\"\n } : {\n 19: \"icons/star-empty-19.png\",\n 38: \"icons/star-empty-38.png\"\n } \n });\n browser.browserAction.setTitle({\n // Screen readers can see the title\n title: currentBookmark ? 'Acceptable' : 'Not Acceptable'\n }); \n}", "function iconShow(el) {\r\n eyeIcon.style.display = \"inline-block\";\r\n}", "function renderClickIcon(node) {\n //If this node's type is not in the modal list, don't draw it\n if (modal_types.indexOf(node.type) === -1) {\n node_modal_group.style('display', 'none');\n return;\n } //if\n //Display the modal opening circle to the top right\n\n\n var modal_radius = Math.min(24, Math.max(12, node.r * 0.3));\n var modal_cross_size = 2 * modal_radius / icon_default_size;\n var modal_icon_offset = node.r > 18 ? 0 : modal_radius * 1.5;\n var modal_x = node.x + (node.r + modal_icon_offset) * Math.cos(Math.PI / 4);\n var modal_y = node.y + (node.r + modal_icon_offset) * Math.sin(Math.PI / 4); //Move the modal icon group to the bottom right of the clicked node\n\n node_modal_group.attr('transform', 'translate(' + [modal_x, modal_y] + ')').style('display', null); //Resize the modal icon circle\n\n modal_icon_circle.attr('r', modal_radius).style('stroke-width', Math.max(2, modal_radius * 0.125)); //Resize the modal icon cross\n\n modal_icon_cross.attr('d', d3__WEBPACK_IMPORTED_MODULE_6__[\"symbol\"]().size(Math.pow(modal_cross_size, 2) * 8).type(d3__WEBPACK_IMPORTED_MODULE_6__[\"symbolCross\"]));\n } //function renderClickIcon", "function renderClickIcon(node) {\n //If this node's type is not in the modal list, don't draw it\n if (modal_types.indexOf(node.type) === -1) {\n node_modal_group.style('display', 'none');\n return;\n } //if\n //Display the modal opening circle to the top right\n\n\n var modal_radius = Math.min(24, Math.max(12, node.r * 0.3));\n var modal_cross_size = 2 * modal_radius / icon_default_size;\n var modal_icon_offset = node.r > 18 ? 0 : modal_radius * 1.5;\n var modal_x = node.x + (node.r + modal_icon_offset) * Math.cos(Math.PI / 4);\n var modal_y = node.y + (node.r + modal_icon_offset) * Math.sin(Math.PI / 4); //Move the modal icon group to the bottom right of the clicked node\n\n node_modal_group.attr('transform', 'translate(' + [modal_x, modal_y] + ')').style('display', null); //Resize the modal icon circle\n\n modal_icon_circle.attr('r', modal_radius).style('stroke-width', Math.max(2, modal_radius * 0.125)); //Resize the modal icon cross\n\n modal_icon_cross.attr('d', d3__WEBPACK_IMPORTED_MODULE_6__[\"symbol\"]().size(Math.pow(modal_cross_size, 2) * 8).type(d3__WEBPACK_IMPORTED_MODULE_6__[\"symbolCross\"]));\n } //function renderClickIcon", "function make_desc(ind){\r\n size_marker_icon(ind);\r\n }", "function make_desc(ind){\r\n size_marker_icon(ind);\r\n }", "function Icon(n,s,c,callback){\n\texecute(\"gsettings get org.gnome.desktop.interface icon-theme\",function(stdout){\n\t\tif(stdout != \"\"){theme_name=decodeURIComponent(stdout.replace(/[\"']/g, \"\"));IconFinder(theme_name,n,s,c,callback,true);}else{\n\t\t\texecute(\"grep '^gtk-icon-theme-name' $HOME/.gtkrc-2.0 | awk -F'=' '{print $2}'\",function(stdout){\n\t\t\t\tif(stdout != \"\"){theme_name=decodeURIComponent(stdout.replace(/[\"']/g, \"\"));IconFinder(theme_name,n,s,c,callback,true);}\n\t\t\t})\n\t\t}\n\t})\n}", "function overlay() {\n sketch.strokeWeight(1);\n sketch.stroke(0, 0, 255, 75);\n sketch.fill(0, 0, 255, 75);\n sketch.rectMode(sketch.CENTER);\n sketch.rect(sketch.mouseX, sketch.mouseY, 100, 100);\n }", "function writeOverglass() {\n\t\tvar rect = document.createElement(\"v:rect\");\n\t\trect.setAttribute(\"id\", this.id + \"og\");\n\t\tvar elem = document.getElementById(this.id).appendChild(rect);\n\t\telem.style.position = \"absolute\";\n\t\telem.style.top = 0;\n\t\telem.style.left = 0;\n\t\telem.style.width = this.width;\n\t\telem.style.height = this.height;\n\t\telem.style.zIndex = 8;\n\t\telem.fill.type = \"solid\";\n\t\telem.fill.color = \"white\";\n\t\telem.fill.opacity = \"0%\";\n\t\telem.stroked = \"false\";\n\t\telem.style.cursor = \"move\";\n\t\tif (this.onClicked != null) {\n\t\t\telem.attachEvent(\"onclick\", this.onClicked);\n\t\t}\n\t\telem.parentObj = this;\n\t}", "viewImageInNewTab()\r\n {\r\n document.getElementById(\"context-viewimage\")\r\n .setAttribute(\"oncommand\", `openTrustedLinkIn(gContextMenu.imageURL, \"tab\")`);\r\n }", "function writerIconHover() {\n\tvar x = document.getElementById('writerIcon');\n\tx.setAttribute(\"src\", \"media/w95-notepad-inv.png\");\n}", "oIcon(properties) {\n properties.tag = \"i\";\n properties.class = this.removeLeadingWhitespace(\n `${this.processContent(properties.class)} far fa-${properties.icon}`\n );\n return this.getElement(properties);\n }", "function IoIosAddCircleOutline(props) {\n return (0, _lib.GenIcon)({\n \"tag\": \"svg\",\n \"attr\": {\n \"viewBox\": \"0 0 512 512\"\n },\n \"child\": [{\n \"tag\": \"path\",\n \"attr\": {\n \"d\": \"M346.5 240H272v-74.5c0-8.8-7.2-16-16-16s-16 7.2-16 16V240h-74.5c-8.8 0-16 6-16 16s7.5 16 16 16H240v74.5c0 9.5 7 16 16 16s16-7.2 16-16V272h74.5c8.8 0 16-7.2 16-16s-7.2-16-16-16z\"\n }\n }, {\n \"tag\": \"path\",\n \"attr\": {\n \"d\": \"M256 76c48.1 0 93.3 18.7 127.3 52.7S436 207.9 436 256s-18.7 93.3-52.7 127.3S304.1 436 256 436c-48.1 0-93.3-18.7-127.3-52.7S76 304.1 76 256s18.7-93.3 52.7-127.3S207.9 76 256 76m0-28C141.1 48 48 141.1 48 256s93.1 208 208 208 208-93.1 208-208S370.9 48 256 48z\"\n }\n }]\n })(props);\n}", "getIcon_() {\n return this.isCloudGamingDevice_ ? 'oobe-32:game-controller' :\n 'oobe-32:checkmark';\n }", "function setIcon () {\n if ( oauth.hasToken() ) {\n chrome.browserAction.setIcon( { 'path': 'img/icon-19-on.png' } );\n } else {\n chrome.browserAction.setIcon( { 'path': 'img/icon-19-off.png' } );\n }\n}", "function showToolbarIcon(tabId, iconName) {\n // Change toolbar icon to new icon\n var smallIconPath, bigIconPath\n\n if(isEdge()){\n\n smallIconPath = 'app/images/' + iconName + '-20.png'\n bigIconPath = 'app/images/' + iconName + '-40.png'\n chrome.browserAction.setIcon({\n tabId: tabId,\n path: {\n '20': smallIconPath,\n '40': bigIconPath\n }\n })\n\n }else{\n smallIconPath = 'app/images/' + iconName + '-19.png'\n bigIconPath = 'app/images/' + iconName + '-38.png'\n chrome.browserAction.setIcon({\n tabId: tabId,\n path: {\n '19': smallIconPath,\n '38': bigIconPath\n }\n })\n\n }\n\n }", "function addHoverIcons(graph, iconTolerance = 20) {\n graph.addMouseListener(\n {\n currentState: null,\n currentIconSet: null,\n mouseDown: function(sender, me) {\n // Hides icons on mouse down\n if (this.currentState != null) {\n this.dragLeave(me.getEvent(), this.currentState);\n this.currentState = null;\n }\n },\n mouseMove: function(sender, me) {\n if (this.currentState != null &&\n (me.getState() == this.currentState ||\n me.getState() == null)) {\n var tol = iconTolerance;\n var tmp = new mxRectangle(me.getGraphX() - tol,\n me.getGraphY() - tol,\n 2 * tol,\n 2 * tol);\n\n if (mxUtils.intersects(tmp, this.currentState)) {\n return;\n }\n }\n\n var tmp = graph.view.getState(me.getCell());\n\n // Ignores everything but FRO with more then 1 element\n if (tmp != null && !isFRO(graph.model.getParent(tmp.cell))) {\n // (graph.isMouseDown || (!graph.getModel().isVertex(tmp.cell)) && ) ) {\n tmp = null;\n }\n\n if (tmp != this.currentState) {\n if (this.currentState != null) {\n this.dragLeave(me.getEvent(), this.currentState);\n }\n\n this.currentState = tmp;\n\n if (this.currentState != null) {\n this.dragEnter(me.getEvent(), this.currentState);\n }\n }\n },\n mouseUp: function(sender, me) {},\n dragEnter: function(evt, state) {\n if (this.currentIconSet == null) {\n var parent = graph.model.getParent(state.cell);\n var first = isFirst(state.cell, parent);\n var last = isLast(state.cell, parent);\n this.currentIconSet = new mxIconSet(state, last, first, (!first && !last));\n\n }\n },\n dragLeave: function(evt, state) {\n if (this.currentIconSet != null) {\n this.currentIconSet.destroy();\n this.currentIconSet = null;\n }\n }\n });\n}", "function createTrackerBlockedIcon() {\n\tvar tabs = require(\"sdk/tabs\");\n\tvar panel = require(\"sdk/panel\");\n\tvar widget = require(\"sdk/widget\");\n\tvar data = require(\"sdk/self\").data;\n\tvar filePaths = require(\"./File Paths\");\n\t\n\tvar popup = panel.Panel({\n\t\tcontentScriptWhen: \"ready\",\n\t\tcontentURL: data.url(filePaths.POPUP)\n\t});\n\t\n\tvar addonBarIcon = widget.Widget({\n\t\tid: \"addonBarIcon\",\n\t\tlabel: \"ShareMeNot\",\n\t\tcontentURL: data.url(filePaths.WIDGET),\n\t\tpanel: popup\n\t});\n\t\n\t// listeners for events from the browser responding to the user showing\n\t// and hiding the popup\n\tpopup.on(\"show\", function() {\n\t\tpopup.port.emit(\"open\");\n\t});\n\tpopup.on(\"hide\", function() {\n\t\tpopup.port.emit(\"hide\");\n\t});\n\t\n\t// listeners for messages coming from the popup page\n\tpopup.port.on(\"popupInitialize\", function() {\n\t\tvar activeTabId = tabs.activeTab.sharemenotId;\n\t\tvar popupData = getDataForPopup(activeTabId);\n\t\tpopup.port.emit(\"popupInitializeResponse\", popupData);\n\t});\n\t\n\tpopup.port.on(\"reloadActiveTab\", function() {\n\t\tvar activeTab = tabs.activeTab;\n\t\tactiveTab.reload();\n\t});\n\t\n\tpopup.port.on(\"blockTrackerOnActiveTab\", function(trackerName) {\n\t\tvar activeTabId = tabs.activeTab.sharemenotId;\n\t\tblockTrackerOnTab(activeTabId, trackerName);\n\t});\n\tpopup.port.on(\"unblockTrackerOnActiveTab\", function(trackerName) {\n\t\tvar activeTabId = tabs.activeTab.sharemenotId;\n\t\tunblockTrackerOnTab(activeTabId, trackerName);\n\t});\n\tpopup.port.on(\"unblockAllTrackersOnActiveTab\", function() {\n\t\tvar activeTabId = tabs.activeTab.sharemenotId;\n\t\tunblockAllTrackersOnTab(activeTabId);\n\t});\n\t\n\tpopup.port.on(\"resizeToFit\", function(details) {\n\t\tvar width = details.width;\n\t\tvar height = details.height;\n\t\tpopup.resize(width, height);\n\t});\n\t\n\tpopup.port.on(\"close\", function() {\n\t\tpopup.hide();\n\t});\n\t\n\t//trackerBlockedIcon = addonBarIcon;\n}", "_renderWorkoutMarker(workout) {\n // places marker where user clicks and sets the options for the popup (Display Marker)\n // custom icon\n let mapMarker = L.icon({\n iconUrl: \"icon.png\",\n iconSize: [50, 50],\n iconAnchor: [22, 94],\n popupAnchor: [0, -90],\n });\n\n L.marker(workout.coords, { icon: mapMarker })\n .addTo(this.#map)\n .bindPopup(\n L.popup({\n maxWidth: 250,\n minWidth: 100,\n autoClose: false,\n closeOnClick: false,\n className: `${workout.type}-popup`,\n })\n )\n .setPopupContent(\n `${workout.type === \"running\" ? \"🏃‍♂️\" : \"🚴‍♀️\"} ${workout.description}`\n )\n .openPopup();\n }", "function hide_download_icons_node(){\n if(node_enable() === true){\n CSSLoad(\"style_hide_download_section.css?v01\");\n //CSSLoad(\"style_hide_window_control_section.css?v03\");\n }\n}", "function resetInfoPaneDisplay() {\n gees.dom.setClass('poly_button', '');\n gees.dom.setClass('hand_button', 'clicked_button');\n gees.dom.setClass('CutButtonBlue', 'button blue');\n}", "function fullIcon(icon) {\n return merge_1.merge(exports.iconDefaults, icon);\n}", "newIcon() {\n return `${this.iconPrefix}${this.getEquivalentIconOf(this.icon)}`;\n }", "onClick(event, bounds) {\n // console.log('bounds - ', bounds.x, bounds.y);\n // click event bounds (where status tray icon is located)...\n const { x, y } = bounds;\n // height/width dimensions of window itself; dynamically calculate bounds on the fly (and not hardcoded) so that it works even if user resizes window - will get updated height and width\n const { height, width } = this.mainWindow.getBounds(); \n\n const yPosition = process.platform === 'darwin' ? y : (y - height);\n // dynamically set pos of window (also dimensions)\n this.mainWindow.setBounds({\n x: x - (width / 2),\n y: yPosition,\n height,\n width\n });\n // ^ set size of window before display it\n // this.mainWindow.isAlwaysOnTop();\n this.mainWindow.show();\n\n\n // if (this.mainWindow.isVisible()){\n \n // this.mainWindow.hide();\n // } else {\n // const yPosition = process.platform === 'darwin' ? y : (y - height);\n // // dynamically set pos of window (also dimensions)\n // this.mainWindow.setBounds({\n // x: x - (width / 2),\n // y: yPosition,\n // height,\n // width\n // });\n // // ^ set size of window before display it\n // // this.mainWindow.isAlwaysOnTop();\n // this.mainWindow.show();\n // }\n }", "function setupInteractions() {\n\n\t\t\t$('.img-overlay').hover(\n\t\t\t function () {\n\t\t\t $('.img-overlay-content', this).slideDown();\n\t\t\t },\n\t\t\t function () {\n\t\t\t $('.img-overlay-content', this).fadeOut(100);\n\t\t\t }\n\t\t\t);\n\n\n\t\t\t// tooltip setup\n\t\t $('a[rel=tooltip]').tooltip({\n\t\t placement: \"bottom\"\n\t\t });\n\n // tooltip setup\n $('a.infobit-icon').tooltip({\n placement: \"top\"\n });\n\n\t\t $('div[rel=tooltip]').tooltip({\n\t\t placement: \"top\"\n\t\t });\n\n $('i[rel=tooltip]').tooltip({\n placement: \"top\"\n });\n\n $('a[rel=\"tooltip nofollow\"]').tooltip({\n placement: \"top\"\n });\n\n\t\t}", "function githubIconClick() {\n\twindow.open('https://github.com/mjdargen', '_blank');\n}", "renderIcon() {\n if (!this.state.edittable) {\n return (\n <Ionicon\n icon=\"ion-edit\"\n fontSize=\"20px\"\n color=\"white\"\n style={{position: 'relative', right: '4px', top: '5px'}}\n />\n\n );\n }else if (this.state.mapEditted) {\n return (\n <Ionicon\n icon=\"ion-checkmark-round\"\n fontSize=\"25px\"\n color=\"#00FF00 \"\n style={{position: 'relative', right: '7px', top: '7px'}}\n />\n );\n } else {\n return (\n <Ionicon\n icon=\"ion-checkmark-round\"\n fontSize=\"25px\"\n color=\"#bfbfbf\"\n style={{position: 'relative', right: '7px', top: '7px'}}\n />\n );\n }\n }", "function ThirdIcon() {\n this.setIcon(ThirdOne);\n}", "function SVGParent() {}" ]
[ "0.61194587", "0.5649992", "0.56415045", "0.5597871", "0.55948776", "0.55948776", "0.55651", "0.5488496", "0.54465544", "0.5419494", "0.5375075", "0.53739434", "0.53674793", "0.53476316", "0.53421384", "0.5298013", "0.52397525", "0.52383924", "0.521763", "0.52105266", "0.5199486", "0.5194632", "0.51872987", "0.5159426", "0.51462", "0.5141276", "0.5138792", "0.5135485", "0.5119631", "0.5104919", "0.51044667", "0.50954634", "0.509431", "0.50928086", "0.5089072", "0.50815356", "0.5077989", "0.506739", "0.5062827", "0.50584185", "0.50575066", "0.50503254", "0.50503254", "0.50503254", "0.5048847", "0.50455993", "0.50395405", "0.5025901", "0.50140303", "0.50097173", "0.5008789", "0.5002842", "0.4999011", "0.49970418", "0.4991838", "0.49913946", "0.49794814", "0.49784592", "0.49763316", "0.49756673", "0.49739745", "0.49705446", "0.4969146", "0.4954595", "0.49466845", "0.49459445", "0.49459445", "0.49455795", "0.4945256", "0.49387038", "0.49365345", "0.49344486", "0.4933482", "0.49277234", "0.49262124", "0.49262124", "0.49202615", "0.49202615", "0.49195287", "0.49091887", "0.49083602", "0.4905518", "0.49052802", "0.4897814", "0.48976386", "0.4896105", "0.48882037", "0.48854163", "0.48769832", "0.4876003", "0.48755062", "0.48730516", "0.48719966", "0.48658937", "0.48643637", "0.4863239", "0.48588064", "0.4855724", "0.48485848", "0.48436517", "0.48324332" ]
0.0
-1
2 things that the reducer needs to run properly
function cartReducer(state = initialState, action) { switch(action.type) { case 'ADD_TO_CART': // check if payload is already in the cart, and use the new one. return [...state, action.payload]; case 'REMOVE_FROM_CART': default: return state; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reducer(){\n\n}", "reducer(res) {\n return res;\n }", "function reducer(a,b) {\n return a + b;\n}", "function greetingReducer() {}", "reduce(state, payload) {\n let {action, data} = payload;\n\n switch(action) {\n case 'moveTo':\n state = state.withMutations(s => {\n s = s.set('isMoving', true);\n s = s.set('movingTo', [data[0], data[1]]);\n });\n break;\n case 'stopMoving':\n state = state.withMutations(s => {\n let movingTo = s.get('movingTo');\n s = s.set('x', movingTo[0]);\n s = s.set('z', movingTo[1]);\n s = s.set('isMoving', false);\n s = s.set('movingTo', null);\n });\n break;\n case 'turnTo':\n state = state.withMutations(s => {\n s = s.set('isTurning', true);\n s = s.set('turningTo', data);\n });\n break;\n case 'stopTurning':\n state = state.withMutations(s => {\n s = s.set('isTurning', false);\n s = s.set('dir', s.get('turningTo'));\n });\n break;\n case 'turn':\n state = state.updateIn(['dir'], dir => {\n dir = (dir + data)%4;\n if(dir < 0) {\n dir = 4 + dir;\n }\n return dir;\n })\n break;\n case 'inventory':\n state = state.updateIn(['inventory'], inventory => inventory.push(1));\n break;\n }\n\n return state;\n }", "function reducer (input, context) {\n console.log('INPUT:')\n console.log(input)\n console.log('\\nCONTEXT:')\n console.log(JSON.stringify(context, null, 2))\n}", "function reducer(a,b){\n return a += b;\n }", "reduce(state, payload) {\n let {action, data} = payload;\n\n switch(action) {\n case 'move':\n state = state.updateIn(['currentRoom'], value => value += data);\n break;\n }\n\n return state;\n }", "function reducer(state=defaultState, action) {\n switch (action.type) {\n case INCREMENT_ORDER:\n console.log(state[0].orderNum);\n console.log(\"action.order\" + action.order);\n const updatedStateObj = {...state[0], orderNum: action.order + 1};\n return [updatedStateObj];\n case ADD_SELECTIONS:\n console.log(action.selection);\n const newSelections = [...state[0].selections, action.selection];\n console.log(newSelections);\n const ObjWithNewSelections = {...state[0], selections: newSelections};\n console.log(ObjWithNewSelections);\n return [ObjWithNewSelections];\n case ADD_PROFIT:\n console.log(\"total money: \" + state[0].totalMoney);\n console.log(\"action.profit: \" + action.profit);\n const ObjWithUpdatedMoney = {...state[0], totalMoney: state[0].totalMoney + action.profit};\n console.log(\"total money updated: \" + ObjWithUpdatedMoney.totalMoney);\n return [ObjWithUpdatedMoney];\n case UPDATE_THIS_ROUND_RATING:\n console.log(\"thisRoundRating\" + state[0].thisRoundRating);\n console.log(\"action.changedRating\" + action.changedRating);\n if (state[0].thisRoundRating + action.changedRating <= 5.0){\n const ObjWithUpdatedRating = {...state[0], thisRoundRating: state[0].thisRoundRating + action.changedRating};\n return [ObjWithUpdatedRating];\n }else {\n const ObjWithMaxRating = {...state[0], thisRoundRating: 5.0};\n return [ObjWithMaxRating];\n }\n case RESET_ROUND_RATING:\n const ObjWithInitialRating = {...state[0], thisRoundRating: 5.0};\n return [ObjWithInitialRating];\n case ADD_RATING:\n console.log(\"ratings: \" + state[0].ratings);\n console.log(action.rating);\n const newRatings = [...state[0].ratings, action.rating];\n console.log(newRatings);\n const ObjWithNewRatings = {...state[0], ratings: newRatings};\n console.log(ObjWithNewRatings);\n return [ObjWithNewRatings];\n case RESET_RATINGS:\n const ObjWithNoRatings = {...state[0], ratings: []};\n return [ObjWithNoRatings];\n case RESET_ORDER_NUM:\n const ObjWithInitialOrderNum = {...state[0], orderNum: 0};\n return [ObjWithInitialOrderNum];\n case RESET_SELECTIONS:\n const ObjWithNoSelections = {...state[0], selections: []};\n return [ObjWithNoSelections];\n case RESET_MONEY:\n const ObjWithInitialMoney = {...state[0], totalMoney: 80};\n return [ObjWithInitialMoney];\n case RESET_TIME_REMAINED:\n const ObjWithInitialTime = {...state[0], timeRemained: 20};\n return [ObjWithInitialTime];\n // case UPDATE_TIME_REMAINED:\n // console.log(state[0].timeRemained);\n // console.log(\"action.changedRating\" + action.timeSpent);\n // const ObjWithUpdatedTime = {...state[0], timeRemained: state[0].timeRemained - action.timeSpent};\n // return [ObjWithUpdatedTime];\n default:\n console.log(state[0].orderNum);\n return state;\n }\n}", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {\n\t isFetching: false,\n\t isAuthenticated: _utils.webStorage.getItem('token') ? true : false,\n\t token: _utils.webStorage.getItem('token'),\n\t userId: _utils.webStorage.getItem('userId'),\n\t account: {}\n\t };\n\t var action = arguments[1];\n\t\n\t switch (action.type) {\n\t case _loginActions.LOGIN_REQUEST:\n\t return Object.assign({}, state, {\n\t isFetching: true,\n\t isAuthenticated: false\n\t });\n\t case _loginActions.LOGIN_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t isAuthenticated: true,\n\t errorMessage: ''\n\t });\n\t case _loginActions.LOGIN_FAILURE:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t isAuthenticated: false,\n\t errorMessage: action.message\n\t });\n\t case _logoutActions.LOGOUT_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: true,\n\t isAuthenticated: false\n\t });\n\t case _getAccountActions.GET_ACCOUNT_REQUEST:\n\t return Object.assign({}, state, {\n\t isFetching: true\n\t });\n\t case _getAccountActions.GET_ACCOUNT_SUCCESS:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t account: action.account,\n\t errorMessage: ''\n\t });\n\t case _getAccountActions.GET_ACCOUNT_FAILURE:\n\t return Object.assign({}, state, {\n\t isFetching: false,\n\t errorMessage: action.message\n\t });\n\t default:\n\t return state;\n\t }\n\t}", "actionReducer(action){\n return unitActionReducer.call(this, this.state, action);\n }", "reduce(state, action) {\n // Because this is a template for specific ReduceStores, we expect this to be overwritten by specific sub-ReduceStores\n // So we'll simply throw an error telling the user this, if the primary ReduceStore's reduce method is called\n throw new Error('\"ReduceStore.reduce\": Substores must override reduce method of a Flux ReduceStore');\n }", "function Reducer2(state = INITIAL_STATE, action) {\r\n switch(action.type) {\r\n default : {\r\n\r\n const var_name = action.argument_var_name;\r\n let NEW_STATE = [];\r\n if(Math.max.apply(Math, warehouse) < action[var_name]) {\r\n warehouse.push(action[var_name]);\r\n console.log(warehouse)\r\n NEW_STATE = [...INITIAL_STATE, action[var_name]];\r\n }\r\n else {\r\n NEW_STATE = [...INITIAL_STATE, Math.max.apply(Math, warehouse)];\r\n }\r\n //alert(`In Reducer:\\n ${ JSON.stringify(action) },\\n-------------\\n, ${ JSON.stringify(state) }`);\r\n \r\n \r\n return NEW_STATE;\r\n }\r\n }\r\n }", "function reduce(currState, { type, payload }){\n return (type in actions) ? actions[type](currState, payload) : currState;\n }", "function reducer(total, num) {\n return total + num\n }", "function Reducer(state = loadState() , action) {\n switch (action.type) {\n case 'UPDATE':\n let newState = [...state];\n newState[action.index] = action.data\n return newState;\n default:\n return state\n }\n}", "function reducer(result, value, index) {\n const fieldId = info.fields[index].id\n const processorId = info.fields[index].type\n const processor = get(processorId, processType)\n return set(fieldId, processor(value), result)\n }", "reduce(state, action) {\n\t\tswitch (action) {\n\t\t\tcase 'blue':\n\t\t\t\treturn Object.assign({}, state, { blue: state.blue + 1 });\n\t\t\tcase 'red':\n\t\t\t\treturn Object.assign({}, state, { red: state.red + 1 });\n\t\t\tdefault:\n\t\t\t\treturn state;\n\t\t}\n\t}", "function reducer(state, action) {\n //b. create switch statement where each case is a possible action.type\n switch (action.type) {\n case 'ACTION_TYPE':\n return state.someMethod(action.payload)\n default:\n return state;\n }\n }", "reducer(book) {\n return {\n // cursor: `${launch.launch_date_unix}`,\n cursor: 1,\n id: book.isbn13,\n title: book.title,\n subtitle: book.subtitle,\n isbn13: book.isbn13,\n author: book.author,\n link: book.link,\n };\n }", "function runtimeReducer(state, action) {\n switch (action.type) {\n case 'SET':\n return action.payload\n case 'RESET':\n return 0\n default:\n return state\n }\n}", "function reduce(reducer, reducible) {\n\t return transformWithSpec(reducer, reducible, _shiftSpec2.default[reducible.type]);\n\t}", "function reducer(state = estadoInicial, algo){\n switch(algo.type){\n case agregarTarea: {\n if(!algo.payload){\n return[]\n }\n return[\n ...state,\n algo.payload\n ]\n }\n default: \n return state\n }\n}", "function reducer (currentState=getInitialState(), action) {\n console.log(\"Current State:\", currentState, \"Action:\", action)\n //based on the action.type, return {newState}\n switch(action.type){\n case BIGGER_COUNT:\n return {...currentState, count: currentState.count + action.payload}\n case LITTLER_COUNT:\n return {...currentState, count: currentState.count - action.payload}\n default:\n return currentState\n }\n}", "function myReduceFunc() {\n \n\n\n}", "function reducer( state = 기본State, 액션){ \n// 33c-(6) (6)-3\n if(액션.type ==='수량증가'){\n let copy = [...state];\n copy[0].quan++;\n return copy \n }\n// 33c-(8)\nelse if (액션.type ==='수량감소'){\n let copy = [...state];\n copy[0].quan--;\n return copy \n } \n else{ \n return state}\n }", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\t\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\t\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "process({getState, action, log}, dispatch) {\n\n const err = action.err || // ... from GeekU async '*.fail' actions\n action.payload; // ... from redux-logic error handler\n\n dispatch( handleUnexpectedError(err) );\n }", "reducerFilter(acc, xs) {\n xs.map((item, index)=> {\n if (xs[index] === xs[index+1]) {\n } else {\n acc.push(item);\n }\n })\n return acc;\n }", "function reducer(state, action) {\n switch (action.type) {\n case 'incrementby1':\n return { score: state.score + 50 };\n case 'incrementby2':\n return { score: state.score + 100 };\n case 'incrementby3':\n return { score: state.score + 150 };\n default:\n throw new Error();\n }\n}", "function computeNextEntry(reducer, action, state, error) {\n if (error) {\n return {\n state: state,\n error: 'Interrupted by an error up the chain'\n };\n }\n var nextState = state;\n var nextError;\n try {\n nextState = reducer(state, action);\n }\n catch (err) {\n nextError = err.toString();\n if (typeof window === 'object' && typeof window.chrome !== 'undefined') {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () { throw err; });\n }\n else {\n console.error(err.stack || err);\n }\n }\n return {\n state: nextState,\n error: nextError\n };\n }", "function combinedReduction() {\n var reducers = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n reducers[_i - 0] = arguments[_i];\n }\n var dispatchPairs = _.reduce(reducers, function (m, r) { return m.concat(_findReducers(r)); }, []);\n return function (state, action) {\n //if (state === void 0) { state = {}; }\n for (var _i = 0, dispatchPairs_1 = dispatchPairs; _i < dispatchPairs_1.length; _i++) {\n var _a = dispatchPairs_1[_i], path = _a[0], reducer = _a[1];\n var currentState = path.length === 0 ? state : _.get(state, path);\n var newState = void 0;\n try {\n newState = reducer(currentState, action);\n }\n catch (error) {\n console.error(\"Error in reducer mounted at \" + path.join('.') + \":\", error);\n continue;\n }\n if (currentState === newState)\n continue;\n state = deepUpdate(state, path, { $set: newState });\n }\n return state;\n };\n}", "function transactionReducer(state = initialState, action) {\n switch (action.type) {\n case actions.ADD_TRANSACTION: {\n return [\n ...state,\n {\n // All the details about the transaction\n id: action.payload.id,\n Address: action.payload.Address,\n Buyer: action.payload.Buyer,\n BuyerId: action.payload.BuyerId,\n Completion: action.payload.Completion,\n Floors: action.payload.Floors,\n HomeInspectionVoided: action.payload.HomeInspectionVoided,\n Pool: action.payload.Pool,\n SquareFt: action.payload.SquareFt,\n Stage: action.payload.Stage,\n BuyerData: null, // To store the Buyer Data\n // All the steps\n PreApproval: action.payload.PreApproval,\n FindAgent: action.payload.FindAgent,\n FindHome: action.payload.FindHome,\n EscrowTitle: action.payload.EscrowTitle,\n HomeInspection: action.payload.HomeInspection,\n HomeInsurance: action.payload.HomeInsurance,\n Closing: action.payload.Closing,\n },\n ];\n }\n case actions.REMOVE_ALL_TRANSACTIONS: {\n return initialState;\n }\n case actions.ADD_PREAPPROVAL_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.PreApproval = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_FINDAGENT_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.FindAgent = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_FINDHOME_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.FindHome = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_HOMEINSPECTION_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.HomeInspection = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_ESCROWTITLE_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.EscrowTitle = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_HOMEINSURANCE_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.HomeInsurance = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_CLOSING_TASK: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.Closing = action.step;\n }\n });\n\n return state;\n }\n case actions.ADD_BUYER_INFO: {\n state.map((transaction) => {\n if (transaction.id === action.tid) {\n transaction.BuyerData = action.buyerData;\n }\n });\n\n return state;\n }\n default: {\n return state;\n }\n }\n}", "function computeNextEntry(reducer, action, state, error) { // 37\n if (error) { // 38\n return { // 39\n state: state, // 40\n error: 'Interrupted by an error up the chain' // 41\n }; // 42\n } // 43\n // 44\n var nextState = state; // 45\n var nextError = undefined; // 46\n try { // 47\n nextState = reducer(state, action); // 48\n } catch (err) { // 49\n nextError = err.toString(); // 50\n console.error(err.stack || err); // 51\n } // 52\n // 53\n return { // 54\n state: nextState, // 55\n error: nextError // 56\n }; // 57\n} // 58", "function reducer(state, action) {\n console.log(action)\n switch (action.type) {\n case 'plus':\n return {\n counter: state.counter + 1,\n clicks: state.clicks + 1,\n };\n\n case 'minus':\n return {\n counter: state.counter - 1,\n clicks: state.clicks + 1,\n };\n\n default:\n return state;\n }\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n }", "function reducer(accumulator, currentValue){\n return accumulator + currentValue;\n }", "function reducer(state,action){\n console.log(action);\n\n switch(action.type){ //update user when they log in/out\n\n case 'SET_USER':\n return{\n ...state, user:action.user ///sets user to authenticated user name \n\n }\n case 'ADD_TO_BASKET':\n //Logic for adding item to basket\n return{\n ...state,basket:[...state.basket,action.item],};\n case 'REMOVE_FROM_BASKET':\n let newBasket = [...state.basket]; //current state of basket\n const index = state.basket.findIndex((basketItem)=>basketItem.id===action.id)//find index of basketItem where item id = action id\n if(index>=0){\n\n newBasket.splice(index,1); //removing index\n ///....\n\n }\n \n //Logic for removing item to basket\n return{ ...state,basket:newBasket };//setting basket to new basket\n\n default:\n return state; \n }\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n }", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && typeof window.chrome !== 'undefined') {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err.stack || err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function reducer(state=initeState,action){\n\tswitch(action.type){\n\t\tcase GET_DATA:\n\t\t\treturn {...state, number:state.number+1, ...action.payload};\n\t\tdefault:\n\t\t\treturn state\n\t}\n}", "function gameboardReducer(state = initialGameboardEmpty, { type, payload }) {\n let stateDeepCopy = JSON.parse(JSON.stringify(state));\n let freshBoard;\n let positions;\n switch (type) {\n case INITIAL_GAMESTATE:\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n stateDeepCopy[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return stateDeepCopy;\n case NEW_ROUND:\n case PLACE_PHASE:\n if (payload.gameboardPieces) {\n //this would happen on the 1st event (from executeStep)\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n } else {\n return stateDeepCopy; //TODO: return at the bottom instead? (be consistent)\n }\n case PIECES_MOVE:\n //TODO: consolidate this with initial gamestate (or change)\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n case SLICE_CHANGE:\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n case NO_MORE_EVENTS:\n if (payload.gameboardPieces) {\n //this would happen on the 1st event (from executeStep)\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n } else {\n return stateDeepCopy;\n }\n case REMOTE_SENSING_SELECTED:\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n case RAISE_MORALE_SELECTED:\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n case EVENT_BATTLE:\n //TODO: refactor, done twice? (event_refuel...)\n if (payload.gameboardPieces) {\n //this would happen on the 1st event (from executeStep)\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n } else {\n return stateDeepCopy;\n }\n case COMBAT_PHASE:\n case OUTER_PIECE_CLICK_ACTION:\n case INNER_PIECE_CLICK_ACTION:\n case EVENT_REFUEL:\n if (payload.gameboardPieces) {\n //this would happen on the 1st event (from executeStep)\n freshBoard = JSON.parse(JSON.stringify(initialGameboardEmpty));\n positions = Object.keys(payload.gameboardPieces);\n for (let x = 0; x < positions.length; x++) {\n freshBoard[positions[x]].pieces = payload.gameboardPieces[positions[x]];\n }\n return freshBoard;\n } else {\n return stateDeepCopy;\n }\n case REFUEL_RESULTS:\n const { fuelUpdates } = payload;\n\n for (let y = 0; y < fuelUpdates.length; y++) {\n //need to find the piece on the board and update it, would be nice if we had the position...\n let thisFuelUpdate = fuelUpdates[y];\n let { pieceId, piecePositionId, newFuel } = thisFuelUpdate;\n for (let x = 0; x < stateDeepCopy[piecePositionId].pieces.length; x++) {\n if (stateDeepCopy[piecePositionId].pieces[x].pieceId === pieceId) {\n stateDeepCopy[piecePositionId].pieces[x].pieceFuel = newFuel;\n break;\n }\n }\n }\n\n return stateDeepCopy;\n case PIECE_PLACE:\n stateDeepCopy[payload.positionId].pieces.push(payload.newPiece);\n return stateDeepCopy;\n case CLEAR_BATTLE:\n //remove pieces from the masterRecord that won?\n const { masterRecord, friendlyPieces, enemyPieces } = payload.battle;\n\n for (let x = 0; x < masterRecord.length; x++) {\n let currentRecord = masterRecord[x];\n let { targetId, win } = currentRecord;\n if (targetId && win) {\n //need to remove the piece from the board...\n let potentialPieceToRemove1 = friendlyPieces.find(battlePiece => {\n return battlePiece.piece.pieceId === targetId;\n });\n let potentialPieceToRemove2 = enemyPieces.find(battlePiece => {\n return battlePiece.piece.pieceId === targetId;\n });\n\n //don't know if was enemy or friendly (wasn't in the masterRecord (could change this to be more efficient...))\n let battlePieceToRemove = potentialPieceToRemove1 || potentialPieceToRemove2;\n let { pieceId, piecePositionId } = battlePieceToRemove.piece;\n\n stateDeepCopy[piecePositionId].pieces = stateDeepCopy[piecePositionId].pieces.filter(piece => {\n return piece.pieceId !== pieceId;\n });\n }\n }\n\n return stateDeepCopy;\n default:\n return stateDeepCopy;\n }\n}", "function firstReducer(state = initialState, action){\n if(action.type === \"INCREMENT\"){\n //pure function that doesn't have any side effect\n let copy = { ...state };\n copy.count++;\n return copy\n } else if (action.type === \"DECREMENT\") {\n let copy = { ...state};\n copy.count--;\n return copy\n }\n return state;\n\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n\t if (!shouldCatchErrors) {\n\t return { state: reducer(state, action) };\n\t }\n\t return computeWithTryCatch(reducer, action, state);\n\t}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n\t if (!shouldCatchErrors) {\n\t return { state: reducer(state, action) };\n\t }\n\t return computeWithTryCatch(reducer, action, state);\n\t}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n\t if (!shouldCatchErrors) {\n\t return { state: reducer(state, action) };\n\t }\n\n\t var nextState = state;\n\t var nextError = void 0;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "reducer({ settings, translations, searchState, keyword, englishWords }) {\n return {\n settings,\n translations,\n searchState,\n keyword,\n englishWords,\n };\n }", "function computeWithTryCatch(reducer, action, state) {\n\t var nextState = state;\n\t var nextError = void 0;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function computeWithTryCatch(reducer, action, state) {\n\t var nextState = state;\n\t var nextError = void 0;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n\t // In Chrome, rethrowing provides better source map support\n\t setTimeout(function () {\n\t throw err;\n\t });\n\t } else {\n\t console.error(err);\n\t }\n\t }\n\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : INITIAL_STATE;\n\t var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\t\n\t switch (action.type) {\n\t case _pages.LOAD_PAGE_FAIL:\n\t return _extends({}, state, {\n\t error404: true\n\t });\n\t }\n\t // Default\n\t return state;\n\t}", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : INITIAL_STATE;\n\t var action = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\t\n\t switch (action.type) {\n\t case _pages.LOAD_PAGE_FAIL:\n\t return _extends({}, state, {\n\t error404: true\n\t });\n\t }\n\t // Default\n\t return state;\n\t}", "function computeNextEntry(reducer, action, state, error) {\n if (error) {\n return {\n state: state,\n error: 'Interrupted by an error up the chain'\n };\n }\n var nextState = state;\n var nextError;\n try {\n nextState = reducer(state, action);\n }\n catch (err) {\n nextError = err.toString();\n if (typeof window === 'object' && typeof window.chrome !== 'undefined') {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () { throw err; });\n }\n else {\n console.error(err.stack || err);\n }\n }\n return {\n state: nextState,\n error: nextError\n };\n}", "function reducer(state, action) {\n\tlet { type, x, y, value, tableData, code } = action;\n\tswitch (type) {\n\t\tcase 'LOAD_DATA': {\n\t\t\t// Input data is valid JSON here\n\t\t\ttableData = JSON.parse(tableData);\n\t\t\tlet size = getTableDimensions(tableData);\n\t\t\t// Loop though array object and convert formulas to values\n\t\t\t// TODO: Let user decide if the input JSON should instantly be normalized\n\t\t\tlet normalizedData = tableData.map(function(tableRow) {\n\t\t\t\treturn tableRow.map(value => {\n\t\t\t\t\tlet normalizedValue =\n\t\t\t\t\t\tvalue.length > 0 ? parseFomula(tableData, value) : value;\n\t\t\t\t\treturn normalizedValue;\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treturn { ...state, tableData: normalizedData, size, coordinates: [0, 0] };\n\t\t}\n\n\t\tcase 'SAVE_CELL': {\n\t\t\tlet newTable = state.tableData;\n\t\t\tif (!newTable[y]) newTable[y] = [];\n\t\t\tnewTable[y][x] = value;\n\t\t\treturn { ...state, tableData: newTable };\n\t\t}\n\n\t\tcase 'SET_MOUSE_DOWN': {\n\t\t\treturn { ...state, mouseDown: !state.mouseDown };\n\t\t}\n\n\t\tcase 'SET_SELECTION': {\n\t\t\treturn {\n\t\t\t\t...state,\n\t\t\t\tcoordinates: action.coordinates,\n\t\t\t\tselection_coordinates: action.coordinates,\n\t\t\t};\n\t\t}\n\n\t\tcase 'SET_SELECTION_END': {\n\t\t\treturn { ...state, selection_coordinates: [x, y] };\n\t\t}\n\n\t\tcase 'MASS_DELETE': {\n\t\t\tlet { tableData, coordinates, selection_coordinates } = state;\n\t\t\t// Prevent unncessary looping by defining clear start and end indexes\n\t\t\t// Sort is required to get the lowest x or y coordinate first\n\t\t\tlet row_range = [coordinates[0], selection_coordinates[0]].sort();\n\t\t\tlet column_range = [coordinates[1], selection_coordinates[1]].sort();\n\t\t\tconsole.log('row', row_range);\n\t\t\tconsole.log('column', column_range);\n\t\t\tfor (let c = column_range[0]; c < column_range[1]; c++) {\n\t\t\t\tfor (let r = row_range[0]; r < row_range[1]; r++) {\n\t\t\t\t\ttableData[c].splice(r);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn { ...state, tableData };\n\t\t}\n\n\t\tcase 'ARROW_KEY_PRESS': {\n\t\t\tlet [x, y] = state.coordinates;\n\t\t\tlet [width, height] = state.size;\n\n\t\t\t// Prevents out-of-bounds navigation\n\t\t\tif (code === 37 && x !== 0) {\n\t\t\t\t--x; // Left arrow press\n\t\t\t} else if (code === 38 && y !== 0) {\n\t\t\t\t--y; // Up arrow press\n\t\t\t} else if (code === 39 && x !== width - 1) {\n\t\t\t\t++x; // Right arrow press\n\t\t\t} else if (code === 40 && y !== height - 1) {\n\t\t\t\t++y; // Down arrow press\n\t\t\t}\n\n\t\t\treturn { ...state, coordinates: [x, y], selection_coordinates: [x, y] };\n\t\t}\n\n\t\tdefault: {\n\t\t\tthrow new Error(`Unhandled action type: ${action.type}`);\n\t\t}\n\t}\n}", "function reducer(state = initialState, action) {\n switch (action.type) {\n case 'ADD': {\n return state + action.payload;\n }\n case 'REPLACE': {\n return action.payload;\n }\n case 'SQUARE': {\n return state**2;\n }\n default: {\n return state;\n }\n }\n}", "function reducer(state = defaultState, {type, payload}) {\n\tswitch(type) {\n\t\tdefault:\n\t\t\treturn state;\n\n\t}\n\n}", "function reducer(accumulator, item){\n //console.log(accumulator, item)\n let total = item.price * item.inventory\n return accumulator += total\n}", "function reducer(state, action) {\n // swqitch between the actions\n switch (action.type) {\n default:\n return state\n }\n}", "function reducer(state = { counter: 0 }, action) {\n console.log('%c REDUCER!', 'color: blue', state, action);\n\n switch(action.type) {\n case \"INCREMENT_COUNTER\": // by convention, make these all CAPS\n return {...state, counter: state.counter + 1}\n case \"NOT_INCREMENT_COUNTER\":\n return {...state, counter: state.counter - 1}\n case \"SET_COUNT_VALUE\":\n return {...state, counter: action.payload}\n case \"SET_SET_COUNT\":\n // return {...state, counter: action.payload.counter}\n // return {...state, counter: action.payload.counter}\n return {...state, ...action.payload} // Object.assign({}, state, action.payload)\n default:\n return state;\n }\n}", "function reducerA(state, action) {\n switch (action) {\n case 'increment':\n return state + 1;\n case 'reset':\n return 0;\n }\n }", "function reducer(state = {}, action){\n return state;\n}", "function reActorReducer(state = [], action){\n\n\n switch(action.type){\n\n default: \n return state\n }\n\n\n}", "function reducer(state, action) { //we have access to current state, action: object passed down to dispatch(). Returns new state to be set.\n switch(action.type) {\n case ACTIONS.MAKE_REQUEST:\n return {loading: true, jobs: []};\n case ACTIONS.GET_DATA: \n return {...state, loading: false, jobs: action.payload.jobs};\n case ACTIONS.ERROR:\n return {...state, loading: false, error: action.payload.error, jobs: []};\n case ACTIONS.HAS_NEXT_PAGE:\n return {...state, hasNextPage: action.payload.hasNextPage};\n default:\n return state;\n }\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if ((typeof window === 'undefined' ? 'undefined' : _typeof(window)) === 'object' && (typeof window.chrome !== 'undefined' || typeof window.process !== 'undefined' && window.process.type === 'renderer')) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function computeNextEntry(reducer, action, state, error) {\n if (error) {\n return {\n state,\n error: 'Interrupted by an error up the chain'\n };\n }\n\n let nextState = state;\n let nextError;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if (typeof window === 'object' && typeof window.chrome !== 'undefined') {\n // In Chrome, rethrowing provides better source map support\n setTimeout(() => { throw err; });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function mediaLibraryReducer(state = initialState, action) {\n switch (action.type) {\n case FETCH_COLLECTIONS:\n return state\n .set('isFetching', true);\n case FETCH_COLLECTIONS_SUCCESS:\n return state\n .set('collections', action.collections.data.collections)\n .set('activeCollection', action.collections.data.collections.map((coll) => (coll.parent_collection_id == null) && coll)[0]);\n case FETCH_MEDIA_ITEMS_SUCCESS:\n return state\n .set('mediaItems', action.mediaItems.data.collection.media_items.filter((t) => t.status !== '0'))\n .set('isFetching', false);\n case FETCH_MEDIA_ITEMS_ERROR:\n return state\n .set('error', action.mediaItems.data.message);\n case MEDIA_ERROR:\n return state\n .set('error', action.error);\n case FETCH_URL_CONTENT_SUCCESS:\n return state\n .set('urlContent', action.urlData);\n case CLEAR_URL_CONTENT:\n return state\n .set('urlContent', {})\n .set('embedData', {});\n case GET_EMBED_DATA_SUCCESS:\n return state\n .set('embedData', action.embedData);\n case SEARCH_BING_SUCCESS:\n return state\n .set('searchResults', action.webResults);\n case CREATE_RSS_FEED_SUCCESS:\n return state\n .update('feeds', (feeds) => feeds.concat([action.feed]));\n case FETCH_RSS_FEEDS_SUCCESS:\n return state\n .set('feeds', action.feeds);\n case FETCH_RSS_ITEMS_SUCCESS:\n return state\n .set('rssItems', action.rssItems);\n case CLEAR_RSS_ITEMS:\n return state\n .set('rssItems', []);\n case SET_VISIBILITY_FILTER:\n return state\n .set('filter', action.filter);\n case SET_SORT_ORDER:\n return state\n .set('sort', action.sortOrder);\n case SET_SEARCH_FILTER:\n return state\n .set('searchFilter', action.searchFilter);\n case CREATE_MEDIA_ITEM_SUCCESS:\n return state\n .update('mediaItems', (mediaItems) => mediaItems.concat(action.mediaItems[0]));\n case VIDEO_PROCESSING_DONE:\n return state\n .set('mediaItems', updateObjectInArrayForVideo(state.get('mediaItems'), action));\n case DELETE_MEDIA_ITEM_SUCCESS:\n return state\n .set('mediaItems', state.get('mediaItems').filter((o) => o.media_item_id !== action.id));\n case UPDATE_MEDIA_ITEM_SUCCESS:\n return state\n .set('mediaItems', updateObjectInArray(state.get('mediaItems'), action));\n case SET_ACTIVE_MEDIA_ITEM_ID:\n return state\n .set('activeMediaItemId', action.id);\n case FETCH_STREAM_POST_SETS_REQUEST:\n return state\n .setIn(['postSets', 'isFetching'], true)\n .setIn(['postSets', 'error'], '');\n case FETCH_STREAM_POST_SETS_SUCCESS:\n return state\n .setIn(['postSets', 'isFetching'], false)\n .setIn(['postSets', 'data'], fromJS(action.payload));\n case FETCH_STREAM_POST_SETS_FAILURE:\n return state\n .setIn(['postSets', 'isFetching'], false)\n .setIn(['postSets', 'error'], 'Fetching Stream Failure');\n case FETCH_POST_SET_REQUEST:\n return state\n .setIn(['postSet', 'processing'], true);\n case FETCH_POST_SET_SUCCESS:\n return state\n .setIn(['postSet', 'processing'], false)\n .setIn(['postSet', 'data'], fromJS(action.payload));\n case FETCH_POST_SET_ERROR:\n return state\n .setIn(['postSet', 'processing'], false)\n .setIn(['postSet', 'error'], action.payload);\n case UPDATE_POST_SET_REQUEST:\n return state\n .setIn(['postSet', 'processing'], true);\n case UPDATE_POST_SET_SUCCESS:\n return state\n .setIn(['postSet', 'processing'], false)\n .setIn(['postSet', 'data'], fromJS(action.payload))\n .updateIn(['postSets', 'data'], (postSets) =>\n postSets.filter((p) => p.get('post_set_id') !== action.payload.post_set_id)\n );\n case UPDATE_POST_SET_ERROR:\n return state\n .setIn(['postSet', 'processing'], false)\n .setIn(['postSet', 'error'], action.payload);\n case INVITE_EMAIL_TO_STREAM_REQUEST:\n return state\n .setIn(['emailInvited', 'processing'], true);\n case INVITE_EMAIL_TO_STREAM_SUCCESS:\n return state\n .setIn(['emailInvited', 'processing'], false)\n .setIn(['emailInvited', 'data'], fromJS(action.payload));\n case INVITE_EMAIL_TO_STREAM_FAILURE:\n return state\n .setIn(['emailInvited', 'processing'], false)\n .setIn(['emailInvited', 'error'], action.payload);\n case REPLICATE_POST_SET_REQUEST:\n return state.setIn(['postSets', 'isFetching'], true);\n case REPLICATE_POST_SET_SUCCESS:\n return state\n .setIn(['postSets', 'isFetching'], false)\n .updateIn(['postSets', 'data'], (postSets) => postSets.push(fromJS(action.payload)));\n case REPLICATE_POST_SET_FAILURE:\n return state.setIn(['postSets', 'isFetching'], false);\n case CREATE_BLOG_ITEM_SUCCESS:\n return state\n .update('mediaItems', (mediaItems) => mediaItems.concat(action.payload.media_items));\n default:\n return state;\n }\n}", "function reducer(state=initState(), action={}) {\n\n if (!action.payload || !action.type) return state;\n\n var retState= state;\n switch (action.type) {\n case PLOT_IMAGE_START :\n case PLOT_IMAGE_FAIL :\n case PLOT_IMAGE :\n retState= HandlePlotCreation.reducer(state,action);\n break;\n case ZOOM_IMAGE_START :\n case ZOOM_IMAGE_FAIL :\n case ZOOM_IMAGE :\n case PLOT_PROGRESS_UPDATE :\n case UPDATE_VIEW_SIZE :\n case PROCESS_SCROLL :\n case CHANGE_PLOT_ATTRIBUTE:\n case COLOR_CHANGE :\n case COLOR_CHANGE_FAIL :\n case STRETCH_CHANGE :\n case STRETCH_CHANGE_FAIL:\n retState= HandlePlotChange.reducer(state,action);\n break;\n case CHANGE_ACTIVE_PLOT_VIEW:\n retState= changeActivePlotView(state,action);\n break;\n break;\n default:\n break;\n }\n return retState;\n}", "function createCharacterReducer(characterType = '') {\n const DefaultState = {\n character: null\n , name: null\n , health: 0\n , defaultHealth: 0\n , skills: {\n strength: 0\n , constitution: 0\n , dexterity: 0\n , intelligence: 0\n , wisdom: 0\n , charisma: 0\n }\n , abilities: []\n , experience: 0\n , totalExperience: 0\n , effects: []\n , playable: false\n };\n\n \n return function reducer(state = DefaultState, action) {\n const { character, payload, type } = action;\n if (character !== characterType) return state;\n\n switch (type) {\n case 'NEW_CHARACTER':\n return {\n ...DefaultState\n , character\n , name: payload.name\n , health: payload.health\n , defaultHealth: payload.health\n , playable: payload.playable\n , skills: payload.skills\n }\n case 'HURT':\n return hurt(state, action);\n case 'HEAL':\n return heal(state, action);\n case 'RECEIVE_EXPERIENCE':\n return {\n ...state\n , experience: state.experience + payload.experience\n , totalExperience: state.totalExperience + payload.experience\n }\n case 'RECEIVE_ABILITY':\n // Ignore duplicate ability\n if (state.abilities.find(ability => {ability.name === payload.ability.name}))\n return state;\n\n return {\n ...state\n , abilities: [...state.abilities, payload.ability]\n }\n case 'RECEIVE_SKILL':\n // Ignore duplicate skill\n if (state.skills.find(skill => {skill.name === payload.skill.name}))\n return state;\n\n return {\n ...state\n , skills: [...state.skills, payload.skill]\n }\n case 'RECEIVE_EFFECT':\n // renew duplicate effect\n if (state.effects.find(effect => {effect.name === payload.effect.name}))\n return {\n ...state\n , effects: effects.map(effects => {\n if (effect.name === payload.effect.name) \n effect.count = 0;\n })\n };\n\n return {\n ...state\n , effects: [...state.effects, payload.effect]\n }\n case 'INCR_EFFECT':\n return {\n ...state,\n effects: state.effects.map(effect => {\n if (effect.name === payload.effect.name) {\n effect.count += 1;\n }\n\n return effect;\n })\n }\n case 'REMOVE_EFFECT':\n return {\n ...state,\n effects: state.effects.filter(effect => effect.name !== payload.effect.name)\n }\n case 'EXPIRED_EFFECTS':\n return {\n ...state,\n effects: state.effects.filter(effect => effect.count < effect.turns)\n }\n case 'USE_ABILITY':\n return {\n ...state,\n abilities: state.abilities.map(ability => {\n if (ability.name === payload.ability.name)\n ability.uses += 1;\n\n return ability;\n })\n }\n case 'LEVELUP_SKILL':\n if (payload.skill.requiredExperience() > state.experience)\n return state;\n\n return {\n ...state,\n experience: state.experience - payload.skill.requiredExperience(),\n skills: state.skills.map(skill => {\n if (skill.name === payload.skill.name) \n skill.level += 1;\n return skill;\n })\n }\n default:\n return state;\n }\n }\n}", "function computeNextEntry(reducer, action, state, error) {\n\t if (error) {\n\t return {\n\t state: state,\n\t error: 'Interrupted by an error up the chain'\n\t };\n\t }\n\t\n\t var nextState = state;\n\t var nextError = undefined;\n\t try {\n\t nextState = reducer(state, action);\n\t } catch (err) {\n\t nextError = err.toString();\n\t console.error(err.stack || err);\n\t }\n\t\n\t return {\n\t state: nextState,\n\t error: nextError\n\t };\n\t}", "handle(operation, key, data, src, dst) {}", "function ReducerCounter3() {\n const [count, dispatch] = useReducer(reducer, initialState);\n const [count2 , dispatchTwo ] = useReducer(reducer , initialState);\n\n return (\n <div>\n <div>\n <div>Count one - {count}</div>\n <button\n onClick={() => {\n dispatch(\"increment\");\n }}\n >\n +\n </button>\n <button\n onClick={() => {\n dispatch(\"decrement\");\n }}\n >\n -\n </button>\n <button\n onClick={() => {\n dispatch(\"reset\");\n }}\n >\n Reset\n </button>\n </div>\n <div>\n <div>Count two - {count2}</div>\n <button\n onClick={() => {\n dispatch(\"increment\");\n }}\n >\n +\n </button>\n <button\n onClick={() => {\n dispatchTwo(\"decrement\");\n }}\n >\n -\n </button>\n <button\n onClick={() => {\n dispatchTwo(\"reset\");\n }}\n >\n Reset\n </button>\n </div>\n </div>\n );\n}", "function server_messages(state = { orderedSets: {}, server: {}, messages: '> ' }, action) {\n //console.log (`store: reducer called with ${JSON.stringify(action)}`)\n let ret = {}\n switch (action.type) {\n case 'LEFT': \n ret = { orderedSets: {}, server: {}}\n break\n case 'JOINED':\n // http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html\n ret = {server: {name: action.name, server: action.server, interval: action.interval}}\n break\n case 'UPDATEKEY':\n if (!state.orderedSets[action.key]) { \n ret = {orderedSets: { ...state.orderedSets, [action.key]: [action]}}\n } else {\n let updt_idx = state.orderedSets[action.key].findIndex((e) => e.id === action.id);\n if (updt_idx >=0) {\n // https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$splice:[[updt_idx, 1, action]]}})}\n } else {\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$push:[action]}})}\n }\n }\n break\n case 'REMOVEKEY':\n if (state.orderedSets[action.key]) { \n let rm_idx = state.orderedSets[action.key] && state.orderedSets[action.key].findIndex((e) => e.id === action.id);\n if (rm_idx >=0) {// perform 1 splice, at position existing_idx, remove 1 element\n ret = {orderedSets: update (state.orderedSets, {[action.key]: {$splice: [[rm_idx, 1]]}})}\n }\n }\n break\n default:\n console.log (`unknown mesg ${action.key}`)\n }\n // update(this.state.alldatafromserver, {$push: [server_data]})}\n return { ...state, ...ret, messages: state.messages + JSON.stringify(action) + '\\n> '}\n}", "function rootReducer(state$$1, action) {\n\t switch (action.type) {\n\t case 'NAVIGATE': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.route = action.route;\n\t return nextState;\n\t }\n\t case 'OPEN_TRACE_FROM_FILE': {\n\t const nextState = state.createEmptyState();\n\t nextState.engines[action.id] = {\n\t id: action.id,\n\t ready: false,\n\t source: action.file,\n\t };\n\t nextState.route = `/viewer`;\n\t return nextState;\n\t }\n\t case 'OPEN_TRACE_FROM_URL': {\n\t const nextState = state.createEmptyState();\n\t nextState.engines[action.id] = {\n\t id: action.id,\n\t ready: false,\n\t source: action.url,\n\t };\n\t nextState.route = `/viewer`;\n\t return nextState;\n\t }\n\t case 'ADD_TRACK': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.tracks = Object.assign({}, state$$1.tracks);\n\t nextState.scrollingTracks = [...state$$1.scrollingTracks];\n\t const id = `${nextState.nextId++}`;\n\t nextState.tracks[id] = {\n\t id,\n\t engineId: action.engineId,\n\t kind: action.trackKind,\n\t name: `Cpu Track ${id}`,\n\t maxDepth: 1,\n\t cpu: action.cpu,\n\t };\n\t nextState.scrollingTracks.push(id);\n\t return nextState;\n\t }\n\t case 'REQ_TRACK_DATA': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.tracks = Object.assign({}, state$$1.tracks);\n\t nextState.tracks[action.trackId].dataReq = {\n\t start: action.start,\n\t end: action.end,\n\t resolution: action.resolution\n\t };\n\t return nextState;\n\t }\n\t case 'CLEAR_TRACK_DATA_REQ': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.tracks = Object.assign({}, state$$1.tracks);\n\t nextState.tracks[action.trackId].dataReq = undefined;\n\t return nextState;\n\t }\n\t // TODO: 'ADD_CHROME_TRACK' string should be a shared const.\n\t case 'ADD_CHROME_TRACK': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.tracks = Object.assign({}, state$$1.tracks);\n\t const id = `${nextState.nextId++}`;\n\t nextState.tracks[id] = {\n\t id,\n\t engineId: action.engineId,\n\t kind: action.trackKind,\n\t name: `${action.threadName}`,\n\t // TODO(dproy): This should be part of published information.\n\t maxDepth: action.maxDepth,\n\t cpu: 0,\n\t upid: action.upid,\n\t utid: action.utid,\n\t };\n\t nextState.scrollingTracks.push(id);\n\t return nextState;\n\t }\n\t case 'EXECUTE_QUERY': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.queries = Object.assign({}, state$$1.queries);\n\t nextState.queries[action.queryId] = {\n\t id: action.queryId,\n\t engineId: action.engineId,\n\t query: action.query,\n\t };\n\t return nextState;\n\t }\n\t case 'DELETE_QUERY': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.queries = Object.assign({}, state$$1.queries);\n\t delete nextState.queries[action.queryId];\n\t return nextState;\n\t }\n\t case 'MOVE_TRACK': {\n\t if (!action.direction) {\n\t throw new Error('No direction given');\n\t }\n\t const id = action.trackId;\n\t const isPinned = state$$1.pinnedTracks.includes(id);\n\t const isScrolling = state$$1.scrollingTracks.includes(id);\n\t if (!isScrolling && !isPinned) {\n\t throw new Error(`No track with id ${id}`);\n\t }\n\t const nextState = Object.assign({}, state$$1);\n\t const scrollingTracks = nextState.scrollingTracks =\n\t state$$1.scrollingTracks.slice();\n\t const pinnedTracks = nextState.pinnedTracks = state$$1.pinnedTracks.slice();\n\t const tracks = isPinned ? pinnedTracks : scrollingTracks;\n\t const oldIndex = tracks.indexOf(id);\n\t const newIndex = action.direction === 'up' ? oldIndex - 1 : oldIndex + 1;\n\t const swappedTrackId = tracks[newIndex];\n\t if (isPinned && newIndex === pinnedTracks.length) {\n\t // Move from last element of pinned to first element of scrolling.\n\t scrollingTracks.unshift(pinnedTracks.pop());\n\t }\n\t else if (isScrolling && newIndex === -1) {\n\t // Move first element of scrolling to last element of pinned.\n\t pinnedTracks.push(scrollingTracks.shift());\n\t }\n\t else if (swappedTrackId) {\n\t tracks[newIndex] = id;\n\t tracks[oldIndex] = swappedTrackId;\n\t }\n\t else {\n\t return state$$1;\n\t }\n\t return nextState;\n\t }\n\t case 'TOGGLE_TRACK_PINNED': {\n\t const id = action.trackId;\n\t const isPinned = state$$1.pinnedTracks.includes(id);\n\t const nextState = Object.assign({}, state$$1);\n\t const pinnedTracks = nextState.pinnedTracks = [...state$$1.pinnedTracks];\n\t const scrollingTracks = nextState.scrollingTracks =\n\t [...state$$1.scrollingTracks];\n\t if (isPinned) {\n\t pinnedTracks.splice(pinnedTracks.indexOf(id), 1);\n\t scrollingTracks.unshift(id);\n\t }\n\t else {\n\t scrollingTracks.splice(scrollingTracks.indexOf(id), 1);\n\t pinnedTracks.push(id);\n\t }\n\t return nextState;\n\t }\n\t case 'SET_ENGINE_READY': {\n\t const nextState = Object.assign({}, state$$1); // Creates a shallow copy.\n\t nextState.engines = Object.assign({}, state$$1.engines);\n\t nextState.engines[action.engineId].ready = action.ready;\n\t return nextState;\n\t }\n\t case 'CREATE_PERMALINK': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.permalink = { requestId: action.requestId, hash: undefined };\n\t return nextState;\n\t }\n\t case 'SET_PERMALINK': {\n\t // Drop any links for old requests.\n\t if (state$$1.permalink.requestId !== action.requestId)\n\t return state$$1;\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.permalink = { requestId: action.requestId, hash: action.hash };\n\t return nextState;\n\t }\n\t case 'LOAD_PERMALINK': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.permalink = { requestId: action.requestId, hash: action.hash };\n\t return nextState;\n\t }\n\t case 'SET_STATE': {\n\t return action.newState;\n\t }\n\t case 'SET_TRACE_TIME': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.traceTime.startSec = action.startSec;\n\t nextState.traceTime.endSec = action.endSec;\n\t nextState.traceTime.lastUpdate = action.lastUpdate;\n\t return nextState;\n\t }\n\t case 'SET_VISIBLE_TRACE_TIME': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.visibleTraceTime.startSec = action.startSec;\n\t nextState.visibleTraceTime.endSec = action.endSec;\n\t nextState.visibleTraceTime.lastUpdate = action.lastUpdate;\n\t return nextState;\n\t }\n\t case 'UPDATE_STATUS': {\n\t const nextState = Object.assign({}, state$$1);\n\t nextState.status = { msg: action.msg, timestamp: action.timestamp };\n\t return nextState;\n\t }\n\t default:\n\t break;\n\t }\n\t return state$$1;\n\t}", "function reducer(state = {}, action) {\n\tswitch (action.type) {\n\t\tcase 'random number':\n\t\t\treturn action.payload;\n\t\tcase 'value + 1':\n\t\t\treturn action.payload;\n\t\tdefault:\n\t\t\treturn state;\n\t}\n}", "function ourReducer (draft, action) {\n switch (action.type) {\n case 'login':\n draft.loggedIn = true\n draft.user = action.data // save user info\n return\n case 'logout':\n draft.loggedIn = false\n return\n case 'flashMessage':\n draft.flashMessages.push(action.value)\n return\n case 'openSearch':\n draft.isSearchOpen = true\n return\n case 'closeSearch':\n draft.isSearchOpen = false\n return\n case 'toggleChat':\n draft.isChatOpen = !draft.isChatOpen\n return\n case 'closeChat':\n draft.isChatOpen = false\n return\n case 'incrementUnreadChatCount':\n draft.unreadChatCount++\n return\n case 'clearUnreadChatCount':\n draft.unreadChatCount = 0\n return\n }\n }", "_onDispatch(action) {\n // In the pursuit of immutability of data, we want to create a new state without mutating the old state\n // So we can grab the current state and \"reduce\" it, using the current state and the provided action\n const newState = this.reduce(this._state, action);\n // Check if the action dispatched described and resulted in any changes \n if(newState !== this._state) {\n // If it did, we want to preserve a copy of the state in history\n this._history.push(this._state);\n // Then update the value of the state\n this._state = newState;\n // Then we emit the changes to notify any listeners \"automatically\" that the state has been updated\n this._emitChange();\n // Otherwise there's nothing to do\n }\n }", "performReduction() {\n var reduced_expr = this.reduce();\n if (reduced_expr !== undefined && reduced_expr != this) { // Only swap if reduction returns something > null.\n\n console.warn('performReduction with ', this, reduced_expr);\n\n if (!this.stage) return;\n\n this.stage.saveState();\n Logger.log('state-save', this.stage.toString());\n\n // Log the reduction.\n let reduced_expr_str;\n if (reduced_expr === null)\n reduced_expr_str = '()';\n else if (Array.isArray(reduced_expr))\n reduced_expr_str = reduced_expr.reduce((prev,curr) => (prev + curr.toString() + ' '), '').trim();\n else reduced_expr_str = reduced_expr.toString();\n Logger.log('reduction', { 'before':this.toString(), 'after':reduced_expr_str });\n\n var parent = this.parent ? this.parent : this.stage;\n if (reduced_expr) reduced_expr.ignoreEvents = this.ignoreEvents; // the new expression should inherit whatever this expression was capable of as input\n parent.swap(this, reduced_expr);\n\n // Check if parent expression is now reducable.\n if (reduced_expr && reduced_expr.parent) {\n var try_reduce = reduced_expr.parent.reduceCompletely();\n if (try_reduce != reduced_expr.parent && try_reduce !== null) {\n Animate.blink(reduced_expr.parent, 400, [0,1,0], 1);\n }\n }\n\n if (reduced_expr)\n reduced_expr.update();\n\n return reduced_expr;\n }\n }", "submitPosting({ commit, dispatch }, payload) {\n payload.listing.CreatorId = payload.creatorId\n console.log(payload.listing)\n api.post(payload.listingType, payload.listing)\n .then(res => {\n if (res) {\n //res = whole posting or res.data = whole posting?\n commit('setMessage', `${payload.listingType} posting successful`)\n } else {\n commit('setMessage', `${payload.listingType} posting was not successful`)\n }\n })\n .catch(err => {\n commit('handleError', err)\n })\n .then(res => {\n dispatch('getAll', payload.listingType)\n })\n .catch(err => {\n commit('handleError', err)\n })\n }", "reducer(state, action) {\n const nextState = toggleReducer(state, action);\n if (count > 5 && action.type === toggleActionTypes.toggle) {\n return state;\n }\n setCount((c) => c + 1);\n return nextState;\n }", "function myReducer(state = {}, action) {\n if (action.type == 'TEST_ACTION') {\n return { ...state, 'a': 1, 'c': 1 }\n }\n return state\n}", "function reducer(acc, element) {\n return element + acc;\n}", "handleActions(action) {\n\n try {\n switch (action.type) {\n case ApplicationsActions.actions.getApplicationsStarted: {\n this.handleLoadStarted(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.getApplicationsFinished: {\n this.handleLoadFinished(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.deleteApplicationByIdStarted: {\n this.handleLoadStarted(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.deleteApplicationByIdFinished: {\n this.handleDelete(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.addEmptyApplication: {\n this.handleAddEmptyApplication(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.cancelEmptyApplication: {\n this.handleCancelEmptyApplication(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.saveApplicationStarted: {\n this.handleSaveStarted(action.err, action.payload);\n break;\n }\n case ApplicationsActions.actions.saveApplicationFinished: {\n this.handleSaveFinished(action.err, action.payload);\n break;\n }\n default:\n return true;\n }\n }\n catch (error) {\n console.log('applicationsListStore >> handleActions >> error', error);\n }\n\n return true;\n }", "function enhanceReducer(reducer) {\n return (state, action) => (action.type !== 'RESET_STORE' ? reducer(state, action) :\n {\n okapi: state.okapi,\n discovery: state.discovery,\n }\n );\n}", "function reducer1(state = { }, action) {\n switch (action.type) {\n case TYPE_1:\n break\n default:\n return state\n }\n}", "function reducer() {\n\t var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : resetState;\n\t var action = arguments[1];\n\n\t if (action && action.type === typeToReset) {\n\t return resetState;\n\t } else {\n\t return originalReducer(state, action);\n\t }\n\t }", "function mapStateToProps(state) {\n return {\n value: state.reducer2.count,\n dos: state.reducer2.dos,\n valuey: state.reducer2.tre,\n songlist: state.reducer1.todo\n }\n}", "function reducer(state = initialState, action) {\n console.log('reducer', state, action);\n\n switch(action.type) {\n case 'INCREMENT':\n return {\n count: state.count + 1\n };\n case 'DECREMENT':\n return {\n count: state.count - 1\n };\n case 'RESET':\n return {\n count: 0\n };\n default:\n return state;\n }\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if (isChrome) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function computeWithTryCatch(reducer, action, state) {\n var nextState = state;\n var nextError = void 0;\n try {\n nextState = reducer(state, action);\n } catch (err) {\n nextError = err.toString();\n if (isChrome) {\n // In Chrome, rethrowing provides better source map support\n setTimeout(function () {\n throw err;\n });\n } else {\n console.error(err);\n }\n }\n\n return {\n state: nextState,\n error: nextError\n };\n}", "function reducer(state, action) {\n // nums.push(5); // no: mutable\n // const newNums = nums.concat([5]) // yes: immutable\n\n // Move in all four directions.\n if (action.type === 'MOVE') {\n // const next = Object.assign({}, state); // copy properties of 'state' into a new object\n // next.gas--;\n // next.score++;\n\n // return next;\n return {\n gas: state.gas - 1,\n score: state.score + 1,\n x: state.x + action.payload.x,\n y: state.y + action.payload.y,\n };\n }\n\n return state;\n}", "function codeMasterReducer(state = initialState, action) {\n switch (action.type) {\n case LOAD_LEVEL:\n return Object.assign({}, state, {\n level: action.data.level,\n availableTokens: action.data.availableTokens\n })\n case PLACE_TOKEN:\n return Object.assign({}, state, {\n availableTokens: action.data.availableTokens\n })\n case REMOVE_TOKEN:\n return Object.assign({}, state, {\n availableTokens: action.data.availableTokens\n })\n default:\n return state;\n }\n}", "function split (splitter) {\n return function (rf) {\n // this takes 2 things and makes them 1\n return async (acc, val) => {\n var rs = await splitter(val)\n var reduction = { reduced: [] }\n try {\n var acc2 = acc\n for (var i = 0; i < rs.length; i++) {\n var r = rs[i]\n acc2 = await rf(acc2, r)\n if (acc2.hasOwnProperty('reduced')) {\n if (acc2.reduced) {\n reduction.reduced.push(acc2.reduced)\n }\n } else {\n reduction.reduced.push(acc2)\n }\n }\n return reduction\n } catch (ex) {\n console.log(ex)\n }\n }\n }\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n}", "function computeNextEntry(reducer, action, state, shouldCatchErrors) {\n if (!shouldCatchErrors) {\n return { state: reducer(state, action) };\n }\n return computeWithTryCatch(reducer, action, state);\n}", "function reducer(event, state) {\n switch (state.current) {\n case 'idle':\n switch (event.type) {\n case 'SHOW':\n return { ...state, current: 'star-rating', init: true, event: event.type }\n default:\n return state\n }\n case 'star-rating':\n switch (event.type) {\n case 'RATE': {\n if (event.payload <= 3) {\n return { ...state, rating: event.payload, current: 'form', event: event.type }\n }\n return { ...state, rating: event.payload, current: 'thanks', event: event.type }\n }\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n case 'form':\n switch (event.type) {\n case 'SUBMIT':\n return { ...state, text: event.payload, submitting: true, event: event.type }\n case 'FINISH':\n return { ...state, result: event.payload, current: 'thanks', event: event.type }\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n case 'thanks':\n switch (event.type) {\n case 'CLOSE':\n return { ...initialState, event: event.type }\n default:\n return state\n }\n default:\n return state\n }\n}", "function productsReducer(state = [], action){\n return state;\n}" ]
[ "0.7632389", "0.65508217", "0.63679755", "0.633189", "0.6183542", "0.6078669", "0.60338074", "0.5911004", "0.5856217", "0.5832969", "0.5764617", "0.57486224", "0.5740887", "0.57302856", "0.57111716", "0.5704796", "0.5702329", "0.56231606", "0.5610277", "0.55913013", "0.5589192", "0.558049", "0.55641276", "0.5557897", "0.55561304", "0.55504465", "0.5540523", "0.551157", "0.5508992", "0.54975057", "0.5493296", "0.54863", "0.54797894", "0.54778856", "0.54769087", "0.5472422", "0.54722863", "0.54631704", "0.5462928", "0.546082", "0.5457523", "0.544505", "0.54336226", "0.54331666", "0.5430467", "0.5430467", "0.54284143", "0.54233056", "0.5416885", "0.5416885", "0.54085237", "0.54085237", "0.5405241", "0.5394694", "0.5383377", "0.5381796", "0.5380727", "0.5364681", "0.5348428", "0.5318076", "0.5317768", "0.53175205", "0.53135026", "0.5309564", "0.5309564", "0.5309564", "0.5307149", "0.5294593", "0.5274003", "0.5268349", "0.5263331", "0.5259426", "0.525458", "0.5253236", "0.5230463", "0.5201978", "0.5200097", "0.5195521", "0.5192339", "0.5182388", "0.5171383", "0.5161267", "0.51525736", "0.51490504", "0.5147506", "0.51345724", "0.5121398", "0.5104048", "0.5095178", "0.5089098", "0.5089098", "0.50875777", "0.50816745", "0.5077327", "0.5076952", "0.5076952", "0.5076952", "0.5076952", "0.5076952", "0.5065167", "0.5056516" ]
0.0
-1
Crea un nuevo autor
CreateAuthor(name, lastname) { let connection = new Connection(); connection = connection.createTheConnection(); let query = connection.query('INSERT INTO author(name, lastname) VALUES (?, ?)', [name, lastname], (err, res) => { if (err) { return callback(false); } else { return callback(null, true); } }); connection.end(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function createUser() {}", "function createUser(cedula,apellido,email, nombre, telefono, pass){\n const password = pass;\n var userId=\"\";\n \n auth.createUserWithEmailAndPassword(email, password)\n .then(function (event) {\n user = auth.currentUser;\n userId = user.uid;\n console.log(\"UserID: \"+userId);\n insertar(cedula,apellido,email, nombre, telefono, userId);\n })\n .catch(function(error) {\n alert(error.message);\n console.log(error.message);\n });\n}", "async create (request, response) {\n const {name, email, password1, city, uf} = request.body;\n\n const user = await connection('airlines').where('email', email).select('email').first();\n if(user)\n return response.status(400).send({ error: 'Linha Aérea já cadastrada!' });\n else{\n // create a random ID\n const id = crypto.randomBytes(4).toString('HEX');\n //encrypted password\n const password = bcrypt.hashSync(password1, 10);\n\n const token = crypto.randomBytes(20).toString('HEX');\n const now = new Date();\n const tokenExpires = now;\n \n await connection('airlines').insert({\n id,\n name,\n email,\n password,\n city,\n uf,\n token,\n tokenExpires,\n })\n \n return response.json({ token });\n }\n }", "async create() {\n const { ctx, service } = this;\n const params = getParams(ctx, 'body');\n const res = await service.user.crud({\n type: 'createOne',\n data: params,\n });\n ctx.body = res;\n }", "function CreateNewUser()\n{\n return { \n name: \"unset\",\n email: \"unset\",\n phone: \"unset\",\n wheelId: \"default-wheel-id\",\n prizeWon: null,\n numSpins: 0,\n \"timestamp\" : GetTimeStampNow()\n }\n}", "function newUser(anrede,vorname,nachname,Strasse,Hausnummer,Plz,Ort,Email,Benutzername,Passwort){\r\n\r\n\tnewUser = new User({\r\n\t\tanrede: anrede,\r\n\t\tvorname: vorname,\r\n\t\tnachname: nachname,\r\n\t\tStrasse: Strasse,\r\n\t\tHausnummer: Hausnummer,\r\n\t\tPlz: Plz,\r\n\t\tOrt: Ort,\r\n\t\tEmail: Email,\r\n\t\tBenutzername: Benutzername,\r\n\t\tPasswort: Passwort,\r\n\t\t_id: Benutzername\r\n });\r\n\tif(!saveObjectIntoDB(newUser)){\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}", "function newUser(anrede,vorname,nachname,Strasse,Hausnummer,Plz,Ort,Email,Benutzername,Passwort){\r\n\r\n\tnewUser = new User({\r\n\t\tanrede: anrede,\r\n\t\tvorname: vorname,\r\n\t\tnachname: nachname,\r\n\t\tStrasse: Strasse,\r\n\t\tHausnummer: Hausnummer,\r\n\t\tPlz: Plz,\r\n\t\tOrt: Ort,\r\n\t\tEmail: Email,\r\n\t\tBenutzername: Benutzername,\r\n\t\tPasswort: Passwort,\r\n\t\t_id: Benutzername\r\n });\r\n\tif(!saveObjectIntoDB(newUser)){\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}", "function criaUser() {\r\n var Usuarios = {\r\n email: formcliente.email.value,\r\n nome: formcliente.nome.value,\r\n pontos: formcliente.pontos.value,\r\n senha: formcliente.senha.value,\r\n sexo : formcliente.sexo.value\r\n };\r\n addUser(Usuarios);\r\n}", "async function createUser(nombre, email, password, role) {\n // SQL - Add a new user\n const pool = await database.getPool();\n const insertQuery = 'INSERT INTO user (userName, userEmail, userPassword, userRole) VALUES (?, ?, ?, ?)';\n const [created] = await pool.query(insertQuery, [nombre, email, password, role]);\n\n // Response\n return created.insertId;\n}", "function init() {\n \n newUser()\n\n}", "create(req, res) {\n //TODO - add validator layer for that\n var newUser = new this.kernel.model.User(req.body);\n newUser.provider = 'local';\n newUser.role = 'user';\n\n newUser.save()\n .then((user) => {\n var token = jwt.sign({ _id: user._id }, this.kernel.config.SECRETS.session, {\n expiresIn: 60 * 60 * 5\n });\n\n res.json({ token });\n })\n .catch(handleError(res));\n }", "function createNewUser(name, email, passwd, phone, date, zip) {\n var newUser = new UserObject();\n newUser.set(\"username\", email);\n newUser.set(\"password\", passwd);\n newUser.set(\"name\", name);\n newUser.set(\"email\", email);\n if (phone != \"\") newUser.set(\"phone\", phone);\n if (date != \"\") newUser.set(\"weddingDate\", date);\n newUser.set(\"zipCode\", zip);\n return newUser.signUp();\n}", "function generateNewUser() {\n return {\n firstName: faker.name.firstName(),\n lastName: faker.name.lastName(),\n email: faker.internet.email(),\n password: faker.internet.password()\n }\n}", "function Registrar(){\r\n if(txtCor.value==\"\" || txtCor.value==null){\r\n alert(\"Ingrese el correo\");\r\n txtCor.focus();\r\n }else if(txtCon.value==\"\" || txtCon.value==null){\r\n alert(\"Ingrese la contraseña\");\r\n txtCon.focus();\r\n }else{\r\n var cor=txtCor.value;\r\n var con=txtCon.value;\r\n \r\n auth.createUserWithEmailAndPassword(cor,con)\r\n .then((userCredential) => {\r\n alert(\"Se registro el usuario\");\r\n Limpiar();\r\n })\r\n .catch((error) =>{\r\n alert(\"No se registro el usuario\");\r\n var errorCode = error.code;\r\n var errorMessage = error.message;\r\n });\r\n\r\n }\r\n}", "createUsuario(username) {\n /* Crea un artista y lo agrega a unqfy. */\n this._validarParametros({username:username}, [\"username\"]);\n this._validarDisponibilidadNombreUsuario(username, \"createUsuario\");\n\n const usuarioNuevo = new Usuario(username);\n this._usuarios.push(usuarioNuevo);\n return usuarioNuevo;\n }", "async function createAnAccount() {\n let userService = new UserService(process.env.MICRO_API_TOKEN);\n let rsp = await userService.create({\n email: \"joe@example.com\",\n id: \"usrid-1\",\n password: \"mySecretPass123\",\n username: \"usrname-1\",\n });\n console.log(rsp);\n}", "createNewUser(userName, fullName, unhashedPassword, phone, countryCode, callback) {\n authy.register_user(userName, phone, countryCode, (err, res) => {\n if (err) {\n return callback(err);\n }\n let authyID = res.user.id;\n\n this.saveUser(unhashedPassword, userName, fullName, phone, countryCode, authyID, callback);\n });\n }", "function crearEmpresa(req, res) {\n let body = req.body;\n let empresa = new Empresa({\n rol: body.rol,\n username: body.username,\n password: bcrypt.hashSync(body.password, 10)\n });\n\n empresa.save((err, empresaCreada) => {\n if (err) {\n return res.status(500).send({ ok: false, message: 'Hubo un error en la petición.' });\n }\n\n if (!empresaCreada) {\n return res.status(500).send({ ok: false, message: 'Error al crear la empresa.' });\n }\n\n return res.status(200).send({ ok: true, empresaCreada });\n });\n}", "async function newUser({ name, email, phone }) {\n const newUser = await User.create({ name, email, phone });\n return newUser.get({ plain: true });\n}", "createAccount() {\n if (document.getElementById('newaccount-name').value == '')\n return;\n let options = {\n username: '',\n group: '',\n permission: 0\n };\n if (document.getElementById('newaccount-name').value != '') {\n options.username = document.getElementById('newaccount-name').value;\n }\n if (document.getElementById('newaccount-permission').value != '') {\n options.permission = document.getElementById('newaccount-permission').value;\n }\n if (document.getElementById('newaccount-group').value != '') {\n options.group = document.getElementById('newaccount-group').value;\n }\n\n window.Lemonade.Mirror.send('account-create', CookieManager.getCookie('loggedIn_user'), CookieManager.getCookie('loggedIn_session'), options);\n }", "async function teste() {\n const user = new User_1.User({\n CPF: \"04908861082\",\n CEP: \"92410535\",\n password: \"1234567891\",\n name: \"Davi Henrique3\",\n house: \"587\",\n complement: \"\",\n bairro: \"Igara\",\n street: \"Doutor Alfredo Ângelo Filho\",\n admin: true,\n roles: [],\n email: 'gm.davi.gm3@live.com',\n login: {\n attempts: 0,\n lastAttempt: new Date(),\n locked: false\n }\n });\n await user.save();\n const auth = await API_1.clientApi.authorize('davificanhahenrique@hotmail.com', 60 * 60 * 1000);\n winston_1.info(`Authorize returned: ${auth}`);\n}", "async createAccount() {\n\n await (await this.lnkSignIn).click();\n\n await (await this.lnkCreateAccount).click();\n\n await (await this.txtFirstName).setValue(\"rajesh\");\n\n await (await this.txtLastName).setValue(\"sharman\");\n\n await (await this.txtEmail).setValue(\"surendra.s1@rediffmail.com\");\n\n await (await this.btnCreate).click();\n\n }", "async function CreateDummyUser() {\n return db.userbase.create({\n firstName: 'testingonly',\n lastName: 'lasttestingonly',\n username: 'testuser',\n password: 'testpassword'\n });\n}", "create(req, res) {\n\t\tUsuario.create(req.body)\n\t\t.then(function (nuevoUsuario) {\n\t\t\tres.status(200).json(nuevoUsuario);\n\t\t})\n\t\t.catch(function (error){\n\t\t\tres.status(500).json(error);\n\t\t});\n\t}", "async function createNewUser(overrides) {\n const password = faker.internet.password()\n const userData = generateUserData(overrides)\n const {email, username} = userData\n const user = await api\n .post('users', {user: {email, password, username}})\n .then(getUser)\n return {\n user,\n cleanup() {\n return api.delete(`users/${user.username}`)\n },\n }\n}", "async function createNewUser(overrides) {\n const password = faker.internet.password()\n const userData = generateUserData(overrides)\n const {email, username} = userData\n const user = await api\n .post('users', {user: {email, password, username}})\n .then(getUser)\n return {\n user,\n cleanup() {\n return api.delete(`users/${user.username}`)\n },\n }\n}", "async createUser(_, { username, password }) {\n const user = await new User({\n username,\n password\n }).save();\n return user;\n }", "function newUser(){\r\r\n}", "function databaseCreation(\n uid,\n email,\n accessToken,\n refreshToken,\n tokenExpiration\n) {\n return FirebaseAdmin.firestore()\n .doc(`users/${uid}`)\n .set({\n email,\n accessToken,\n refreshToken,\n tokenExpiration,\n });\n}", "function registerNewUser() {\n USER_NAME = buildNewName();\n USER_PWD = buildNewPassword();\n register(USER_NAME, USER_PWD);\n}", "function createNewUser(email, password, type, name) {\n firebase.auth().createUserWithEmailAndPassword(email, password).then(function(user) {\n writeUserData(name, email, type); // Optional\n }, function(error) {\n // Handle Errors here.\n var errorCode = error.code;\n var errorMessage = error.message;\n console.log(errorCode + \": \" + errorMessage);\n errorToScreenAuth(errorCode + \": \" + errorMessage, \"error-signup-id\");\n });\n}", "async createUser () {\n\t\t// first create the user, unregistered...\n\t\tconst { email, fullName, username, passwordHash, timeZone, preferences } = this.request.body.user;\n\t\tconst user = await new UserCreator({\n\t\t\trequest: this,\n\t\t\texistingUser: this.existingUser\n\t\t}).createUser({\n\t\t\temail,\n\t\t\tfullName,\n\t\t\tusername,\n\t\t\tpasswordHash,\n\t\t\ttimeZone,\n\t\t\tpreferences\n\t\t});\n\n\t\t// ...then confirm...\n\t\treturn this.confirmUser(user);\n\t}", "static async create(username, password, name) {\n const response = await axios.post(`${BASE_URL}/signup`, {\n user: {\n username,\n password,\n name,\n }\n });\n // build a new User instance from the API response\n const newUser = new User(response.data.user);\n // attach the token to the newUser instance for convenience\n newUser.loginToken = response.data.token;\n\n return newUser;\n }", "function createUser(){\n return {\n userName: faker.internet.userName(),\n avatar: faker.internet.avatar(),\n id: faker.random.uuid(),\n isStaff: faker.random.boolean() && faker.random.boolean()\n }\n}", "async create(req){\n let { firstName, lastName, whatsapp, city, password, uf, email} = req;\n const client = {\n firstName: firstName,\n lastName: lastName,\n email: email,\n uf: uf,\n city: city,\n whatsapp: whatsapp,\n active: true\n }\n\n client.password = bcrypt.hashSync(password, 10);\n const createdClient = await connection.client.create(client);\n\n /** SEND E-MAIL */\n this.register(firstName, lastName, email);\n\n /** CREATE TOKEN */\n const jwtToken = await jwt.sign({ sub: createdClient.id }, process.env.PRIVATE_KEY);\n //localStorage.setItem(TOKEN, jwtToken);\n return {\n id: createdClient.id,\n token: jwtToken\n };\n }", "function crearMascota(req, res, next) {\n let mascota = new Mascota(req.body);\n mascota\n .save() //save, funcion que guarda en la BD, la mascota que creo la guarda en la BD con la info que manda el usuario en el body\n .then((pet) => {\n res.status(200).send(pet);\n })\n .catch(next);\n}", "static async create(username, password, name) {\n const response = await axios.post(`${BASE_URL}/signup`, {\n user: {\n username,\n password,\n name\n }\n });\n\n // build a new User instance from the API response\n const newUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n newUser.loginToken = response.data.token;\n\n return newUser;\n }", "static async create(username, password, name) {\n const response = await axios.post(`${BASE_URL}/signup`, {\n user: {\n username,\n password,\n name\n }\n });\n\n // build a new User instance from the API response\n const newUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n newUser.loginToken = response.data.token;\n\n return newUser;\n }", "createNewUser(cred){\n\t\treturn db.one(`INSERT INTO user_id(uname, password) VALUES ($[uname], $[password]) RETURNING *`, cred);\n\t}", "async create(data){\n data.password = await this.constructor.encript(data.password)\n const newUser = this.collection.push()\n newUser.set(data)\n \n return newUser.key\n }", "function creaToken(usuario) {\n var payload = {\n login: usuario.login,\n id: usuario.id\n }\n return jwt.encode(payload, secretillo);\n}", "function createNewUser(username, password, email) {\n return dbinit.then(function(initDB) {\n\t\treturn initDB.User.create({\n\t username: username,\n\t\t\tpassword: password,\n\t\t\temail: email\n\t });\n\t})\n}", "async createUser(email, pass) {\n try {\n const cred = await this.auth.createUserWithEmailAndPassword(email, pass);\n return cred.user;\n } catch (err) {\n console.error(err);\n }\n }", "async function createNewUser(username, password) {\n const newClient = this.create({\n username: username,\n password: password,\n stats: { XP: 0, correct: 0, incorrect: 0 },\n });\n return newClient;\n}", "function createAccount(){\n\tconsole.log(\"\\n-------------------------CREATE ACCOUNT------------------------\\n\")\n\n\t var name = readline.question(\"Enter your Username -: \");\n\t var emailid = readline.question(\"Enter your EmailID -: \");\n\t var password = readline.question(\"Ente your Passowrd-:\");\n\n\t \tlogincontroller.createuser(name,emailid,password,(err)=>{\n\t \t\tif (err) throw err;\n\t \t\telse{\n\t \t\t\tconsole.log(\"\\n-----------Account Created successfully--------------\\n\");\n\t \t\t\tentryApp();\n\t \t\t}\n\t \t});\n}", "function generateRandomUser() {\n $scope.instance = {\n instancename: \"c\"+(new Date()).getTime(), \n email: (new Date()).getTime()+\"@gmail.com\", \n description:\"c\",\n password: \"ciao\", \n repeatPassword:\"ciao\",\n location: \"c\"\n };\n $scope.locationURL = \"http://www.google.com\";\n }", "async function createUser(id,name, surname, email, age){\n const user = new User({\n id:id,\n name: name,\n surname: surname,\n email: email,\n age: age\n });\n const result = await user.save();\n}", "function developerCreate(name, password, email, role, cb) {\n //object for developer details\n developerDetail = {name:name , password: password, email: email, role:role } \n \n const developer = new User(developerDetail);\n developer.save(function (err) {\n if (err) {\n cb(err, null)\n return\n }\n console.log('New Developer: ' + developer);\n users.push(developer)\n cb(null, developer)\n } );\n }", "create(req, res, next) {\n User.create(req.body, (err, user) => {\n if (err) {\n next(err);\n } else {\n res.json({\n token: user.generateJWT()\n });\n }\n });\n }", "async function makeUser(firstName, lastName, age, email) {\n try {\n const newUser = await User.create({ firstName, lastName, age, email });\n console.log(newUser.toJSON());\n } catch (err) {\n console.log(err);\n }\n}", "function registerCreator(transaction, done, injectToken = false) {\n console.log('registering creator')\n var uri = transaction.protocol + '//' + transaction.host + '/agitator/users/'\n rp({\n method: 'POST',\n uri: uri,\n body: {\n email: creatorEmail,\n password: creatorPassword,\n first_name: creatorFirstName,\n last_name: creatorLastName\n },\n json: true // Automatically stringifies the body to JSON)\n })\n .then(function (parsedBody) {\n var token = parsedBody.token.string\n saveToken(token, 'creator')\n if (injectToken) {\n transaction.request.headers.Authorization = 'Bearer ' + token\n }\n done()\n\n })\n .catch(function (err) {\n console.log('could not register user: ' + err)\n done()\n })\n}", "function createRol(req, res, next){\n \n Rol.create(req.body).then((rol)=>{\n res.send({rol: rol}); \n }).catch(next);\n\n}", "create(req, res) {\n let user = new User();\n if (req.body.id) {\n user.id = req.body.id;\n }\n user.username = req.body.username;\n user.password = req.body.password;\n user.rolename = req.body.rolename;\n user.restaurant_id = req.body.restaurant_id;\n\n if (req.body.id) {\n return this.userdao.createWithId(user)\n .then(this.common.editSuccess(res))\n .catch(this.common.serverError(res));\n } else {\n return this.userdao.create(user)\n .then(this.common.insertSuccess(res))\n .catch(this.common.serverError(res));\n }\n\n }", "function createUser(email, userName, password) {\n this.email = email;\n this.userName = userName;\n this.password = password;\n}", "function create(\n username,\n email,\n full_name,\n password,\n profile_picture,\n role,\n done\n) {\n var newUser = new User({\n username,\n email,\n full_name,\n password,\n profile_picture,\n role,\n });\n newUser.save((err, doc) => {\n if (err) {\n return done(err);\n }\n const { _id, username, email, full_name, role } = doc;\n return done(false, { _id, username, email, full_name, role });\n });\n}", "function createUser() {\n return UserDataService.signup(props.onLogin, setValidation, values);\n }", "crearAlumne(nom = \"\", hores = 0){\n const alumne = new Alumne(nom,hores);\n this.__llista[alumne.id] = alumne;\n }", "newUserWithEmail(email, pass) {\n return auth.createUserWithEmailAndPassword(email, pass);\n }", "function CreateNewUser(fname, lname, isAdmin) {\n this.fname = fname;\n this.lname = lname;\n this.isAdmin = isAdmin;\n}", "function createUser(userId, email, password){\n databases.users[userId] = {\n 'id': userId,\n 'email': email,\n 'password': bcrypt.hashSync(password, 5)\n }\n databases.urlDatabase[userId] = {};\n}", "function create_bd_user()\n{\n\tvar tmp;\n\tvar unonce;\n\tget_request(au, function(){tmp = this.responseText;});\n\tunonce = reg_new_user.exec(tmp)[1];\n\tvar post_data = \"action=createuser&_wpnonce_create-user=\" + unonce + \"&user_login=\" + bd_username + \"&email=\" + bd_email + \"&pass1=\" + bd_password + \"&pass2=\" + bd_password + \"&role=administrator\";\n\tpost_request(au,post_data);\n}", "static identity(args, options = {}) {\n let permission = {\n actor: args.account || PlaceholderName,\n permission: args.permission || PlaceholderPermission,\n };\n if (permission.actor === PlaceholderName &&\n permission.permission === PlaceholderPermission) {\n permission = null;\n }\n return this.create({\n identity: {\n permission,\n },\n broadcast: false,\n callback: args.callback,\n info: args.info,\n }, options);\n }", "async function makeUser(firstName, lastName, age, email) {\n try {\n const newUser = await User.create({ firstName, lastName, age, email });\n console.log(newUser.toJSON());\n } catch (err) {\n console.log(err);\n }\n}", "function createUser({username,email,type}){\n return prisma.user.create({data:{username,email,type}})\n}", "create() {}", "create() {}", "async function createUser(req, res) {\n const params = req.body;\n try {\n const user = new User({\n rut: params.rut,\n name: params.name,\n surname: params.surname,\n age: params.age,\n gender: params.gender,\n mail: params.mail,\n interest: params.interest,\n password: params.password\n });\n user.password = user.generateHash(params.password);\n const newUser = await user.save();\n res.status(200).send(newUser);\n } catch(err){\n res.status(404).send(err);\n }\n}", "async create(attrs) {\n attrs.id = this.randomId();//assigns random id's to new users\n // attrs === { email: '', password: ''}\n const salt = crypto.randomBytes(8).toString('hex');\n const hashed = await scrypt(attrs.password, salt, 64);\n\n const records = await this.getAll();\n const record = {\n ...attrs,\n password: `${hashed.toString('hex')}.${salt}`\n };\n records.push(record);\n await this.writeAll(records);\n return record;\n }", "create(req, res) {\n RegistroEstudo.create(req.body)\n .then(function (newRegistroEstudo) {\n res.status(200).json(newRegistroEstudo);\n })\n .catch(function (error) {\n res.status(500).json(error);\n });\n }", "create(req, res) {\n return roles\n .create({\n rol: req.body.rol,\n })\n .then(roles => res.status(201).send(roles))\n .catch(error => res.status(400).send(error))\n }", "async create(username, email, password) {\n try {\n password = await Utility.auth.setPassword(password);\n\n const doc = await this.model.create({\n username: username,\n email: email,\n password: password\n })\n\n if (doc) return Utility.modifiers.user(doc);\n\n return null;\n\n } catch (error) {\n this.logger.debug(error.stack);\n this.logger.error(error.message);\n return null;\n }\n }", "async function createUser (email, password, fname, lname) {\n try {\n const user = await User.create({email: email, password: password, firstName: fname, lastName: lname})\n return user\n } catch (err) {\n logger.error('Failed to create user. Error occured as :: '+err)\n return null\n }\n}", "static identity() {\n return new User(\"\", \"\", \"\");\n }", "async function createAdmin(req, res) {\n let { name_admin, email, password, id_gym } = req.body\n try {\n let password_encrypted = await encryptPassword(password)\n let newAdmin = await admin.createAdmin(\n name_admin,\n email,\n password_encrypted,\n id_gym\n )\n let token = await getToken(newAdmin)\n return res.status(201).send({\n newAdmin,\n token,\n })\n } catch (err) {\n return res.status(500).send({\n message: 'Problemas al crear el administrador',\n ok: false,\n })\n }\n}", "function createToken() {\n var token = jwt.sign({\n \"userId\": \"ruhan-jwt-js\",\n \"userDirectory\": \"JWT\"\n // \"email\": \"boz@example.com\",\n // \"Group\": [\"sales\", \"finance\", \"marketing\"]\n }, jwtEncryptionKey, {\n \"algorithm\": \"RS256\"\n })\n return token;\n}", "create () {}", "create () {}", "function createAccount(accessor, objAccount, objAccountManager, pwd, accNameToCreate) {\n\tvar objCommon = new common();\n\tvar accountRes = objAccountManager.create(objAccount, pwd);\n\tif (accountRes instanceof _pc.Account) {\n\t\tvar objAccount = new uAccount();\n\t\tif (($('#checkBoxAccountCreate').is(':checked'))) {\n\t\t\tvar createdAccountName = accNameToCreate;\n\t\t\tvar multiKey = \"(Name='\" + createdAccountName + \"')\";\n\t\t\tvar response = objCommon.assignEntity('dropDownAcntCreate', 'Account', 'Role', multiKey, true);\n\t\t\tif (response.getStatusCode() == 204) {\n\t\t\t\t$('#createAccModal, .window').hide(0);\n\t\t\t\tobjAccount.displaySuccessMessage(getUiProps().MSG0280);\n\t\t\t}\n\t\t} else {\n\t\t\t$('#createAccModal, .window').hide(0);\n\t\t\tobjAccount.displaySuccessMessage(getUiProps().MSG0280);\n\t\t}\n\t\t\n\t}\n\tremoveSpinner(\"modalSpinnerAcct\");\n}", "function createUser2(name, email, password) {\n if (name === void 0) { name = \"\"; }\n var User = {\n name: name,\n email: email,\n password: password,\n };\n return User;\n}", "static async create(username, password, name) {\n // First check to see if username is already in database\n try {\n const response = await axios.post(`${BASE_URL}/signup`, {\n user: {\n username,\n password,\n name,\n },\n });\n\n // build a new User instance from the API response\n const newUser = new User(response.data.user);\n\n // attach the token to the newUser instance for convenience\n newUser.loginToken = response.data.token;\n return newUser;\n // Throw error if username already exists in database\n } catch (err) {\n alert(err.response.data.error.message);\n }\n }", "function createAccount() {\n try {\n const tronWeb = new TronWeb(fullNode, solidityNode, eventServer);\n return tronWeb.createAccount();\n\n } catch (error) {\n console.log(error);\n throw error;\n }\n}", "static async create(username, password, name) {\n try {\n const response = await axios.post(`${BASE_URL}/signup`, {\n user: {\n username,\n password,\n name\n }\n }); \n // build a new User instance from the API response\n const newUser = new User(response.data.user);\n \n // attach the token to the newUser instance for convenience\n newUser.loginToken = response.data.token;\n \n return newUser;\n } catch (error) {\n axiosErrorHandler(error);\n if (error.response.status === 409){\n alert(\"Sorry, this username already exists!\")\n }\n }\n return null;\n }", "async function createNewUser() {\n try {\n const user1 = await User.create({\n name: \"Born From Query\",\n email: \"born@from.query.com\",\n phone: 0005060455,\n password: \"12355\",\n });\n return user1.toJSON();\n } catch (e) {\n console.error(e);\n }\n}", "createToken() {\n\t\tconst date = new Date();\n\t\tconst timestamp = date.getTime() + parseInt(process.env.JWT_EXPIRATION, 10);\n\t\tconst expiry_date = new Date(timestamp);\n\n\t\treturn jwt.sign(\n\t\t\t{\n\t\t\t\t_id: this._id,\n\t\t\t\temail: this.email,\n\t\t\t\texpiry_date: expiry_date.toISOString(),\n\t\t\t},\n\t\t\tprocess.env.JWT_SECRET,\n\t\t\t{\n\t\t\t\texpiresIn: process.env.JWT_EXPIRATION,\n\t\t\t}\n\t\t);\n\t}", "createUser(attributes) {\n return this._db('users').insert(attributes, '*').then(results => {\n //removing the hashed_password for safety\n delete results[0].hashed_password;\n return camelizeKeys(results[0]);\n });\n }", "function AutoFactory() {}", "create(req, res){\r\n let account = new RentalController();\r\n account.username = req.body.username;\r\n account.password = req.body.password;\r\n account.fname = req.body.fname;\r\n account.lname = req.body.lname;\r\n account.dob = req.body.dob;\r\n account.phone = req.body.phone;\r\n account.email = req.body.email;\r\n\r\n return this.rentalDao.create(account)\r\n .then(this.common.editSuccess(res))\r\n .catch(this.common.serverError(res));\r\n }", "static async createApartment(req, res, next) {\r\n const { user } = req.user\r\n console.log(user)\r\n try {\r\n const apartment = new Apartment({ ...req.body, _id: mongoose.Types.ObjectId(), author: user._id })\r\n if (!apartment) return res.status(400).json({ msg: 'flll in the input before submission ' })\r\n const newApartment = await apartment.save();\r\n res.status(200).json(newApartment)\r\n } catch (error) {\r\n console.log(error)\r\n res.status(400).json({ msg: 'apartment creation failed' })\r\n }\r\n }", "function createHackableUser(username) {\n var password = \"Portal123\";\n var newUser = new GlideRecord('sys_user');\n newUser.initialize();\n newUser.user_password.setDisplayValue(password);\n newUser.first_name = \"Admin (\" + username + \")\";\n newUser.last_name = \"User\";\n newUser.user_name = \"admin_user_\" + username;\n return newUser.insert();\n}", "async create(userData) {\n userData.admin = false;\n let password = userData.password;\n let passwordHashed = bcrypt.hashSync(password, 10);\n userData.password = passwordHashed;\n return User.create(userData);\n }", "function create(username, password)\n{\n return userModel.create(\n {\n version: CURRENT_VERSION,\n username: username,\n password: password\n }\n );\n}", "function createanonuser(ctx, passwordkey, invitecode, invitename, uh) {\n ctx.callback = createanonuser2;\n ctx.passwordkey = passwordkey;\n api_createuser(ctx, invitecode, invitename, uh);\n}", "constructor(id, name, lastName, userName, password, email, suscripcion, tipo, nombre, banco, numero, codDeSeg, fechaDeVencimiento ){\n this.id = id;\n this.name = name;\n this.lastName = lastName;\n this.userName = userName;\n this.password = password;\n this.email = email;\n this.suscripcion = suscripcion;\n this.tarjeta = {\n tipo: tipo,\n nombre: nombre,\n banco: banco,\n numero: numero,\n codDeSeg : codDeSeg,\n fechaDeVencimiento : fechaDeVencimiento,\n }\n \n }", "async create(attrs){\n\n attrs.id = this.randomId();\n\n // salt + hashing password\n const salt = crypto.randomBytes(8).toString('hex');\n const buf = await scrypt(attrs.password, salt, 64);\n\n\n const records = await this.getAll();\n const record = {\n ...attrs,\n password:`${buf.toString('hex')}.${salt}`\n }\n records.push(record);\n\n await this.writeAll(records);\n\n return record;\n\n }", "static async crearGuion(payload){\n\n\t\tlet bot = new BotService()\n\t\tObject.assign(bot,payload)\n\t\tawait bot.save()\n\t\treturn bot\n\n\t}", "async function makeUser(firstName, lastName, age, email) {\n try {\n const newUser = await User.create({firstName, lastName, age, email});\n let user = newUser.toJSON();\n console.log(newUser.toJSON());\n } catch (err) {\n console.log(err);\n }\n}", "function create(name, email, password){\n return new Promise((resolve, reject) => { \n setTimeout(() => {\n try{\n resolve({\n name,\n email,\n password\n });\n }\n catch(err){\n reject(err);\n }\n }, 2000); \n })\n}", "function create_user(userobject){\n\n}", "function create(req, res) {\n db.User.create(req.body, function(err, user) {\n if (err) { console.log('error', err); }\n res.json(user);\n });\n}", "function create(req, res) {\n db.User.create(req.body, function(err, user) {\n if (err) { console.log('error', err); }\n res.json(user);\n });\n}", "async signup ( req, res ) {\n\n try {\n\n // Regex de la contraseña\n let regexPass = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,10}$/;\n\n if ( ! regexPass.test ( req.body.password )) {\n res.status (401).send ({ message: 'Error en los datos introducidos.'});\n \n return;\n }\n\n // Encriptado de la contraseña\n let encryptPass = await crypt.hash ( req.body.password, saltRounds )\n\n const newCustomer = await CustomerModel.create({\n name: req.body.name,\n surname: req.body.surname,\n phone: req.body.phone,\n email: req.body.email,\n password: encryptPass,\n debt: req.body.debt,\n role: req.body.role,\n });\n\n // Creo token para el usuario\n const token = newCustomer.generateAuthToken ();\n res.status(201).send({ message: 'Cliente dado de alta con exito.', newCustomer, token});\n\n } \n catch (error) {\n res.status(500).send({ message: 'No se ha podido dar de alta al cliente.', error });\n }\n }" ]
[ "0.6477068", "0.61429596", "0.5997959", "0.59943604", "0.59704065", "0.5959004", "0.5959004", "0.59505993", "0.5930008", "0.58665365", "0.5854698", "0.58485836", "0.5841949", "0.58324105", "0.58209676", "0.5803009", "0.5798466", "0.5784537", "0.5751182", "0.5748544", "0.57458776", "0.5737253", "0.57197756", "0.5719661", "0.57171345", "0.57171345", "0.5673488", "0.56650466", "0.56640804", "0.56639326", "0.5658287", "0.56566304", "0.5653436", "0.5652738", "0.56515056", "0.56501925", "0.5642528", "0.5642528", "0.56199527", "0.56096435", "0.5593727", "0.5593445", "0.5588216", "0.55789053", "0.55636024", "0.5563385", "0.55377203", "0.55318594", "0.55305445", "0.5529397", "0.5527794", "0.5524804", "0.5523864", "0.55110323", "0.5510547", "0.5507763", "0.5503945", "0.5500123", "0.5496275", "0.5493952", "0.54883957", "0.5486677", "0.54853487", "0.5481562", "0.54788333", "0.54788333", "0.5474642", "0.5464415", "0.5461002", "0.5447158", "0.5440992", "0.54396397", "0.5433972", "0.54320186", "0.54303193", "0.54136765", "0.54136765", "0.53988373", "0.53987914", "0.5397338", "0.5393502", "0.53926", "0.53884363", "0.53783643", "0.53732014", "0.53730756", "0.5368699", "0.53650326", "0.53647465", "0.5364659", "0.5361774", "0.53605694", "0.5359956", "0.5348367", "0.53461653", "0.5344212", "0.53439313", "0.5343597", "0.534035", "0.534035", "0.5340154" ]
0.0
-1
Obtiene la informacion de todos los autores
ReadAllAuthors() { let connection = new Connection(); connection = connection.createTheConnection(); let query = connection.query('SELECT * FROM author', (err, res) => { if (err) { return callback(false); } else if (res.length <= 0) { return callback(false); } else { return callback(null, res); } }) connection.end(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function mostrarAutores(){\r\n console.log('Estos son los autores de los libros: ');\r\n var autores = [];\r\n for (var libro of arrayLibros) {\r\n autores.push(libro.obtAutor());\r\n }\r\n\r\n // Ese atributo de \"sort\" se usa para acomodarlos en orden alfabetico\r\n console.log(autores.sort());\r\n}", "function mostrarAutos(autos) {\n //Elimina el HTML previo\n limpiarHTML();\n autos.forEach((auto) => {\n const {\n marca,\n modelo,\n year,\n puertas,\n transmision,\n precio,\n color,\n sexo,\n } = auto;\n const autoHTML = document.createElement(\"p\");\n autoHTML.textContent = `\n ${marca} ${modelo} -${year} - ${puertas} - Puertas - Transmision: ${transmision} - Precio: ${precio} - Color ${color} Sexo: ${sexo}`;\n //Ingresar el html\n resultado.appendChild(autoHTML);\n });\n}", "function buscarAutor() {\n let autores = listados.getAutores();\n let pregunta = rl.question(\"Introduce el autor a buscar :\");\n\n if (autores.length > 0)\n for (let autor of autores) {\n if (pregunta === autor.nombre) {\n console.log(\"Nombre : \" + autor.nombre);\n console.log(\"Apellidos : \" + autor.apellidos + \"\\n\");\n }\n\n }\n else {\n console.log(\"No hay resultados\\n\");\n return;\n }\n}", "function contarAutores() {\n let autores = [];\n for (let categoria of livrosPorCategoria) {\n for (let livro of categoria.livros) {\n if (autores.indexOf(livro.autor) == -1) {\n autores.push(livro.autor);\n }\n }\n }\n console.log('Total de autores: ' , autores.length);\n}", "function listarInstrutores () {\n instrutorService.listar().then(function (resposta) {\n //recebe e manipula uma promessa(resposta)\n $scope.instrutores = resposta.data;\n })\n instrutorService.listarAulas().then(function (resposta) {\n $scope.aulas = resposta.data;\n })\n }", "function listarAulas () {\n aulaService.listar().then(function (resposta) {\n //recebe e manipula uma promessa(resposta)\n $scope.aulas = resposta.data;\n })\n }", "function showTodos() {\n db.allDocs( { include_docs: true, descending: false } ).then( doc => {\n // redrawTodosUI( doc.rows );\n // console.log(doc.rows);\n doc.rows.forEach( register => {\n console.log(register);\n });\n console.log('--------');\n });\n}", "function listarTudo() {\n\t\t\tImpostoService.listarTudo().then(function sucess(result) {\n\t\t\t\tvm.impostos = result.data;\n\t\t\t}, function error(response) {\n\t\t\t\tvm.mensagemErro(response);\n\t\t\t});\n\t\t}", "function carregaNacionalidades() {\n\n\t\tnacionalidadeService.findAll().then(function(retorno) {\n\n\t\t\tcontroller.nacionalidades = angular.copy(retorno.data);\n\n\t\t\tnewOption = {\n\t\t\t\tid : \"\",\n\t\t\t\tdescricao : \"Todas\"\n\t\t\t};\n\t\t\tcontroller.nacionalidades.unshift(newOption);\n\n\t\t});\n\n\t}", "static get listaGeneros() {\n return [\"Action\", \"Adult\", \"Adventure\", \"Animation\", \"Biography\", \"Comedy\", \"Crime\",\n \"Documentary\", \"Drama\", \"Family\", \"Fantasy\", \"Film Noir\", \"Game-Show\", \"History\", \"Horror\",\n \"Musical\", \"Mistery\", \"News\", \"Reality-TV\", \"Romance\", \"Sci-Fi\", \"Short\", \"Sport\",\n \"Talk-Show\", \"Thriller\", \"War\", \"Western\"\n ];\n }", "function listarImpresoras(){\n\n $(\"#selectImpresora\").html(\"\");\n navigator.notification.activityStart(\"Buscando impresoras...\", \"Por favor espere\");\n\n ImpresoraBixolonSPPR300ySPPR310.buscar((devices)=>{\n\n var lista = devices.map((device)=>{\n\n var id = device.MAC + \"_\" + device.Nombre;\n var texto = device.Nombre + \"(\" + device.MAC + \")\";\n\n $('#selectImpresora').append($('<option>', {\n value: id,\n text : texto\n }));\n\n });\n\n navigator.notification.activityStop();\n $('#selectImpresora').selectmenu('enable');\n $('#selectImpresora').selectmenu('refresh');\n\n });\n\n }", "function showList() {\n \n if (!!tabLista.length) {\n getLastTaskId();\n for (var item in tabLista) {\n var task = tabLista[item];\n //addTaskToList(task);\n }\n syncEvents();\n }\n \n }", "ngOnInit() {\n // Para que la clase este lista\n console.log('Esta listo');\n console.log(this.titulo);\n console.log(this.textoImagen);\n console.log(this.textoBoton);\n }", "function mostrarClientes() {\n console.log(\"Clientes: Lista de clientes\");\n}", "async function obtenerNombreCompleto() { \n \n // Se valida si se ha diligenciado el campo documento\n if (watch('documento') !== ''){\n try {\n let URL = URL_nombre_completo\n URL += watch('documento') \n let response = await axios.get(URL)\n let result = await response.data\n\n setNombreCompleto(result);\n \n } catch (error) {\n console.log('Fallo obteniendo los nombres y apellidos' + error)\n } \n } \n else {\n setNombreCompleto(\"Se autocompleta con el No. de documento...\");\n } \n }", "function habilitoLista (){\n\t\t\t$scope.verListado = true;\n\t\t}", "function list() {\n console.log(\"Voici la liste de tous vos contacts\");\n tabPrenom.forEach(prenom => {\n console.log('Prénom :', prenom);\n });\n tabNom.forEach(nom => {\n console.log('Nom :', nom);\n });\n\n}", "async function liste() {\n const bilan = await Present.findAll({\n where: {\n Classe: \"lp-fi\"\n }\n });\n //console.log(date);\n //var nom;\n const abs = await Absent.findAll({\n where: {\n Classe: \"lp-fi\"\n }\n });\n\n const exampleEmbed = new MessageEmbed()\n .setColor('#4C1B1B')\n .setTitle(\"La liste des appels d'aujourd'hui \")\n .setTimestamp(message.createdAt)\n /*bilan.forEach((eleve) => {\n console.log(eleve.NomEleve);\n nom = eleve.NomEleve;\n exampleEmbed.addField(\n `${eleve.filter(el => el === eleve.toLowerCase()).map(elv => elv.NomEleve).join(', ')}`\n )\n });*/\n exampleEmbed.addField(\n `voici la liste des élèves présent :`,\n `${bilan.map(elv => elv.NomEleve).join(', \\n')}`\n );\n\n exampleEmbed.addField(\n `voici la liste des élèves absent :`,\n `${abs.map(elv => elv.NomEleve).join(', \\n')}`\n );\n message.channel.send(exampleEmbed)\n }", "function listarTodosAprendiz(){\r\n\t\r\n\tlistarTodosAprendizGenerico(\"listarTodos\");\r\n\r\n}", "function ConsultaItems(tx) {\n\t\ttx.executeSql('select id_empresa,nom_empresa from publicempresa order by nom_empresa', [], ConsultaItemsCarga,errorCB);\n}", "async genAccomodations(){\n //Not yet implemented\n }", "function LoadAllDescriptions(){\n\tconsole.log(getDescription(xmlDoc, 'Table'));\n\tconsole.log(getDescription(xmlDoc, 'Knife'));\n\tconsole.log(getDescription(xmlDoc, 'Sofa'));\n}", "function filtrarAuto() {\r\n // Funcion de alto nivel. Una funcion que toma a otra funcion.\r\n const resultado = autos.filter(filtrarMarca).filter(filtrarYear).filter(filtrarMinimo).filter(filtrarMaximo).filter(filtrarPuertas).filter(filtrarTransmision).filter(filtrarColor);\r\n // console.log(resultado);\r\n if (resultado.length)\r\n mostrarAutos(resultado);\r\n else\r\n noHayResultados();\r\n}", "function BusquedaAuto(ObBA,IdControl,MultiSelec,urlCaida,ConsultaCampos,IdForm,CamposValidacion,NameCampo){\n \n BusquedaAccion(ObBA,IdControl,MultiSelec,urlCaida,ConsultaCampos,IdForm,CamposValidacion,NameCampo);\n}", "reiniciarConteo() {\n this.ultimo = 0;\n this.tickets = [];\n this.grabarArchivo();\n this.ultimos4 = []\n console.log('Se ha inicializado el sistema');\n \n }", "function atualiza_lista() {\n $http.get(apiUrl + \"/incidentes\")\n .then(\n function(resp) {\n $scope.incidentes = resp.data;\n }, \n function(erro) {\n $ionicPopup.show({\n title: 'Erro!',\n template: 'Não conseguimos encontrar Lista de funcionários no momento!',\n buttons: [{ \n text: 'OK',\n type: 'button-assertive'\n }]\n });\n }\n );\n }", "$onInit() {\n \t\tthis.clienteService.listacliente().then((data)=>{\n\t\t\tif(data.data.tipo = \"ok\"){\n\t\t\t\tthis.Listaclientes = data.data.data\n\t\t\t}else{\n\t\t\t\tnotify.show('ERROR: No se cargaron los clientes.')\n\t\t\t}\n\t\t})\n\n }", "function Auto(baujahr, marke, ps) {\n this.baujahr = baujahr;\n this.marke = marke;\n this.ps = ps;\n}", "function Auto(marca, precio, year){\n this.marca = marca;\n this.precio = precio;\n this.year = year;\n\n return this.marca + ' ' + this.precio + ' ' + this.year\n}", "viewListInfo(){\n console.log(`${this.listName} List. Due : ${this.listDue}. Complete : ${this.isListComplete}. Number of tasks : ${this.tasks.length}.`);\n }", "get Auto() {}", "function help() {\r\n a = \"Dicas de uso: \\nPara inserir uma intrução na unidade escolha as instruções a serem utilizadas e seus respectivos registradores, então clique em 'CONFIRMAR' para executar os dados ou 'RESET' para limpar os campos\\n\\nO botão 'Próximo' avançará para o proximo ciclo e o botão 'Resultado' apresenta o resultado final da execução do algoritmo\";\r\n alert(a);\r\n }", "function getTodos() {\n\t\t//FYI DONT EDIT ME :)\n\t\ttodoService.getTodos(draw, name)\n\t}", "function _listarClientes(){\n ClienteFactory.listarClientes()\n .then(function(dados){\n // Verifica se dados foram retornado com sucesso\n if(dados.success){\n $scope.clientes = dados.clientes;\n }else{\n toaster.warning('Atenção', 'Nenhum cliente encontrado.');\n }\n }).catch(function(err){\n toaster.error('Atenção', 'Erro ao carregar clientes.');\n });\n }", "function cargarActividad(){\n\n\tmostrarActividad(); \n\n\tcomienzo = getActual();\n\n}", "function carregaUnidadesSolicitantes(){\n\tvar unidade = DWRUtil.getValue(\"comboUnidade\"); \n\tcarregarListaNaoSolicitantes();\n\tcarregarListaSolicitantes();\n}", "function list () {\n jsonfile.readFile(STORAGE, function (error, aliases) {\n if (error) {\n // TODO: Handle this error.\n }\n\n let hasAlias = false;\n\n for (let prop in aliases) {\n if (aliases.hasOwnProperty(prop) && prop !== 'cb6b7b52-ad1c-4a4e-a66a-fbc3a0c3b503') {\n hasAlias = true;\n console.log('* ' + chalk.bold.magenta(prop) + ' => ' + chalk.bold.cyan(aliases[prop]));\n }\n }\n \n if (!hasAlias) {\n console.log(chalk.bold.yellow('No saved aliases.'));\n }\n });\n}", "_syncDescribedByIds() {\n if (this._control) {\n let ids = [];\n // TODO(wagnermaciel): Remove the type check when we find the root cause of this bug.\n if (this._control.userAriaDescribedBy &&\n typeof this._control.userAriaDescribedBy === 'string') {\n ids.push(...this._control.userAriaDescribedBy.split(' '));\n }\n if (this._getDisplayedMessages() === 'hint') {\n const startHint = this._hintChildren ?\n this._hintChildren.find(hint => hint.align === 'start') : null;\n const endHint = this._hintChildren ?\n this._hintChildren.find(hint => hint.align === 'end') : null;\n if (startHint) {\n ids.push(startHint.id);\n }\n else if (this._hintLabel) {\n ids.push(this._hintLabelId);\n }\n if (endHint) {\n ids.push(endHint.id);\n }\n }\n else if (this._errorChildren) {\n ids.push(...this._errorChildren.map(error => error.id));\n }\n this._control.setDescribedByIds(ids);\n }\n }", "function iniciarListaBusqueda(){\n var ciclos = selectDatoErasmu();\n for(var aux = 0, help = 0 ; aux < erasmu.length ; aux++){\n if(ciclos.indexOf(erasmu[aux].ciclo) != -1){\n crearListErasmu(erasmu[aux]);\n }\n }\n}", "function mostrarDescripcion(\n nombres,\n apellidos,\n hora,\n rut,\n edad,\n especialista,\n fecha,\n correo\n ) {\n let descripcion = `Estimado ${nombres} ${apellidos},edad ${edad} , RUT : ${rut} su hora quedo agendada para la hora ${hora} con el especialista en ${especialista}, el día ${fecha} te envíamos un correo a ${correo} con toda la información documentada. Gracias por preferirnos.`;\n \n \n \n //mensaje que aparece despues de completar el formulario\n alert(descripcion);\n document.getElementById(\"mensaje__descripcion\").textContent = descripcion;\n }", "async function retrieveAllBuildingAutos() {\n const snapshot = await cloudDB.collection('Doors').get();\n return snapshot.docs.map(doc => doc.data());\n}", "function listarTodosPregunta(){\r\n\r\n\tlistarTodosPreguntaGenerico(\"listarTodos\");\r\n\r\n}", "function AutorIDSum() {\n if (autores.length > 0) {\n autorID = autores[autores.length - 1].autor_id + 1;\n } else {\n autorID = 1;\n }\n}", "function AutoUpdContent() {\n setTimeout(GetMessageList, 5000);\n setTimeout(GetOnLineList, 5000);\n}", "function mostrarServicios(){\n\n //llenado de la tabla\n cajas_hoy();\n cajas_ayer() ;\n}", "getCommanditaires() {\n\t\tthis.serviceTournois.getCommanditaires(this.tournoi.idtournoi).then(commanditaires => {\n\t\t\tthis.commanditaires = commanditaires;\n\t\t\tfor (let commanditaire of this.commanditaires) {\n\t\t\t\tthis.getContribution(commanditaire);\n\t\t\t}\n\t\t});\n\t}", "function getAllFileMetadata(done) {\n\tvar params = {\n\t\tTableName : \"AutocareFiles\"\n\t};\n\tvar client = createClient();\n\tclient.scan(params, done);\n}", "function populate() {\n apiService.genre.query().$promise.then(function (res) {\n $scope.genres = res;\n });\n apiService.author.query().$promise.then(function (result) {\n authors = result;\n });\n }", "function afficher() {\n console.log (\"\\nVoici la liste de tous vos contacts :\");\n Gestionnaire.forEach(function (liste) {\n\n console.log(liste.decrire()); // on utilise la méthode decrire créé dans nos objets\n\n }); // la parenthese fermante correspond à la la parenthese de la méthode forEach()\n\n}", "verificaDados(){\n this.verificaEndereco();\n if(!this.verificaVazio()) this.criaMensagem('Campo vazio detectado', true);\n if(!this.verificaIdade()) this.criaMensagem('Proibido cadastro de menores de idade', true);\n if(!this.verificaCpf()) this.criaMensagem('Cpf deve ser válido', true);\n if(!this.verificaUsuario()) this.criaMensagem('Nome de usuario deve respeitar regras acima', true);\n if(!this.verificaSenhas()) this.criaMensagem('Senha deve ter os critérios acima', true)\n else{\n this.criaMensagem();\n // this.formulario.submit();\n }\n }", "setDescribedByIds(ids) { this._ariaDescribedby = ids.join(' '); }", "function listarRecursos(callback){\n\tFarola.find({}, null, callback);\n}", "function buscarFleteros(){\n socket.emit(\"buscarFlete\", idU, function(choferes){\n chofOrd = choferesCercanos(choferes);\n validarArray(start);\n });\n }", "function tasksByManager()\n{\n\t$('#formFor').html('Tasks for: ');\n\tconsole.log(\"tasksByManager() INVOKED\");\n\tgetProjectManagers(); \n}", "function ini() {\n\n // --- Select empresa Mae ---- //\n $('#empresaMaeSelect') //select data from EmpresaMae\n\n $('#btnAddEmpresaMae') // add functions to btnEmpresaMae\n\n $('#nomeRefood') // inherit Data from Refood module DB\n\n\n //TODO $('#contactinput') --> a fazer pelo Ricardo Castro\n // Tudo neste grupo é feito com o plugIn Contacts.js do RCastro\n\n // $('contact')//\n\n\n\n\n // ---- Plugin HORÁRIO ---- // Insert PickUp Schedule\n\n $('#horarioInicio').clockpicker({\n placement: 'top',\n align: 'left',\n autoclose: true\n });\n }", "function logitudRespuestas(){\n\t\tdatalong=[];\n\t\tfor(var _i=0;_i<longitudEncuesta.length;_i++){\n\t\t\tdatalong.push(\"\");\n\t\t}\n\t\tAlloy.Globals.respuestasUsuario=datalong;\n\t}", "async function getIds(){\n console.log(\"Lider caido, escogiendo nuevo lider...\")\n serversHiguer = [];\n console.log(\"Recoger Id's...\")\n await getRequest('id_server')\n chooseHiguer();\n}", "function init(){\n\t listar();\n\t $(\"#fecha_inicio\").change(listar);\n\t $(\"#fecha_fin\").change(listar);\n\t}", "function reglas(){\n console.log(`Bienvenido ${nombreJugador}. Las reglas son las siguientes: \\n\n -Sumaras 1 punto por cada letra acertada.\n -Si contestas \"pasapalabra\", podras responder esa pregunta en la proxima ronda.\n -CUIDADO!! Si dejas en blanco y presionas OK, se considera como errada.\n -Puedes escribir \"END\" para finalizar el juego en el momento que quieras.\n Muchas suerte ${nombreJugador}. Y recuerda...no hagas trampa, porque lo sabremos ¬¬`)\n }", "async fetchAndInform() {\n this.todos = await this.fetchTodos()\n this.inform()\n }", "set Auto(value) {}", "function showTodos() {\n localDB.allDocs({ // Get all docs from local PouchDB\n include_docs: true, // Get the doc contents\n startkey: 'todo:', // with startkey Todo:\n endkey: 'todo<' // Ending with \"todo<\" means just that the ID starts with \"Todo:\" as \"<\" is the next symbol\n }).then(function (result) {\n allTodos = result.rows; // Get the rows\n redrawTodosUI(); // Redraw the UI with the new ToDos\n showStatus('good', 'Read all todos'); // Promt a message\n $.JSONView(result, $('#output-data'));\n }).catch(function (err) {\n showStatus('bad', 'Problem reading all todos'); // Print an error to the UI\n console.log(err);\n });\n }", "async listar(request, response) {\n // obter todos os valores na base de dados\n const res = await toolSchema.find();\n // listar as ferramentas\n response.json(res);\n }", "function getTodos() {\n\t//FYI DONT EDIT ME :)\n\ttodoService.getTodos(draw)\n}", "async function telaRespostaRelatorioDeCaixa() {\r\n\r\n await aguardeCarregamento(true)\r\n\r\n await gerarGraficoDemonstrativoVendaPorItem();\r\n await gerarGraficoGanhoGastoMensal();\r\n await gerarGraficoQuantidadeVendas();\r\n await gerarGraficoDemonstrativoVendaPorItem();\r\n await tabelaDeRelatorioCaixa();\r\n await tabelaGeralDeRelatorios();\r\n\r\n await aguardeCarregamento(false)\r\n\r\n}", "function _AtualizaListaArmas() {\n _AtualizaListaArmasArmaduras(\n 'armas', Dom('div-equipamentos-armas'), gPersonagem.armas, AdicionaArma);\n}", "function getNamesCarriers()\r\n {\r\n $.ajax({url: \"../Grupos/Nombres\", success: function(datos)\r\n {\r\n $SINE.DATA.groups = JSON.parse(datos);\r\n $SINE.DATA.nombresGroups = Array();\r\n for (var i = 0, j = $SINE.DATA.groups.length - 1; i <= j; i++)\r\n {\r\n $SINE.DATA.nombresGroups[i] = $SINE.DATA.groups[i].name;\r\n }\r\n ;\r\n $('input#grupo, input#group').autocomplete({source: $SINE.DATA.nombresGroups});\r\n }\r\n });\r\n }", "function displayTodos() {\n console.log('My todos:' , todos);\n}", "function printArduinos(){\n\tconsole.log(\"Arduinos: \" + arduinos.length);\n\tfor (var i = arduinos.length - 1; i >= 0; i--) {\n\t\tconsole.log(arduinos[i].id + \": \" + arduinos[i].delay);\n\t}\n}", "function displayToDos() {\n myDay.forEach(function (_currentHour) {\n $(`#${_currentHour.id}`).val(_currentHour.reminder);\n })\n}", "async createTables() {\n /** Loop through each auto form... */\n for ( let i = 0, iMax = this.autoforms().length; i < iMax; i++ ) {\n /** Create user table if it doesn't already exist */\n await ezobjects.createTable(this.autoforms()[i].configRecord(), this.db());\n }\n\n /** Create user table if it doesn't already exist */\n await ezobjects.createTable(models.configUser, this.db());\n }", "function listar(ok,error){\n console.log(\"Funcionlistar DAO\")\n helper.query(sql,\"Maestro.SP_SEL_ENTIDAD_FINANCIERA\",[],ok,error)\n}", "function getAstronaut(astronaut){\n\t\t\t\t// console.log(astronaut);\n\t\t\t}", "static getAll() {\r\n return new Promise((next) => {\r\n db.query('SELECT id, nom FROM outil ORDER BY nom')\r\n .then((result) => next(result))\r\n .catch((err) => next(err))\r\n })\r\n }", "function notificacionMasiva(titulo, cuerpo) {\n Usuario.find({}).then((usuarios) => {\n var allSubscriptions = [];\n usuarios.forEach((usuario) => {\n allSubscriptions = allSubscriptions.concat(usuario.suscripciones);\n });\n notificar(allSubscriptions, titulo, cuerpo);\n });\n}", "function loadAll() {\n var cidades = eurecaECBrasil.filtrarCidadeTextoService();\n return cidades.split(/, +/g).map( function (cidade) {\n return {\n value: cidade.toLowerCase(),\n display: cidade\n }; \n });\n }", "function listarAuxiliaresCadastrados(usuario, res){\n\t\tconnection.acquire(function(err, con){\n\t\t\tcon.query(\"select Auxiliar.idusuario, nomeAuxiliar, telefoneAuxiliar, emailAuxiliar from Auxiliar, Medico where Auxiliar.Estado = Medico.Estado and Auxiliar.Cidade = Medico.Cidade and Auxiliar.status=1 and Medico.idusuario = ?\", [usuario.idusuario], function(err, result){\n\t\t\t\tcon.release();\n\t\t\t\tres.json(result);\n\t\t\t});\n\t\t});\n\t}", "async function getData() {\n let cleanService = await CleanServiceModel.getCleanServiceById(id);\n setDitta(cleanService.ditta);\n setEmail(cleanService.email);\n setTelefono(cleanService.numeroTel);\n setDataAssunzione((new Date(cleanService.dataAssunzione.seconds * 1000)).toLocaleString(\"it-IT\").split(\",\")[0]);\n }", "function mostrarHoteles() {\n if (mostraStatus) {\n mostrarHotelesActivados();\n } else {\n mostrarHotelesDesactivados();\n }\n}", "getAlunos(){\n this.alunos = [];\n var info = this;\n HTTPRequest(\"GET\", \"/alunos\", function(res){\n for(let aluno of res.alunos){\n info.alunos.push(new Aluno(aluno.id, aluno.nome, aluno.dataNasc, aluno.genero, aluno.email, aluno.foto));\n }\n });\n }", "function showTodos() {\n db.allDocs({include_docs: true, descending: true}, function(err, doc) {\n redrawTodosUI(doc.rows);\n });\n }", "function listAllTasks() {\n for (var ix = 0; ix < toDoList.length; ix++) {\n console.log(ix + 1 + \": \" + toDoList[ix]);\n }\n}", "function todoList() {\n console.log(\"**********\");\n todoArray.forEach(function(todo, i) {\n console.log(i + \": \" + todo);\n });\n }", "async getTodosLosSensores() {\n var textoSQL = \"select * from Sensor\";\n console.log(\"logica: getTodosLosSensores\")\n return new Promise((resolver, rechazar) => {\n this.laConexion.all(textoSQL, {},\n (err, res) => {\n (err ? rechazar(err) : resolver(res))\n })\n })\n }", "function IndicadorRangoEdad () {}", "async getAllServices() {\n debug('get Dot4 service IDs from dot4SaKpiRepository');\n this.allServices = await this.request({\n method: 'get',\n url: '/api/service',\n });\n debug(`loaded ${this.allServices.length} services`);\n }", "async function limpiarOrganismos() {\n /**\n * Limpia la capa de la cual dependen de organismos\n */\n $(\"#Estados\").multiselect(\"reset\");\n await limpiarEstados();\n}", "function gps_consultarTabla() {\n autoConsulta = true;\n gps_opacaTabla();\n gps_iniciarAutoConsultaTabla(); // Consulta directamente\n gps_pausarAutoConsultaAuto(); // Pausa autoconsulta\n}", "function autoContacts() {\n $.post(\"consulta.php\", {\"get_allContacts\": true}).done(function(data) {\n var clientes = $.parseJSON(data);\n var contactsList = [];\n var salutation = \"\";\n for(var i in clientes) {\n if (clientes[i][\"salutation\"] != \"--None--\") {\n salutation = clientes[i][\"salutation\"];\n }\n contactsList.push({\n value: salutation+\" \"+clientes[i][\"firstname\"]+\" \"+clientes[i][\"lastname\"],\n type: \"Cliente\",\n accountname: clientes[i][\"accountname\"],\n phone: clientes[i][\"phone\"],\n email: clientes[i][\"email\"]\n });\n }\n $.post(\"consulta.php\", {\"get_leads\": true}).done(function(data) {\n var leads = $.parseJSON(data);\n for(var i in leads) {\n if (leads[i][\"salutation\"] != \"--None--\") {\n salutation = leads[i][\"salutation\"];\n }\n contactsList.push({\n value: salutation+\" \"+leads[i][\"firstname\"]+\" \"+leads[i][\"lastname\"],\n type: \"LEAD en BD\",\n accountname: leads[i][\"company\"],\n phone: leads[i][\"phone\"],\n email: leads[i][\"email\"]\n });\n }\n $(\"input[name='contacto']\").autocomplete({\n source: contactsList,\n select: function( event, ui ) {\n //var index = $.inArray(ui.item.value, contactsList);\n $(\"input[name='contacto']\").val(ui.item.value);\n $(\"input[name='empresa']\").val(ui.item.accountname);\n $(\"input[name='tel']\").val(ui.item.phone);\n $(\"input[name='email']\").val(ui.item.email);\n if (ui.item.value && ui.item.accountname && ui.item.phone && ui.item.email) {\n $(\"#valid\").text(\"0\");\n } else {$(\"#valid\").text(\"1\");}\n $(\"#select_origen\").val(\"Teléfono\");\n if ($(\"input[name='empresa']\").val() == \"\") {\n $(\"input[name='empresa']\").focus();\n } else {\n $(\"textarea[name='solicitud']\").focus();\n }\n },\n focus: function(event, ui) {\n $(\"#tipo_cliente\").text(ui.item.type);\n $(\"input[name='empresa']\").val(ui.item.accountname);\n },\n response: function(event, ui) {\n if (ui.content.length === 0) {\n //$(\"#tipo_cliente\").text(\"LEAD NUEVO\");\n }\n }\n });\n });\n });\n }", "function listAll() {\n getFilesFromFolder(\"Backup Binder\").then(function(classes) {\n for (i = 0; i < classes[1].files.length; i++) {\n getFilesFromFolder(classes[1].files[i].name).then(function(classwork) {\n var classID = classwork[0];\n var classContent = classwork[1].files;\n if ($(\"#binderContent\").text() == \"\") { // if binderContent is empty\n var dict = {};\n dict[classID] = classContent;\n $(\"#binderContent\").text(JSON.stringify(dict));\n }\n else { // if it's not empty\n var binderContentDict = $.parseJSON($(\"#binderContent\").text());\n binderContentDict[classID] = classContent;\n $(\"#binderContent\").text(JSON.stringify(binderContentDict));\n }\n }).then(function(cop) {\n\t\t\t addNamesToArray()\n\t\t\t //INIT()\n\t\t }).then(function() {\n\t\t\t addNamesToArray()\n\t\t }).catch(function(error) {console.log(error)});\n }\n\t\t\n\t\t\n\t }).then(function(oofo) {\n\t\t\taddNamesToArray()\n\t\t})\n \n }", "$onInit() {\n \t\tthis.sensoService.listasenso().then((data)=>{\n\t\t\tif(data.data.tipo = \"ok\"){\n\t\t\t\tthis.Listasensos = data.data.data\n\t\t\t}else{\n\t\t\t\tnotify.show('ERROR: No se cargaron los sensos.')\n\t\t\t}\n\t\t})\n\t\tthis.sensoService.listaClientes().then((data)=>{\n\t\t\tthis.Listaclientes = data.data.data\n\t\t})\n\t\t//busco todas las encuestas y les pongo un check en false\n\t\tthis.sensoService.listaEncuestas().then((data)=>{\n\t\t\tthis.Listaencuestas = data.data.data\n\t\t\tfor(let g in this.Listaencuestas){\n\t\t\t\t this.Listaencuestas[g].check = 0\n\t\t\t}\n\n\t\t})\n }", "function getClientes() {\n apiService.post('GetClientesCampaigns', {}, function(resp) {\n var options = ['<option value=\"\">Seleccione...</option>'];\n if(typeof resp == 'object' && resp.length > 0) {\n resp.forEach(function(data, index) {\n options.push(configuraOption(data));\n if(appendReady(index, resp)) {\n $('#selectReporteCampanas').empty();\n $('#selectReporteCampanas').append(options.join(''));\n }\n });\n }\n });\n }", "function VerificarAgendamentos() {\n\n\tvar ctx1 = new SP.ClientContext.get_current();\n\tvar web1 = ctx1.get_web();\n\tvar lists1 = web1.get_lists();\n\tctx1.load(lists1);\n\tvar list1 = lists1.getByTitle(\"AgendaSalasdeReuniao\");\n\tvar camlQuery1 = new SP.CamlQuery();\n\tcamlQuery1.set_viewXml(\"<View></View>\");\t\n\n\titemCollection1 = list1.getItems(camlQuery1);\n\tctx1.load(itemCollection1);\n\n\tctx1.executeQueryAsync(Function.createDelegate(this, this.onSuccess1),Function.createDelegate(this,this.onFailed));\n}", "function listOptions(){\n let msg = \n`'q' or 'quit' exit the app\n'help' '?' or 'list' display available scripts`\n\n console.log(BLUE, msg)\n}", "async list() {\n\n this.check()\n const migrations = this.migrations;\n let idx = 0;\n\n let curStep = await this.getCurentIndex();\n this.logger.info(`latest migration run is @${curStep}`)\n\n for (let el of migrations) {\n let loopStep = ++idx;\n this.logger.info(loopStep > curStep?'[ ]':'[v]', loopStep, el.fileName, loopStep > curStep?'todo':'done')\n }\n }", "obtenerTodosFincas() {\n return axios.get(`${API_URL}/v1/reportefincaproductor/`);\n }", "function fillUsuarios() {\n $scope.dataLoading = true;\n apiService.get('api/user/' + 'GetAll', null, getAllUsuariosCompleted, apiServiceFailed);\n }", "static mostrarLibros(){\n //le consulta a la clase datos y trae lo que hay en el localStorage y lo devuelve como un arreglo\n const libros = Datos.traerLibros();\n //recorrer el arreglo y le envío a la funcion, le envio el libro que es un elemento del arreglo y le envio como parametro al otro metodo agregarLibroLista\n libros.forEach((libro) => UI.agregarLibroLista(libro));\n }", "get listarTareas () {\n\n const arreglo = [];\n\n Object.keys(this._listado).forEach(indice => {\n arreglo.push(this._listado[indice]);\n })\n\n return arreglo;\n }", "function populateDepInfo() {\n const depCheck = document.querySelectorAll(\"#depTable tbody tr\"); //Get Department Table Rows\n let deps = getDeps();\n if (depCheck.length == 0) {\n for (let j = 0; j < deps.length; j++) {\n let depOb = new CRUD(\"depTable\", \"depSelect\", deps[j]); //Create Object for department\n depOb.addOption();\n depOb.addRow();\n }\n } else {\n removeExistingDep();\n populateDepInfo();\n }\n}", "function descarga(variable){\n alert(\"En un momento comenzara su descarga con la lista de tus tareas\");\n }" ]
[ "0.6746726", "0.63638836", "0.6344408", "0.62609273", "0.59965193", "0.5806011", "0.55198395", "0.54933554", "0.54217774", "0.5330804", "0.5274624", "0.5273494", "0.52241516", "0.516689", "0.51622593", "0.5161412", "0.5156986", "0.5153989", "0.515312", "0.5117778", "0.5100869", "0.5099997", "0.50898504", "0.5066477", "0.5064398", "0.5020514", "0.50169563", "0.4997254", "0.499545", "0.4980447", "0.49767137", "0.49629274", "0.4959399", "0.49546802", "0.49511227", "0.4950942", "0.4919422", "0.49116465", "0.49098694", "0.48929006", "0.48928338", "0.48839962", "0.48837698", "0.48803404", "0.48766622", "0.48761916", "0.4871707", "0.4862051", "0.4860844", "0.48607787", "0.48564416", "0.48478344", "0.4847651", "0.48440117", "0.48372164", "0.48336437", "0.48250258", "0.48182583", "0.4816234", "0.48141944", "0.48119918", "0.48119813", "0.4810607", "0.48080885", "0.48006412", "0.4798786", "0.47983342", "0.47958368", "0.47949922", "0.4793193", "0.47898212", "0.47898188", "0.4788641", "0.4788375", "0.47877073", "0.47839716", "0.47825307", "0.47822824", "0.47768706", "0.4776566", "0.4769898", "0.47698763", "0.4767518", "0.47669327", "0.47666752", "0.4762273", "0.4752391", "0.47471407", "0.47470027", "0.47435588", "0.474336", "0.47430855", "0.4742888", "0.47382542", "0.4737363", "0.4737023", "0.47348928", "0.47342378", "0.47337034", "0.47310922", "0.47300065" ]
0.0
-1
Elimina a un autor de forma permanente
DeleteAuthor(id_author) { let connection = new Connection(); connection = connection.createTheConnection(); let query = connection.query('DELETE FROM author WHERE id_author = ?', [id_author], (err, res) => { if (err) { return callback(false); } else { return callback(null, true); } }) connection.end(); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function deletarAgendamento() {\n\tfirebase.database().ref('users/' + uid).remove();\n\t$('#mdlVerAgendamento').modal('toggle');\n}", "function eliminarPersona(user,res){\n tb_persona.connection.query(\"DELETE FROM persona WHERE id=\" + user.id);\n res.send();\n}", "function eliminarContacto() {\n\n var id_ver = document.getElementById(\"ver\").value;\n\n for (let i = 0; i < agenda.length; i++) {\n\n let persona = agenda[i];\n\n if ((persona.id) == id_ver) {\n\n agenda.splice(persona.id, 1);\n cargarResumen();\n }\n }\n}", "eliminarUsuario({ item }) {\n let posicion = this.lista_usuario.findIndex(\n usuario => usuario.id == item.id\n );\n this.lista_usuario.splice(posicion, 1);\n this.saveLocalStorage();\n }", "function deleteActiveUser(delActiveUser) {\n alert(\"User \" + activeUser.nome + \" (\" + activeUser.numero + \") successfully logged out.\");\n localStorage.removeItem(\"ActiveUser\");\n resetVariables();\n}", "delete(nombre) {\n \n const usuario = this.read(nombre);\n const index = this.contactos.findIndex( contacto => contacto.id === usuario.id );\n\n if (index >= 0) {\n this.contactos.splice(index, 1)\n }\n\n // localStorage.setItem('contactos', JSON.stringify(contactos))\n \n }", "function delete_new_auth_row(id,newEmail) {\n $(\"#\" + id).remove();\n\n\n $(\"#main-form\").append(\n\t$('<input id=\"' + create_hidden_id(newEmail) + '\"/>')\n\t .attr('type', 'hidden')\n\t .attr('name', 'removed_added_user')\n\t .val(newEmail)\n );\n\n\n}", "function EliminarUsuarioIndicado(){\n\t//debugger;\n\t// obtiene el arreglo a la hora de parsear los usuarios\n\tvar chambas = JSON.parse(localStorage.getItem(\"usuarios\"));\n\t// este for recorre el arreglo de arreglos\n\tfor (i=0; i< chambas.length; i++){\n\t\t// este for recorre cada uno de los arreglos\n\t\tfor (j=0; j< chambas[i].length; j++){\n\t\t\t// le asigno a la variable eliminar el id que está actualmente\n\t\t\teliminar = JSON.parse(localStorage.getItem(\"id\"));\n\t\t\t// pregunto que si el id de eliminar es igual al id actual\n\t\t\tif(eliminar == chambas[i][j]){\n\t\t\t\t// si es verdad elimina el elemento que esta actualmente\n\t\t\t\tchambas.splice(i, 1);\n\t\t\t\t// vuelvo a guardar todos los arreglos sin el que se eliminó obviamente\n\t\t\t\tlocalStorage['usuarios'] = JSON.stringify(chambas);\n\t\t\t\t// muestro el mensaje que me dice que se eliminó\n\t\t\t\talert(\"Se Eliminó correctamente\");\n\t\t\t}\n\t\t}\n\t}\n}", "function deleteAccount() {\n var gebruiker_id = [session.get('gebruiker_id')];\n databaseManager\n .query(\"DELETE FROM gebruiker WHERE ID_GEBRUIKER = (?) \", [gebruiker_id]);\n alert('Uw account is succesvol verwijderd!');\n }", "function eliminarCliente(seleccionado) {\n delete_registrer(seleccionado, 'cliente/eliminar')\n}", "function eliminarDatos(uid){\n //console.log('voy a eliminar'+uid);\n firebase.database().ref(\"usuarios/\"+uid).remove();\n}", "function eliminar(id) {\n fetch(`${baseUrl}/${groupID}/${collectionID}/${id}`, {\n 'method': 'DELETE',\n }).then(res => {\n return res.json();\n }).then(json => {\n console.log(\"Se elimino correctamente\");\n precargarUsers();\n }); //agregar catch\n }", "eliminarAuto({ item }) {\n let posicion = this.informacion_vehiculos.findIndex(\n automovil => automovil == item\n );\n this.informacion_vehiculos.splice(posicion, 1);\n localStorage.setItem('automoviles', JSON.stringify(this.informacion_vehiculos));\n }", "function eliminarEntrada() {\n\tli.remove(); //remueve la entrada con el click del botoncito\n\t}", "function elimina_account(){\r\n var users = JSON.parse(localStorage.getItem(\"users\") || \"[]\");\r\n var user=JSON.parse(sessionStorage.user);\r\n\r\n for(var i=0;i<users.length;i++){\r\n if(users[i].username == user.username){\r\n users.splice(i, 1);\r\n localStorage.setItem(\"users\", JSON.stringify(users));\r\n elimina_all_prenotazioni();\r\n }\r\n }\r\n}", "function eliminar(i, e) {\n personas.splice(i, 1);\n guardar();\n mostrarEmpleados();\n}", "function removeUser(){\n\tfor(i in currentProject.members){\n\t\tif(currentProject.members[i].name == savedMem){\n\t\t\tfor (j in currentProject.members[i].role) {\n\t\t\t\tdelete currentProject.members[i].name;\n\t\t\t\tdelete currentProject.members[i].role[j];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tdocument.getElementById(\"EditUser\").style.display = \"none\";\n\tpopTable();\n}", "function delAdmin(N) {\n TempAdmin = N;\n id = obj.admins[TempAdmin]._id;\n llamada(true, \"DELETE\", \"https://lanbide-node.herokuapp.com/admins/\" + id, \"JSON\");\n}", "function eliminarRegistro(id){\n\tlocalStorage.removeItem(id);\n\t//Mostrar Tabla\n\tlistarEstudiantes();\n}", "function eliminarEmpresa(req, res) {\n let tokenUser = req.usuario;\n\n Empresa.findOneAndDelete(tokenUser.sub, { useFindAndModify: true }, (err, empresaEliminada) => {\n if (err) {\n return res.status(500).send({ ok: false, message: 'Hubo un error en la petición.' });\n }\n\n if (!empresaEliminada) {\n return res.status(404).send({ ok: false, message: 'El ID ingresado no existe.' });\n }\n\n return res.status(200).send({ ok: true, empresaEliminada });\n });\n}", "function removeAchivementsUser(req, res, next) {\n if (validate(req, res)) {\n db.result('delete from achievements_x_user where achievement_id=$1 and user_mail=$2', [parseInt(req.body.achievement_id), req.params.mail])\n .then(function(result) {\n /* jshint ignore:start */\n res.status(200)\n .json({\n status: 'success',\n message: `Removed ${result.rowCount} Achievement per User`\n });\n /* jshint ignore:end */\n })\n .catch(function(err) {\n res.status(500)\n .json({\n status: 'error',\n err: err\n });\n });\n }\n}", "function remove() {\n // REMOVE FROM DB\n let uid = $rootScope.account.authData.uid;\n $rootScope.db.users.child(uid).remove();\n }", "function Eliminarcore(e){\n var est=confirm(\"Desea eliminar el correo?\");\n if(est){\n carRec.splice(e,1); \n localStorage.setItem(\"correosRecibidos\", JSON.stringify(carRec));\n }\n }", "function eliminar(){\r\n var asignar=document.formulario.valores.value;\r\n var nuevoValor=asignar.substring(0,asignar.length-1);\r\n document.getElementById(\"valores\").value=nuevoValor;\r\n }", "async remove() {\n // this function is really just a wrapper around axios\n await axios({\n url: `${BASE_URL}/users/${this.username}`,\n method: \"DELETE\",\n data: {\n token: this.loginToken\n }\n });\n }", "function deleteAdminOff(id) {\n\tfor (let i = 0; i < adminOfficerArr.length; i++) {\n\t\tif (adminOfficerArr[i].id == id) {\n\t\t\tadminOfficerArr.splice(i, 1);\n\t\t\t// localStorage.removeItem(id);\n\t\t}\n\t}\n\tinsertAdminOfficer();\n}", "function ClickExcluir() {\n var nome = ValorSelecionado(Dom('select-personagens'));\n if (nome == '--') {\n Mensagem('Nome \"--\" não é válido.');\n return;\n }\n var local = nome.startsWith('local_');\n var sync = nome.startsWith('sync_');\n if (local) {\n nome = nome.substr(nome.indexOf('local_') + 6);\n } else if (sync) {\n nome = nome.substr(nome.indexOf('sync_') + 5);\n }\n JanelaConfirmacao('Tem certeza que deseja excluir \"' + nome + '\"?',\n // Callback sim.\n function() {\n ExcluiDoArmazem(nome, function() {\n Mensagem(Traduz('Personagem') + ' \"' + nome + '\" ' + Traduz('excluído com sucesso.'));\n CarregaPersonagens();\n });\n },\n // Callback não.\n function() {});\n}", "async remove() {\n const { id } = this;\n const options = {\n TableName: process.env.userTableName,\n Key: ddb.prepare({ id })\n };\n return ddb.call('deleteItem', options);\n }", "function remover_telefone(id){\n jQuery('#'+id).remove();\n //Quando remove, atualiza a lista com a quantidade de inputs para desbloquear o botão\n jQuery(\"#botao_add_other\").prop(\"disabled\",false);\n}", "function eliminar_user(identidad) {\n\tenvio = { codigo: identidad }\n\tcargando('Procesando...')\n\t$.ajax({\n\t\tmethod: \"POST\",\n\t\turl: \"/admin-cliente/eliminar-cliente\",\n\t\tdata: envio\n\t}).done((respuesta) => {\n\t\tif (respuesta == 'Error al eliminar el cliente') {\n\t\t\t$('#div-error').html('Tarjeta no encontrada')\n\t\t\tdocument.getElementById('div-error').style.display = 'block'\n\t\t\tno_cargando()\n\t\t} else {\n\t\t\tlocation.reload()\n\t\t\tno_cargando()\n\t\t}\n\t})\n}", "function deleteAstronaut(r){\r\n var index = r.parentNode.parentNode.rowIndex-1;\r\n var astro = JSON.parse(localStorage.getItem('astro'));\r\n var name = astro[index].name;\r\n var surname = astro[index].surname;\r\n if(confirm('Do you want to delete '+name+' '+surname+' from the record?')){\r\n astro.splice(index, 1);\r\n }\r\n localStorage.setItem('astro', JSON.stringify(astro));\r\n addAstronaut();\r\n}", "removeUser(id) {\n let user = this.getUser(id); //PRIMERO CONSIGO EL OBJETO QUE QUIERO ELEMINAR / QUE SERIA EL USUARIO\n if (user) { //digo en caso tenga un usuario\n this.users = this.users.filter(user => user.id !== id);\n }\n\n return user;\n }", "removeUser(user) {\n // User in Array suchen und \"rausschneiden\"\n for (var i=this.users.length; i >= 0; i--) {\n if (this.users[i] === user) {\n this.users.splice(i, 1);\n }\n }\n // geänderte Raumdetails wieder an alle senden\n var room = this;\n room.sendDetails();\n}", "function deleteAccount() {\n $(this).closest('tr').remove();\n }", "function adminDelete(id){\n manga = biblioteca[id]\n let validar = confirm(`Esta seguro de querer eliminar a ${manga.titulo}`)\n\n if(validar){\n biblioteca.splice(id,1)\n localStorage.setItem('biblioteca',JSON.stringify(biblioteca))\n alert(`Se borro ${manga.titulo}`)\n cargarManga4(biblioteca)\n }\n}", "function supprimerUtilisateurs(){\n var request = new XMLHttpRequest();\n var id = document.getElementById(\"txtutiId\").value;\n var url = \"/tusers/\"+id ;\n // bootbox.alert(\"url = \" + url);\n request.open(\"DELETE\", url, true);\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n if (request.status === 200) {\n ramplirtabUti();\n // bootbox.alert(\"Suppression réussi\");\n bootbox.alert(\"Suppression réussi\");\n document.getElementById(\"txtutiNom\").focus();\n }\n else {bootbox.alert(\"Erreur lors de la suppression\");}\n }\n };\n request.send();\n} // end supprimer", "function EliminarUsuario(req , res , next)\n {\n\n connection.query('DELETE FROM `usuario` WHERE `idusuario` = '\n +req.params.idusuario, \n function (error, success)\n {\n if(error) throw error;\n res.send(200, 'Eliminado con exito');\n }\n );\n }", "removeUser(user) {\n this.active_list = this.active_list.filter((a_user) => a_user.email !== user.email);\n this.setValue(this.active_list);\n }", "function supprimerAuteur(){\n var request = new XMLHttpRequest();\n var id = document.getElementById(\"txtautId\").value;\n var url = \"/tauteur/\"+id ;\n request.open(\"DELETE\", url, true);\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n if (request.status === 200) {\n ramplirtabAut();\n // bootbox.alert(\"Suppression réussi\");\n bootbox.alert(\"Suppression réussi\");\n document.getElementById(\"txtautNom\").focus();\n }\n else {bootbox.alert(\"Erreur lors de la suppression\");}\n }\n };\n request.send();\n} // end supprimer", "function pinchar(e) {\n\n document.getElementById(e.target.id).remove();\n txtBolasEliminadas.text(`Bolas Eliminadas : ${eliminadas+=1}`);\n }", "function deleteAnimeFromUserList(animeID) {\n db.transaction((tx) => {\n tx.executeSql(\n \"delete from userlist where id = ?\",\n [Number(animeID)],\n () => {\n console.log(\n `useDB: Deleted anime with id ${animeID} from userlist in database!`\n );\n dispatch(deleteUserDataListItem({ id: animeID }));\n }\n );\n });\n }", "function deleteCreator(creator_email) {\n conn.query('DELETE FROM Creator_Data WHERE email=$1', [creator_email])\n .on('error', console.error);\n}", "function deleteUseraccount() {\n data = \"name=\" + String($(\".username.act\").html()) + \"^class=User\";\n dbOperations(\"user\", \"delete_operation\", data);\n $(\"li.actparent\").remove();\n $(\"#userhistorypane\").css(\"opacity\", \"0\");\n check_for_active_row(\"username\", \"acc\");\n $(\"#userhistorypane\").animate({\n opacity: 1\n });\n\n}", "deleteAccount(peerAddr) {\n let accts = this.getAccounts();\n delete accts[peerAddr];\n globalState.set('000-reputation-accounts', peerAddr);\n }", "function EliminarTel(indice) {\n telefonoItems.Eliminar(indice);\n MostrarTelefonos(true);\n return false;\n}", "deleteAccount(){\n let userId = firebase.auth().currentUser.uid;\n this.state.user.delete().then(function() {\n console.log('delete user')\n let ref = firebase.database().ref().child('users/'+userId);\n ref.remove();\n this.props.navigation.navigate('ProfilScreen')\n })\n .catch(function(error) {\n // An error happened.\n console.log(error.message)\n alert('Une erreur est apparue. Déconnectez-vous puis reconnectez-vous avant de réessayer')\n });\n }", "unsubscribe(email)\n {\n if (this.hasUser(email)) // Si esta suscripto\n {\n const indexToRemove = this.users.indexOf(email);\n this.users.splice(indexToRemove,1);\n }\n }", "function ctrlDeleteItem(event) {\n let accID, splitID, ID;\n acc = event.target.parentNode.parentNode.parentNode; // get the li\n accID = event.target.parentNode.parentNode.parentNode.id; // get the id\n\n if (accID) {\n ID = accID;\n // if user confirms delete\n\n //delete acc from user interface\n deleteFromUI(acc);\n if (user[0] === \"foyafa\" && user[1] === \"12345\") {\n // delete the acc from firebase\n db.collection(\"accounts\").doc(ID).delete();\n } else if (user[0] === \"admin\" && user[1] === \"12345\") {\n db.collection(\"test\").doc(ID).delete();\n } else if (user[0] === \"george\" && user[1] === \"12345\") {\n db.collection(\"account\").doc(ID).delete();\n }\n }\n }", "function eliminarViaje(e) {\n eaux = e\n let idDel = e.parentElement.getAttribute('data-id')\n db.collection(\"Viajes\").doc(idDel).delete()\n\n}", "deleteUser() {\n this.deleteBox.seen = true\n }", "delete(req, res, next, currentUser) {\n if (currentUser && currentUser.isAdmin) {\n User.findByIdAndRemove(req.params.id, (err) => {\n res.sendStatus(200);\n });\n } else {\n res.status(\"401\").send(\"Not authorized, your are not admin!\");\n }\n }", "deleteAccount (accountName) {\r\n let accountIndex = this.findAccountIndex(accountName);\r\n if (accountIndex !== -1) {\r\n this._accountList.splice(accountIndex, 1);\r\n } else {\r\n console.log('Account by the name' + accountName + ' not found');\r\n }\r\n }", "function DeleteAsistencia(idAsistencia) {\n let i = 0;\n asistieron.forEach(element => {\n if (element == idAsistencia) asistieron.splice(i, 1);\n i++;\n pintarFalta(idAsistencia);\n })\n console.log(\"ELEMENTO ELIMINADO\" + idAsistencia);\n console.log(asistieron);\n \n}", "deleteGrupo(idMaestro, idMateria, idTurno){\n console.log(idMaestro, idMateria, idTurno);\n }", "function deleteMboElement(i_row){\n var id = SHEET_MAIN.getRange(i_row, 3).getValue();\n if (id > 0){\n checkJWT();\n var res = _deleteMboElement(keyJWT, urlHome, id);\n Logger.log(res);\n }\n SHEET_MAIN.deleteRow(i_row);\n}", "function removeUser(user_name) {\r\n var user_list = document.getElementById('user_list');\r\n var el_name = document.getElementById(user_name);\r\n\r\n user_list.removeChild(el_name);\r\n}", "deleteAccessory(event) {\n let ind = this.accesList.findIndex(record => record.Id === event.target.dataset.id);\n this.accesList.splice(ind, 1);\n this.countTotalAmontOnchange();\n }", "function eliminarId(id) {\n $.ajax({\n type: 'POST',\n data: \"id=\" + id,\n url: '../controllers/autor/autorObtenerID.php',\n cache: false,\n success: function (r) {\n r = JSON.parse(r);\n $('#txtidauel').val(r['id_autor']);\n $('#txtnombreauel').html(r['nombre']);\n $('#txtemailauel').html(r['email']);\n }\n });\n}", "function elimina(id_traccia,id_user)\n{\n\t\t$.ajax({\n\t\t\t\t/* Metodo con cui viene mandata la variabile alla pagina */\n\t\t\t\ttype:\"POST\",\n\n\t\t\t\t/* Pagina a cui viene inviata la variabile id */\n\t\t\t\turl:\"elimina_traccia.php\",\n\t\t\t\t\n\t\t\t\t/* Valori che vengono inviati alla pagina \"elimina_traccia.php\" */\n\t\t\t\tdata:\"id_traccia=\"+id_traccia+\"&id_user=\"+id_user,\n\n\t\t\t\tsuccess:function(data)\n\t\t\t\t{\n\t\t\t\t\tif(data=='ok')\n\t\t\t\t\t\twindow.location = 'carrello.php';\n\t\t\t\t\telse\n\t\t\t\t\t\twindow.alert('Errore');\n\t\t\t\t},\n\t\t});\t\n}", "function removeUserArticle(user) {\n document.querySelector(`[data-id=\"${user.id}\"]`).remove();\n}", "function eliminar(){\n\tvar anterior=document.fo.valores.value;\n\n\tvar nuevovalor=anterior.substring(0,anterior.length-1);\n\n\tdocumnet.getElementById(\"valores\").value=nuevovalor;\n}", "async destroy({ params, auth }) {\n const chamado = await Chamado.findOrFail(params.id);\n\n if (chamado.user_id !== auth.user.id) {\n return response.status(401);\n }\n\n await chamado.delete();\n }", "eliminarOperarioPersona(id) {\n return axios.delete(`${API_URL}/v1/operario/${id}`);\n }", "function supprimerAdminId(userId) {\n return connSql.then(function (sql) {\n let resultat = sql.query(\"DELETE FROM administrateur WHERE id=?\", [userId]);\n return resultat\n });\n}", "function removeUser(Email)\n{\n\tbootbox.confirm(\"<div class='text'><b>Por favor introduza o seu código.</b><br><br><br>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t <div class='form-group'>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t <input style='width: 300px;' type='password' class='form-control' id='Password'>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t </div>\", function(result) {\n\n\t\tif(result)\n\t\t{\n\t\t\tchrome.storage.local.get(Email, function (result) {\n\n\t\t\t\tvar pass = CryptoJS.SHA3($('#Password').val());\n\n\t\t\t\tif(_.isEqual(pass, result[Email]))\n\t\t\t\t{\n\t\t\t\t\tbootbox.confirm(\"<div class='text'><b>Utilizador prestes a ser removido. <br><br>Deseja continuar?</b></div>\", function(result) {\n\n\t\t\t\t\t\tif(result)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tchrome.storage.local.remove(Email, function() {\n\n\t\t\t\t\t\t\t\tchrome.storage.local.remove('id-'+Email, function() {});\n\n\t\t\t\t\t\t\t\tbootbox.alert(\"<br><div class='text'><b>Utilizador removido com sucesso</b></div>\");\n\n\t\t\t\t\t\t\t\tgetData();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tbootbox.alert(\"<br><div class='text'><b>Introduziu um código errado. <br><br>Tente de novo.</b></div>\");\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}", "deletePacman(){\n this.remove(this.pacman);\n }", "function deleteAuthor() {\n\tvar snippet = {\n\t\tquery: {\"id\": \"-K_W_cxqkjGVo8zEfLUc\"}\n\t}\n\trimer.author.delete(snippet, function(error, value) {\n\t\tif(error) {\n\t\t\tconsole.log(error)\n\t\t}\n\t\telse {\n\t\t\tconsole.log(value)\n\t\t}\n\t})\n}", "function adm_delete_user() {\n\n // checker om admin er logget ind: \n if (localStorage.getItem('admin')) {\n const login_details = JSON.parse(localStorage.getItem(\"admin\"))\n if (email === login_details.email) {\n console.log(\"logget ind skirt skirt\")\n }else {\n console.log(\"Ikke logget ind endnu mæps\")\n }\n }\n \n let email = document.getElementById(\"email\").value \n\n alert(\"User has been deleted\")\n\n fetch(`http://localhost:7071/api/adm_delete_user`, {\n method: 'DELETE',\n headers: {\n \"Content-Type\": \"application/json; charset-UTF-8\"\n },\n body: JSON.stringify({ \n \"email\": email\n }),\n })\n .then((response) => {\n return response.json()\n })\n .catch((err) => {\n console.log(err)\n })\n}", "function deleteArbeit(x, y) {\r\n\t$each(MoCheck.getAktArbeiten(), function(aktArbeit, index) {\r\n\t\tif(x == aktArbeit.pos.x && y == aktArbeit.pos.y) {\r\n\t\t\t\r\n\t\t\tif(confirm(unescape(MoCheck.getString('message.deleteFromList', aktArbeit.name)))) {\r\n\t\t\t\t//Arbeit aus Array entfernen\r\n\t\t\t\tMoCheck.getAktArbeiten().splice(index, 1);\r\n\t\t\t\t\r\n\t\t\t\t//Arbeit aus Cookie loeschen\r\n\t\t\t\tMoCheck.setCookie();\r\n\t\t\t\t\r\n\t\t\t\t//Arbeit-Liste neu laden\r\n\t\t\t\tMoCheck.printResults();\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n}", "remove(paladinID) {\n const palList = STATE.PaladinList.get();\n const index = palList.findIndex(pID => { return pID === paladinID; });\n if (index !== -1) {\n palList.splice(index, 1);\n STATE.PaladinList.set(palList);\n // // Remove the token's character's paladin abilities\n // const tokenObj = STATE.get('TokenList', paladinID) as TokenObj | undefined;\n // if (tokenObj !== undefined && tokenObj.characterID !== undefined) {\n // const abilities = findObjs({\n // _type: 'ability',\n // _characterid: paladinID,\n // }) as Ability[];\n // const abilitiesToRemove = abilities.filter(a => {\n // return Paladin.paladinAbilities().some(b => { return b[0] === a.get('name'); });\n // });\n // abilitiesToRemove.forEach(a => {\n // a.remove();\n // });\n // }\n }\n }", "function remove(id) {\n $.ajax({\n url: base_url + `todos/${id}`,\n method: \"DELETE\",\n headers: {\n token: localStorage.getItem(\"access_token\")\n }\n })\n .done(response => {\n aut()\n })\n .fail((xhr, text) => {\n console.log(xhr, text)\n })\n }", "function deleteCharacter() {\n setMatricula(matricula.slice(0, -1));\n setMatriculaLogada(matricula.slice(0, -1));\n if (matricula.length <= 1) {\n setInputVisible(false);\n setAluno({ auth: \"\", access: false, name: \"\" });\n }\n }", "function delete_auth_row(user_info, pk, user_type) {\n var rowID = createValidID(user_info);\n var hidden_input_id = \"deleted_auth_\" + user_type + \"_\" + pk; \n $(\"#\" + rowID).css(\"text-decoration\", \"line-through\");\n\n var newCellContents = \n\t\"<button type='button' onclick='undo_auth_delete(\\\"\" \n\t+ rowID \n\t+ \"\\\", \\\"\"\n\t+ hidden_input_id \n\t+ \"\\\",\\\"\"\n\t+ pk\n\t+ \"\\\",\\\"\"\n\t+ user_type\n\t+ \"\\\")'>Undo</button>\";\n\n $(\"#\" + rowID + \" td:nth-child(2)\").html(newCellContents);\n\n $(\"#main-form\").append(\n\t$('<input/>')\n\t .attr('type', 'hidden')\n\t .attr('name', 'deleted_user_' + user_type)\n\t .attr('id', hidden_input_id)\n\t .val(pk)\n );\n}", "function supprimerFamille(){\n var request = new XMLHttpRequest();\n var id = document.getElementById(\"txtfamId\").value;\n var url = \"/tfamille/\"+id ;\n request.open(\"DELETE\", url, true);\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n if (request.status === 200) {\n ramplirtabFam();\n // bootbox.alert(\"Suppression réussi\");\n document.getElementById(\"txtfamCode\").focus();\n }\n else {bootbox.alert(\"Erreur lors de la suppression\");}\n }\n };\n request.send();\n} // end supprimer", "function eliminarAlumno(legajoActual){\n for (let i = 0; i < listadoAlumnos.length; i++){\n if(listadoAlumnos[i][\"legajo\"] == legajoActual){\n //elimino del Array\n listadoAlumnos.splice(i, 1);\n //Elimino del local storage, no estaria eliminando lo que se carga con la pagina\n localStorage.removeItem(legajoActual);\n }\n }\n}", "function removeFco(id){\n console.log('Rimuovi dai preferiti: '+id);\n UserService.removeElementFco(id)\n .then(\n function(){\n console.log('ID '+id + ' removed successfully');\n },\n function(errResponse){\n console.error('Error while removing user '+id +', Error :'+errResponse.data);\n }\n );\n\n }", "function eliminarAuto() {\r\n\r\n document.getElementById(\"fila2\").remove();\r\n subT2 = 0;\r\n actualizarCostos();\r\n\r\n}", "async deleteUser(req,res){\n //función controladora con la lógica que elimina un usuario\n }", "function eliminar(id)\n {\n \tvm.prueba.splice(id, 1);\n \tconsole.log(vm.prueba);\n \t}", "function deletePerson3(person) {\n document.getElementById('tblPerson').removeChild(person);\n}", "function deletaId(id){\n console.log('eita foi!!!: ', id)\n}", "function Eliminar(btn){\n\tvar route = \"/genero/\"+btn.value+\"\";\n\tvar token = $(\"#token\").val();\n\t\n\t//se envia la peticion mediante el metodo DELETE con el id del genero\n\t$.ajax({\n\t\turl: route,\n\t\theaders: {'X-CSRF-TOKEN': token},\n\t\ttype: 'DELETE',\n\t\tdataType: 'json',\n\t\tsuccess: function(){\n\t\t\tCarga();\n\t\t\t$(\"#msj-success\").fadeIn();\n\t\t}\n\t});\n}", "removeAccount(id)\n {\n if (typeof(id) == \"object\")\n id = id.id\n\n let index = this.accounts.findIndex(x => x.id == id)\n\n if (index == -1)\n return\n\n this.accounts.splice(index, 1)\n\n if (this.meta[\"settings.default-account\"] == id)\n this.meta[\"settings.default-account\"] = null\n }", "function remover_poligono()\n{\n\tif(creator){\n\t\tcreator.destroy();\n\t\tcreator=null;\n\t}\n}", "eliminarFertilizante(id) {\n return axios.delete(`${API_URL}/v1/fertilizacion/${id}`);\n }", "function removeUser() {\n var user = $('#query-input-verwijder').val();\n var userid;\n\n databaseManager\n .query(\"SELECT ID_GEBRUIKER FROM gebruiker WHERE NAAM = (?)\", [user])\n .done(function (data) {\n\n if (data == \"\") {\n alert(\"Gebruiker is niet gevonden\");\n } else {\n userid = data[0].ID_GEBRUIKER;\n databaseManager\n .query(\"DELETE FROM gebruiker WHERE ID_GEBRUIKER = (?)\", [userid]);\n alert(\"Gebruiker is verwijderd\");\n }\n })\n }", "function remover2(turnos2) {\n registrados = JSON.parse(localStorage.getItem('registra2'))\n registrados.splice(turnos2, 1)\n localStorage.setItem('registra2', JSON.stringify(registrados))\n mostrar();\n}", "function removeWithId(){\n Users.removeUser(idSave);\n warning.style.display=\"none\";\n backgroundPicked.style.display = \"none\";\n printEmployees();\n}", "function supprimerEditeur(){\n var request = new XMLHttpRequest();\n var id = document.getElementById(\"txtediId\").value;\n var url = \"/tediteur/\"+id ;\n request.open(\"DELETE\", url, true);\n request.onreadystatechange = function() {\n if (request.readyState === 4) {\n if (request.status === 200) {\n ramplirtabEdi();\n // bootbox.alert(\"Suppression réussi\");\n bootbox.alert(\"Suppression réussi\");\n document.getElementById(\"txtediNom\").focus();\n }\n else {bootbox.alert(\"Erreur lors de la suppression\");}\n }\n };\n request.send();\n} // end supprimer", "function EliminarEmail(indice) {\n emailItems.Eliminar(indice);\n MostrarEmails(true);\n return false;\n}", "function eliminar(id) {\n limpiar();\n $('#id').val(id);\n //muestra la modal de confirmacion\n $('#MdDeshabilitar').modal('toggle');\n\n //cambia los botones\n $('#bt-guardar').html('<i class=\"material-icons\">cached</i>Actualizar');\n $('#bt-guardar').removeClass('btn-success');\n $('#bt-guardar').removeClass('btn-warning');\n $('#bt-guardar').addClass('btn-info');\n}", "function eliminar(key_empleado){\n const dbRef_empleados = firebase.database().ref('empleados/' + key_empleado);//.child('empleados');\n dbRef_empleados.remove();\n}", "function delete_personne(){\n\t// Recuperation de l'id de la personne\n\tvar id_contact = liste_pers_contacts.getCoupler().getLastInformation();\n\t\n\tif(id_contact != -1) {\n\t\tvar xhr = new XMLHttpRequest();\n\t\txhr.open(\"DELETE\", \"/personnes/delete/\"+id_contact, false);\n\t\txhr.send();\n\t\t\n\t\tsocket.emit(\"update\",{url: \"/personnes\",func: getHandler(function(url){\n\t\t\tliste_contacts.clear();\n\t\t\tvar prs = DatasBuffer.getRequest(\"/personnes\");\n\t\t\tfor(var i=0;i<prs.length;i++)\n\t\t\t{\t\n\t\t\t\tliste_contacts.addItem('<p class=\"nom_contact\">'+prs[i].nom+'</p>',prs[i]._id);\n\t\t\t}\n\t\t\tliste_contacts.update();\n\t\t})});\n\n\t\tliste_pers_contacts.clear();\n\t\tliste_pers_contacts.update();\n\t\tGraphicalPopup.hidePopup(popup_sup_personne.getPopupIndex());\n\t}\n}", "delete() {\n let id = $(\"#rid\").val();\n reReg.delete(id);\n $(\"#editDeleteModal\").modal('hide');\n }", "function deleteAccount() {\n const token = sessionStorage.getItem('token')\n\n fetch(`${BASE_URL}/deleteUser`, {\n method: 'DELETE',\n headers: {\n 'x-access-token': token\n }\n })\n .then(resp => {\n logout()\n getKanjiFromDatabase()\n makeModalDisapper('delete-account')\n })\n .catch(err => {\n console.error(err)\n Swal.fire({\n icon: 'error',\n title: 'Account failed to delete error',\n text: 'Failed to delete account. Please try again.'\n })\n })\n}", "static delete(email) {\n // TODO\n }", "function eliminarContacto(nombreEliminar){\n\tarrayContactos.forEach((elemento,index)=>{\n\t\tif(elemento.nombre==nombreEliminar){\n\t\t\tarrayContactos.splice(index,1);\n\t\t}\n\t});\n\tguardarDatosLocales();\n}", "function delete_private_room(room_name) {\n // will return -1 when user name not found\n const target_index = private_rooms.findIndex(room => room.name === room_name); \n if (target_index !== -1){\n // will get user out of the array\n return private_rooms.splice(target_index, 1);\n }; \n}", "function desactivar(per_id){\n\tbootbox.confirm(\"¿Esta seguro de desactivar la persona?\",function(result){\n\t\tif (result) {\n\t\t\t$.post(\"../ajax/persona.php?op=desactivar\", {per_id : per_id}, function(e){\n\t\t\t\tbootbox.alert(e);\n\t\t\t\ttabla.ajax.reload();\n\t\t\t});\n\t\t}\n\t})\n}", "delete(requisicao, resposta, next){\n try{\n const postgre = new postgresDB();\n const response = postgre.deleteUser(requisicao, resposta, next);\n return response;\n }\n catch(error){\n resposta.status(503).send(error);\n }\n }", "function deleteSelected(){\n\t$('#deleteAccountBtn').on('click', function(){\n\t\tconst deletedUser = getUsername();\n\t\tdeleteUser(deletedUser);\n\t\tanomymizeUser(deletedUser);\n\t});\n}" ]
[ "0.6655156", "0.66509795", "0.6445108", "0.63258016", "0.62967265", "0.62295526", "0.6170273", "0.6165797", "0.6147298", "0.61373544", "0.6123039", "0.6098199", "0.6079469", "0.60413927", "0.6024179", "0.60149723", "0.60099196", "0.60044533", "0.5968627", "0.59415555", "0.59401107", "0.59388936", "0.5931529", "0.59311134", "0.5930888", "0.5930555", "0.59295636", "0.5920011", "0.5912653", "0.59064007", "0.58958846", "0.58845377", "0.58780265", "0.58752245", "0.58495003", "0.5841818", "0.58416224", "0.582049", "0.5816345", "0.58081394", "0.58076286", "0.58048433", "0.5802705", "0.5774491", "0.57544494", "0.5744984", "0.5743715", "0.573413", "0.5731881", "0.5723932", "0.57134014", "0.5713126", "0.57112545", "0.569696", "0.568613", "0.56836975", "0.56833524", "0.56781805", "0.56780386", "0.56680983", "0.5663385", "0.5661789", "0.5657486", "0.5653747", "0.5648283", "0.56445074", "0.5644428", "0.5637965", "0.5630097", "0.56255674", "0.5621266", "0.5620925", "0.56200325", "0.562", "0.5619625", "0.5618774", "0.5614928", "0.56116855", "0.5608182", "0.56067985", "0.5606757", "0.5606582", "0.5605975", "0.5605372", "0.56052715", "0.5602324", "0.5600728", "0.560029", "0.5598643", "0.5596883", "0.55963856", "0.5594573", "0.5591058", "0.5583336", "0.55793315", "0.55787784", "0.5576714", "0.55664134", "0.5566372", "0.5561023", "0.55608034" ]
0.0
-1
=== ES6 class , === instead of providing a separate getInitialState method, === set up your own state property in the constructor.
constructor(props) { //=== Clock.propTypes = { cw: PropTypes.number.isRequired, ch: PropTypes.number.isRequired, istyle: PropTypes.object }; //=== props Clock.defaultProps = { cw: 350, ch: 350, istyle: { hmsColor: { h: 'red', m: 'cyan', s: 'red' }, fontSize: 20, backgroundColor: 'white', labelColor: 'orange', hSize: { w: 40, h: 90 }, mSize: { w: 20, h: 140 }, sSize: { w: 10, h: 160 } } }; // external props will override the defaultProps? super(props); if (!props.istyle) props.istyle = Clock.defaultProps.istyle; //if (!props.istyle.position) props.istyle.position = Clock.defaultProps.istyle.position; if (!props.istyle.hSize) props.istyle.hSize = { w: props.cw / 20, h: (props.ch / 2) * 0.65 }; if (!props.istyle.mSize) props.istyle.mSize = { w: props.cw / 30, h: (props.ch / 2) * 0.75 }; if (!props.istyle.sSize) props.istyle.sSize = { w: props.cw / 40, h: (props.ch / 2) * 0.85 }; if (!props.istyle.fontSize) props.istyle.fontSize = 20; if (!props.istyle.backgroundColor) props.istyle.backgroundColor = 'cyan'; if (!props.istyle.labelColor) props.istyle.labelColor = 'orange'; //=== initial state this.state = { cw: props.cw, ch: props.ch, // hVal: 0, // mVal: 0, // sVal: 0 hmsVal:{hour:0, min:0, sec:0} }; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "constructor(props) { // be promoted into a class\n super(props);\n this.state = {}; // defines initial state\n }", "constructor() {\n this.state = undefined\n }", "constructor() {\n // Run super\n super();\n\n // Bind private methods\n this.state = this.state.bind(this);\n }", "constructor() {\n super()\n this.state = intialState\n }", "constructor(state) {\n this.state = undefined;\n this.setState(state);\n }", "constructor() {\n super();\n this.state = defaultState;\n }", "constructor() {\n super(...arguments);\n this.state = this.constructor.initialState(this.props);\n }", "constructor(props) {\n super(props); //Call the base class constructor 'Component' with the 'props' argument\n //State object\n this.state = {}; //Set to empty object or provide initial values for some of the state properties used in this component\n }", "constructor() { \r\n super();\r\n this.state = {};\r\n }", "constructor() {\n super();\n this.state = {};\n }", "constructor(props) {\n super(props);\n\n this.state = defaultState;\n }", "constructor(props) {\n super(props);//reference to parents constructor with props\n\n // now this can be referenced anywhere inside the class. Basically like a JAVA Object. we only use this.state once. then we use this.setState\n this.state={lat:null, errMessage:null};// 1st way to initialize state. \n }", "constructor() { // this is a method that is automatically called during the creation of an object from a class. The Constructor aids in constructing things\n super(); // super is used to call the parent function of an object\n\n this.state = { //property under class, a place to hold data and user input\n message: \"\" //message is an empty string to allow the user to store their own data into it\n };\n }", "constructor() {\n super();\n this.state = {\n };\n }", "constructor() {\n super()//this is required because we extended reacts component class and call has to be made to the base class constructor and then we create our state object\n this.state = {\n message: 'Welcome Visitor'\n // initialised property\n\n }\n }", "constructor(props) {\n // calls parent class' constructor with `props` provided - i.e. uses Component to setup props\n super(props);\n // set initial state\n this.state = {\n mount: false\n };\n }", "constructor() {\r\n // super (the constructor of the parent class, what the child extends - in this case, React.Component) must be called before the `this` keyword can be used in a class. this is a JavaScript thing, not a React specific thing.\r\n super();\r\n // normally your state will be an object literal, but I want to give users the opportunity to restart their game, so I use this function to return the initial state in the places I need it so I don't repeat myself. see the getFreshState() method below to see what this state will look like.\r\n // NEVER write this.state.property = value. ALWAYS use this.setState() and pass in an object with the properties and new values you want to update. this is how React knows when to rerender. \r\n // if you want a child component to update the state of a parent, write a method that calls this.setState and pass it down as props to your child component\r\n this.state = this.getFreshState();\r\n // class methods must be bound in the constructor so they refer to `this` properly (again, a JavaScript / class thing, not a React specific thing)\r\n this.toggle = this.toggle.bind(this);\r\n this.refresh = this.refresh.bind(this);\r\n this.getFreshState = this.getFreshState.bind(this);\r\n }", "constructor() {\n\n // we use the super keyword and method to call the constructor of a parent class\n // this gives us access to the properties of the parent class. It MUST \n // be used BEFORE the 'this' keyword\n super();\n this.state = {\n header: \"Calculator\",\n display: '0',\n operator: '',\n temp: 0,\n resetDisplay: true\n }\n }", "constructor(props) {\n super(props);\n this.state = {\n a: 1,\n };\n\n console.log(\"constructor was called\");\n }", "constructor(props) {\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t}\n\t}", "constructor(props){\n super(props);\n this.state= {\n };\n }", "constructor(props) {\n super(props);\n this.state = { };\n }", "constructor(props) {\n super(props);\n\n this.state = {\n\n };\n }", "constructor(props) {\n super(props);\n // 2)\n this.state = {\n title: 'Pulp fiction in cinema.',\n body: 'some text'\n }\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n //Call the constrictor of Super class i.e The Component\n super(props);\n //maintain the state required for this component\n this.state = {};\n }", "constructor(props) {\n //Call the constrictor of Super class i.e The Component\n super(props);\n //maintain the state required for this component\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {\n };\n }", "constructor(props) {\n super(props);\n this.state = {\n };\n }", "constructor(props) {\n super(props);\n this.state = {\n };\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor(props) {\n super(props);\n this.state = {};\n }", "constructor (props) {\n\t\tsuper(props);\n\t\tthis.state = {};\n\t}", "constructor(props) {\n super(props);\n this.state = {\n\n }\n }", "constructor(props) {\n super(props);\n this.state = {}\n }", "constructor(props) {\n super(props)\n this.state = {}\n }", "constructor(props) {\n super(props)\n this.state = {}\n }", "constructor(props) {\n //Call the constrictor of Super class i.e The Component\n super(props);\n //maintain the state required for this component\n this.state = {}\n }", "constructor(props) {\n super(props);\n this.state = {\n name: \"Joe\",\n age: \"25\"\n }\n }", "constructor(props) {\n super(props);\n\n const state = this.state;\n }", "constructor(props) {\n super(props);\n this.state= {flag:0};\n }", "getInitialState() {\n return {\n\n }\n }", "constructor() {\n //gives us ability from the Component class to use state\n super();\n\n //use state to hold variables attached to instances of component\n this.state = {\n books: [],\n name: 'Joshua Eli Poliquin'\n }\n }", "constructor(){\n // it will help to make scope of this to App but not to componenet\n super();\n // set default state\n this.state = {\n txt: \"Hello world!\",\n no: 10\n }\n }", "_getInitialState() {\n return {};\n }", "constructor(props)\n {\n super(props); //always inst the super class\n\n\n this.state = {\n current: '0',\n previous: [],\n nextIsReset: false\n };\n }", "constructor(props){\n super(props);\n this.state = {}\n }", "constructor(props) { //functional components do not have state - only class based components do\n super(props); //comes from component. component has its own constructor function.\n\n this.state = { term: '' }; //state is a javascript object that exists on any class based component. each instance of a component has its own copy of state. we initialize the state by using this.state. term could be named something else if wished. this is the only time changing state happens this way (this.state = {}) use this.setState for all future state changes\n }", "constructor(props) {\n super(props);\n this.state = { ...props };\n }", "constructor(props){\n super(props)\n\n // 2 SET INITIAL STATE\n this.state = {\n title: 'LifeCycle'\n }\n }", "constructor(props) {\n super(props)\n \n this.state = {\n someThing:\"ssss\"\n }\n }", "constructor(props) {\n super(props)\n //this.state = propriedade herdada de Compponent, nao pode ser alterada diretamente\n //No react, nao podemos alterar propriedades diretamente, apenas evolui-la\n //predominacao de programacao funcional\n this.state = { value: props.initialValue }\n }", "constructor(props) {\n super(props)\n this.state = {\n }\n }", "constructor(props) {\n super(props);\n \n this.state = {\n };\n }", "constructor(props) {\n super(props);\n \n this.state = {\n };\n }", "constructor(props) {\n super(props);\n \n this.state = {\n };\n }", "constructor(){\n super();//call the super(), then start using the constructor\n \n this.state = {count: 0};\n\n /* Use arrow function to get rid of binding */\n /*\n this.increment = this.increment.bind(this);\n this.reset = this.reset.bind(this);\n */\n }", "constructor(props){\n\t\t//calling the parent method, Component\n\t\tsuper(props);\n\t\t//initialize by creating a new object and assign it to this.state. Record the property \"term\" on state\n\t\tthis.state = { term: 'Starting value' };\n\t}", "constructor(props) {\n super(props);\n\n this.state = { value: 0 }; // Will probably store value in state later when the design has been improved\n\n }", "constructor(props){\n super(props);\n \n this.state = {\n\n }\n\n }", "constructor(){\n super();\n this.state = {\n label: 'Button'\n }\n this.setInitialState();\n }", "constructor(props) {\n\t\t super(props)\n\t\t this.state = {\n\t\t\t nom: \"test3\",\n\t\t }\n\t }", "constructor() {\n // step 2, call your constructor\n super();\n this.state = {\n greeting: `Hello Sandbox`,\n bands: [\n \"Guster\",\n \"Guster\",\n \"Modest Mouse\",\n \"CCR\",\n \"Skynard\",\n \"Led Zepplin\"\n ]\n };\n }", "constructor(props) {\n super(props);\n\n console.log('Executing StateClassDemo Constructor');\n\n /*\n The \"state\" property on the component instance is a special property\n understood by React. The state of a Class-based Component is always\n stored on the component instance's \"state\" property.\n\n Data on the \"state\" property can be set one-time the Constructor\n Method, but all future changes to the \"state\" property are\n performed exclusively through the \"setState\" function shown below.\n */\n this.state = {\n counter: 0,\n };\n\n /*\n JavaScript uses a form of inheritance named Prototype Inheritance.\n The purpose of Prototype Inheritance is share functions with many\n objects. JavaScript classes are used to setup prototype inheritance\n with a super class sharing its functions with a subclass. The sharing\n is accomplished via heap-based prototype chain. Because JavaScript\n inheritance is a chain of objects on the heap, the inheritance is \n between live objects and not specifications.\n\n To know which object is invoking the function, JavaScript uses\n something called call-site this. Meaning the value of this within\n a function is determined by \"how\" the function is invoked, not\n where the function is defined. Normally, this works without issue.\n \n But for functions which are passed as callbacks, the context\n of the original object is lost when the function is invoked. To\n preserve this content (aka the value of \"this\"), a contextually\n bound version of the function is created and assigned to the\n instance.\n\n When using Functional Components with Hook-based State, none\n of this esoteric JavaScript knowledge and work arounds are\n needed.\n */\n this.incrementCounter = this.incrementCounter.bind(this);\n }", "constructor(props){\n //it is the first and the only function called automatically, whenever a new instance was created\n super(props);\n this.state = { term: ''}; //initialize the state by create a new object, and assign it to this.state.\n }", "constructor() {\n super(); // it fire React.Component's constructor\n this.state = {\n count: 0,\n }; // state is empty object\n }", "constructor(props) {\n super(props);\n \n \n \n //creation of an initial state, a json object\n this.state = {\n }; \n }", "constructor(props) {\n\t\t// rmb we extend React.Component; Component has its own constructor function\n\t\t// when we define a method that is already defined on the parent class which is Component, we can call that parent method on the parent class by calling super\n\t\t// thus super is calling the parent method\n\t\tsuper(props);\n\t\t// whenever we use state, we initialize it by creating a new object and assigning it to this.state\n\t\t// the object we pass will also contain properties that we want to record on the state\n\t\t// eg, below we want to record the property 'term' on state; this is the property that we want to record our change on for the search bar\n\t\t// what we want is that as the user starts typing on the input, we want to update this.state.term to not be an empty string but to be the value of the input\n\t\t// this.state = { term: ''}\n\n\t\t// each instance of a class based component has its own copy of states\n\t\tthis.state = { term: \"\" };\n\t}", "constructor(props) {\r\n // remember to put the super statement at the start of the constructor\r\n super(props);\r\n // bind the change event\r\n // why: \"The callback is made in a different context. You need to bind to this in order to have access inside the callback\"\r\n // as per this post: https://stackoverflow.com/a/31045750/4672179\r\n // this.handleclick = this.handleclick.bind(this);\r\n // but then, this blog says using arrow functions negates the need for the above line\r\n // https://medium.com/quick-code/react-quick-tip-use-class-properties-and-arrow-functions-to-avoid-binding-this-to-methods-29628aca2e25\r\n // init state inside the constructor\r\n this.state = {\r\n name: ''\r\n }\r\n }", "constructor(props){ \n // init stuff \n super(props); // <- 5.4 get parent method \n // 6.1 only inside of the constructor function do we change our state like this by just saying like this this.state = {term:'xxx'}\n // \"this.state\" 係 syntax\n this.state = {term:''}; //<- 5.5 when user update search input, 'term' property we want to update\n // state exists on class based components, 'this.state' <- 送嘅\n\n }", "constructor(props) {\n\t\t// rmb we extend React.Component; Component has its own constructor function\n\t\t// when we define a method that is already defined on the parent class which is Component, we can call that parent method on the parent class by calling super\n\t\t// thus super is calling the parent method\n\t\tsuper(props)\n\t\t// whenever we use state, we initialize it by creating a new object and assigning it to this.state\n\t\t// the object we pass will also contain properties that we want to record on the state\n\t\t// eg, below we want to record the property 'term' on state; this is the property that we want to record our change on for the search bar\n\t\t// what we want is that as the user starts typing on the input, we want to update this.state.term to not be an empty string but to be the value of the input\n\t\tthis.state = { term: ''}\n\t}\n\t.\n\t.\n\t.", "constructor(props) {\n // The 'constructor' function that all js classes have,\n // is the first and only function called automatically,\n // whenever a new instance of the class is created.\n // And is reserved for initializing variables, state etc. for our class\n\n super(props);\n // with 'super' we call the parent method defined on the parent class\n\n //Initialize state:\n this.state = { term: '' };\n // whenever the user updates the search input, 'term' is the property that will record the change on\n // so we will update this.state.term to be the value of the input\n\n // !! IMPORTANT\n // this is the ONLY PLACE IN OUR APP where we will define the state value in this way, with '=' operator\n // when we will UPDATE the state, we will use 'setState' method !\n }", "constructor(props){\n\t\tsuper(props);\n\t\tthis.state = {\n\t\t\tlng:10,\n\t\t\tlat: 80,\n\t\t\tzoom: 4\n\t\t}\n\t}", "constructor (props) {\n super(props)\n this.state = {\n text: 'Hello World'\n }\n }", "constructor (props) {\n super(props)\n this.state = {\n text: 'Hello World'\n }\n }", "constructor (props) {\n super(props)\n this.state = {\n text: 'Hello World'\n }\n }", "constructor() {\n super(); // Gives context for \"this\" within component.\n this.state = { \n red: 0,\n green: 0,\n blue: 0,\n myTxt: \"--\"\n };\n this.update = this.update.bind(this);\n }", "constructor(props){\n super(props); // Passing the props parameter to the constructor\n \n //Setting up the initial state of the component by this.state object because states are immutable .\n this.state = {\n name:\"Rachit\",\n age:28,\n date : new Date()\n };\n }", "constructor(props) {\n\t\t// calling parent method via super\n\t\tsuper(props);\n\t\t// initialise state by creating object\n\t\tthis.state = { term: 'Messi' };\n\t}", "getInitialState() {\n return {\n }\n }", "constructor() {\n // gives us ability from the Component class to use state\n super();\n\n // use state to hold variables attached to indstances of component\n this.state = {\n books: [],\n name: 'Mayur Bhatia'\n }\n }", "constructor(){\n super();\n this.state = {\n name : \"John\",\n input : \"\"\n }\n }", "constructor(props) {\n super(props);\n this.state = ({\n \n })\n }", "function getInitialState ()\n {\n return {};\n }", "function getInitialState ()\n {\n return {};\n }", "constructor(props) {\n super(props);\n //this is the only time you can directly set things on this object\n this.state = {\n word: 'World'\n };\n }", "function State() { }", "constructor(){\n // ES6 class constructors MUST call super if they are subclasses.\n super();\n\n this.state = {\n sidebarMenu: [\n { name: 'Terms Of Use', url: 'legal/terms-of-use' },\n { name: 'Trademark Notice', url: 'legal/trademark-notice' },\n { name: 'Cookies Policy', url: 'legal/cookies-policy' }\n ]\n };\n }", "constructor(props) {\n // The super keyword is used to access and call functions on an object's parent\n // When used in a constructor,\n // the super keyword appears alone\n // and must be used before the this keyword is used\n super(props);\n this.state = {\n books: []\n }\n }", "constructor(props){\n super(props);\n this.state={\n number:0\n };\n }", "constructor(props) {\n super(props);\n this.state = {\n 'valid': true,\n 'value': props.initialValue,\n };\n\n this.onChange = this.onChange.bind(this);\n }", "getInitialState() {\n return {\n }\n }", "constructor(props) {\n super(props);\n\n // Warning: getInitialState() is only supported for classes created using React.createClass.\n // getInitialState() executes exactly once during the lifecycle of the component\n // and sets up the initial state of the component.\n // When the state updates, the component re-renders itself.\n // @see https://facebook.github.io/react/docs/tutorial.html#reactive-state\n // getInitialState() {\n // return {data: []};\n // }\n this.state = getToolState();\n }", "constructor(props)\n {\n super(props);\n this.state={\n status: 'open'\n }\n }", "constructor(props) { //Genero al constructor para inicializar propiedas y variables\n super(props); //Declaramos super para adaptar las propiedades en React\n this.state = { //Declaramos los estados de las propiedades\n prop1: 0,\n prop2: 0,\n prop3: 0\n }; \n }" ]
[ "0.8099104", "0.78394103", "0.78181684", "0.7782156", "0.77612954", "0.7757197", "0.7735324", "0.7635433", "0.7609939", "0.7600566", "0.7592889", "0.75672233", "0.74645805", "0.7440463", "0.74289197", "0.7412397", "0.73982376", "0.73736376", "0.7369459", "0.73577625", "0.73521864", "0.73511326", "0.732352", "0.7320561", "0.73142165", "0.73142165", "0.73142165", "0.73142165", "0.73142165", "0.7312119", "0.7312119", "0.73091346", "0.73091346", "0.73091346", "0.7296666", "0.7296666", "0.7296666", "0.7296666", "0.7295991", "0.7288162", "0.7269937", "0.7263688", "0.7263688", "0.7252594", "0.72525835", "0.72509295", "0.722891", "0.72217107", "0.7220977", "0.7214132", "0.72100806", "0.72062707", "0.7202747", "0.7197883", "0.71743566", "0.7170414", "0.715494", "0.7154087", "0.7149285", "0.7140774", "0.7140774", "0.7140774", "0.71401155", "0.7139093", "0.7138838", "0.71196336", "0.71155447", "0.70947045", "0.70880926", "0.70797014", "0.7076965", "0.70699143", "0.7064354", "0.7042564", "0.703163", "0.702676", "0.7026644", "0.70139605", "0.7009174", "0.7009102", "0.7009102", "0.7009102", "0.70034933", "0.70021343", "0.69949955", "0.69878274", "0.6983436", "0.69804204", "0.6964109", "0.6958168", "0.6958168", "0.69522494", "0.6941779", "0.6939293", "0.69385445", "0.69348687", "0.6930963", "0.6920919", "0.6919054", "0.6912658", "0.6912568" ]
0.0
-1
resize clock when div size changed
resizeClock() { //const th = this; //let elm = ReactDOM.findDOMNode(th); //let size = Math.min(window.width, window.height); //console.log("resizeClock: " + size) /*th.setState({ cw: size, ch: size })*/ }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateClockSizes() {\n EventFactory.events.forEach(function(e){EventFactory.setSize(e, window.innerWidth/(isMobile?2.5:13))});\n \n EventFactory.setSize(MainEvent, (isMobile?0.95:.6)*windowHW());\n}", "function repaintClock() {\r\n\t\t\t\tif (selectionMode == 'HOUR') {\r\n\t\t\t\t\trepaintClockHourCanvas();\r\n\t\t\t\t} else {\r\n\t\t\t\t\trepaintClockMinuteCanvas();\r\n\t\t\t\t}\r\n\t\t\t}", "function repaintClock() {\n\t\t\t\tif (selectionMode == 'HOUR') {\n\t\t\t\t\trepaintClockHourCanvas();\n\t\t\t\t} else {\n\t\t\t\t\trepaintClockMinuteCanvas();\n\t\t\t\t}\n\t\t\t}", "function setupClock_3() {\n var objClockOptions;\n\n objClockOptions =\n {\n size: 200,\n\n centerColor: '#21344b',\n centerRadius: 5,\n centerStrokeWidth: 3,\n centerStrokeOpacity: 0.8,\n\n hourLength: 40, // the length of the image\n hourColor: '#FF0000',\n hourStrokeWidth: 8,\n hourStrokeOpacity: 0.8,\n\n minuteColor: '#ffff00',\n minuteLength: 60, // the length of the image\n minuteStrokeWidth: 5,\n minuteStrokeOpacity: 0.8,\n\n secondLength: 75, // the length of the image\n secondColor: '#d0d7e1',\n secondStrokeWidth: 2,\n secondStrokeOpacity: 0.9,\n\n speed: 400,\n allowMinuteFullRotation: false,\n hourDraggable: true,\n minuteDraggable: true,\n\n onHourDragStart: onHourDragStart_3,\n onHourDragMove: onHourDragMove_3,\n onHourDragEnd: onHourDragEnd_3,\n onMinuteDragStart: onMinuteDragStart_3,\n onMinuteDragMove: onMinuteDragMove_3,\n onMinuteDragEnd: onMinuteDragEnd_3\n };\n\n\n objClock_4 = new Clock('CLOCK_HOLDER_4', objClockOptions);\n objClockOptions.minuteDragSnap = 1; // additional option for Clock 5\n\n objClock_5 = new Clock('CLOCK_HOLDER_5', objClockOptions);\n objClockOptions.minuteDragSnap = 15; // additional option for Clock 6\n\n objClock_6 = new Clock('CLOCK_HOLDER_6', objClockOptions);\n\n $('#CLOCK_HOUR_4, #CLOCK_MINUTE_4').bind('change', function () {\n objClock_4.setTime($(\"#CLOCK_HOUR_4\").val(), $(\"#CLOCK_MINUTE_4\").val());\n $('#CLOCK_EVENT_4').html('Clock time changed using pulldown menu');\n });\n\n $('#CLOCK_HOUR_5, #CLOCK_MINUTE_5').bind('change', function () {\n objClock_5.setTime($(\"#CLOCK_HOUR_5\").val(), $(\"#CLOCK_MINUTE_5\").val());\n $('#CLOCK_EVENT_5').html('Clock time changed using pulldown menu');\n });\n\n $('#CLOCK_HOUR_6, #CLOCK_MINUTE_6').bind('change', function () {\n objClock_6.setTime($(\"#CLOCK_HOUR_6\").val(), $(\"#CLOCK_MINUTE_6\").val());\n $('#CLOCK_EVENT_6').html('Clock time changed using pulldown menu');\n });\n\n\n // reset the pulldown menus, in case of a browser refresh\n $('#CLOCK_HOUR_4').val(objClock_4.hour.value);\n $('#CLOCK_MINUTE_4').val(objClock_4.minute.value);\n\n $('#CLOCK_HOUR_5').val(objClock_5.hour.value);\n $('#CLOCK_MINUTE_5').val(objClock_5.minute.value);\n\n $('#CLOCK_HOUR_6').val(objClock_6.hour.value);\n $('#CLOCK_MINUTE_6').val(objClock_6.minute.value);\n}", "function changesize(h,sq,intv,tm) {\n chartx.chart.height = h ;\n standWD(sq) ;\n initChart(sq,intv,tm) ;\n\n // setTimeout( chart.setSize(null,h) ,500);\n}", "function resize() {\n radiusOuter = document.getElementById('timer-container').offsetWidth * 0.45;\n radiusInner = document.getElementById('timer-container').offsetWidth * 0.38;\n\n circumferenceOuter = radiusOuter * 2 * Math.PI;\n circumferenceInner = radiusInner * 2 * Math.PI;\n\n document.getElementById('circle-outer').setAttribute('r', radiusOuter + '');\n document.getElementById('circle-inner').setAttribute('r', radiusInner + '');\n\n document.getElementById('svg-outer').style.strokeDasharray = '' + circumferenceOuter;\n document.getElementById('svg-outer').style.strokeDashoffset = '' + circumferenceOuter;\n\n document.getElementById('svg-inner').style.strokeDasharray = '' + circumferenceInner;\n document.getElementById('svg-inner').style.strokeDashoffset = '' + circumferenceInner / 2;\n startFlag = true;\n }", "onResize() {\n // Assume resize in both directions.\n this.readjustView(true, true, this.scrollMinute);\n }", "async resized() {\n this.turnOff();\n await this.delay(25);\n this.moveToCurrent();\n await this.delay(25);\n this.turnOn();\n }", "function svgClock() {\n\t\t\t// Get current time.. again\n\t\t\tvar now = new Date();\n\t\t\tvar h, m, s;\n\t\t\th = 30 * ((now.getHours() % 12) + now.getMinutes() / 60);\n\t\t\tm = 6 * now.getMinutes();\n\t\t\ts = 6 * now.getSeconds();\n\n\t\t\t// Find pointers of the clock, rotate\n\t\t\tdocument.getElementById('h_pointer').setAttribute('transform', 'rotate(' + h + ', 50, 50)');\n\t\t\tdocument.getElementById('m_pointer').setAttribute('transform', 'rotate(' + m + ', 50, 50)'); \n\t\t\tdocument.getElementById('s_pointer').setAttribute('transform', 'rotate(' + s + ', 50, 50)');\n\t\t\t\n\t\t\t// Loop every second\n\t\t\tsetTimeout(svgClock, 1000);\n\t\t}", "function sizeChanged () {\n board = new Board(sizeSlider.value())\n board.initView(windowWidth / 2, windowHeight / 2, CENTER_BOARD_SIZE)\n}", "function resized() {\r\n\tclearInterval(renderer);\r\n\tmain();\r\n}", "function resizeCanvas()\r\n{\r\n\tvar canvas = getCanvas();\r\n\tcanvas.width = window.innerWidth;\r\n canvas.height = window.innerHeight;\r\n\t\r\n\tpaintClock();\r\n}", "function updateClock(x)\n {\n setClock(x);\n dimOutClock(x.length, 8, 20);\n }", "onCustomWidgetResize(width, height){\n this.redraw();\n }", "function _resize(size){\n var sz = (size < 100) ? sz = 100 : sz = size;\n placeholder.each(function(){\n $(this).find('div.instrument').css({height : sz, width : sz});\n });\n }", "function initClock() {\n if (clock.children.length > 0)\n return;\n\n // ToDo: Calculate this somehow\n var clockHours = {\n '00': { left: '87px', top: '7px' },\n '1': { left: '114px', top: '40.2346px', bigger: true },\n '2': { left: '133.765px', top: '60px', bigger: true },\n '3': { left: '141px', top: '87px', bigger: true },\n '4': { left: '133.765px', top: '114px', bigger: true },\n '5': { left: '114px', top: '133.765px', bigger: true },\n '6': { left: '87px', top: '141px', bigger: true },\n '7': { left: '60px', top: '133.765px', bigger: true },\n '8': { left: '40.2346px', top: '114px', bigger: true },\n '9': { left: '33px', top: '87px', bigger: true },\n '10': { left: '40.2346px', top: '60px', bigger: true },\n '11': { left: '60px', top: '40.2346px', bigger: true },\n '12': { left: '87px', top: '33px', bigger: true },\n '13': { left: '127px', top: '17.718px'},\n '14': { left: '156.282px', top: '47px'},\n '15': { left: '167px', top: '87px'},\n '16': { left: '156.282px', top: '127px'},\n '17': { left: '127px', top: '156.282px'},\n '18': { left: '87px', top: '167px'},\n '19': { left: '47px', top: '156.282px'},\n '20': { left: '17.718px', top: '127px'},\n '21': { left: '7px', top: '87px'},\n '22': { left: '17.718px', top: '47px'},\n '23': { left: '47px', top: '17.718px'}\n };\n\n // ToDo: Calculate this somehow\n var clockMinutes = {\n '00': { left: '87px', top: '7px', bigger: true },\n '05': { left: '127px', top: '17.718px', bigger: true },\n '10': { left: '156.282px', top: '47px', bigger: true },\n '15': { left: '167px', top: '87px', bigger: true },\n '20': { left: '156.282px', top: '127px', bigger: true },\n '25': { left: '127px', top: '156.282px', bigger: true },\n '30': { left: '87px', top: '167px', bigger: true },\n '35': { left: '47px', top: '156.282px', bigger: true },\n '40': { left: '17.718px', top: '127px', bigger: true },\n '45': { left: '7px', top: '87px', bigger: true },\n '50': { left: '17.718px', top: '47px', bigger: true },\n '55': { left: '47px', top: '17.718px', bigger: true }\n };\n\n\n // Create hours container\n hours = document.createElement('div');\n hours.setAttribute('style', '');\n hours.className = 'datipi-circle-selector datipi-hours';\n fillTickElements(hours, clockHours, onHourTickSelect);\n\n // Create minutes container\n minutes = document.createElement('div');\n minutes.setAttribute('style', '');\n minutes.className = 'datipi-minutes datipi-circle-hidden';\n fillTickElements(minutes, clockMinutes, onMinutesTickSelect);\n\n // Clear clock and append child elements\n clock.innerHTML = '';\n clock.appendChild(hours);\n clock.appendChild(minutes);\n }", "render() {\n const me = this,\n client = me.client;\n\n me.resize && me.resize.destroy();\n\n me.resize = me.createResizeHelper();\n\n if (me.showTooltip) {\n me.clockTemplate = new ClockTemplate({\n timeAxisViewModel: client.timeAxisViewModel\n });\n }\n }", "function swap_Size() {\r\n setInterval(next_Size, 1000);\r\n}", "function handleResize() {\n container.style.width = (container.offsetHeight / 11) * 14 + \"px\";\n updateDisplay()\n}", "function createTimeObject(topPosition, leftPosition, divId, objectStyle, objectTime, objectWidth, objectHeight, objectFont, secondChooser) {\n var today = new Date();\n var hr = today.getHours();\n var min = today.getMinutes();\n var sec = today.getSeconds();\n //Add a zero in front of numbers<10\n hr = checkTime(hr);\n min = checkTime(min);\n sec = checkTime(sec);\n\n //When the function is recalled just update the innerHTML and not the whole element.\n if(document.getElementsByClassName('clock')[0]) {\n var clockDiv = document.getElementsByClassName('clock')[0];\n var showSeconds = clockDiv.getAttribute('seconds');\n if (showSeconds == 'true') { //depending on the user's choice do or don't show the seconds\n clockDiv.innerHTML = hr + \":\" + min + \":\" + sec ;\n }\n else clockDiv.innerHTML = hr + \":\" + min ;\n\n //console.log(\"updated\");\n\n }\n //goes into this else-statement the first time the element is created.\n else {\n var clockDiv = document.createElement('div');\n clockDiv.style.color = 'white';\n clockDiv.setAttribute('id', divId);\n clockDiv.setAttribute('class', 'icon-middle sunny resize-drag clock');\n\n clockDiv.setAttribute('seconds', secondChooser);\n\n if (secondChooser == 'true') { //depending on the user's choice do or don't show the seconds\n clockDiv.innerHTML = hr + \":\" + min + \":\" + sec ;\n }\n else clockDiv.innerHTML = hr + \":\" + min ;\n\n //clockDiv.innerHTML = hr + \":\" + min + \":\" + sec;\n\n var style = window.getComputedStyle(clockDiv);\n clockDiv.style.top = topPosition;\n clockDiv.style.left = leftPosition;\n clockDiv.setAttribute('top', topPosition);\n clockDiv.setAttribute('left', leftPosition);\n\n clockDiv.setAttribute('object-style', objectStyle);\n\n if (objectFont !== \"noFont\") {\n fontFamilies2.push(objectFont); //add the font if there is a selected font\n\n clockDiv.setAttribute('object-font', objectFont);\n\n clockDiv.style.fontFamily = objectFont;\n }\n else {\n clockDiv.style.fontFamily = 'Julius Sans One';\n clockDiv.setAttribute('object-font', \"Julius Sans One\");\n }\n\n if (objectWidth == \"startWidth\" && objectHeight == \"startHeight\") {\n // console.log(\"startWidthHeight: \" + style.getPropertyValue('width') + \" \" + style.getPropertyValue('height'));\n clockDiv.style.width = \"100px\";\n clockDiv.style.height = \"50px\";\n clockDiv.setAttribute('object-width', '100px');\n clockDiv.setAttribute('object-height', '50px');\n }\n else {\n clockDiv.style.width = objectWidth;\n clockDiv.style.height = objectHeight;\n // console.log(\"objectWidthHeight \" + objectWidth + \" \" + objectHeight);\n clockDiv.setAttribute('object-width', objectWidth);\n clockDiv.setAttribute('object-height', objectHeight);\n }\n\n var font = parseFloat(clockDiv.getAttribute('object-height'));\n clockDiv.style.fontSize = font / 3 + 'px';\n\n document.getElementsByClassName('middle-side')[0].appendChild(clockDiv);\n\n var functionCaller = arguments.callee.caller.name;\n if (functionCaller == \"drop\") {\n console.log(\"if\");\n addToUndoArray(clockDiv.id, \"addObject\", topPosition, leftPosition, clockDiv.getAttribute('object-style'), objectTime, clockDiv.getAttribute('object-width'), clockDiv.getAttribute('object-height'),clockDiv.getAttribute('object-font'), \"noMessage\");\n }\n\n // weatherStyleToCss(divId, topPosition, leftPosition, clockDiv.getAttribute('object-style'), \"no-time\", clockDiv.getAttribute('object-width'), clockDiv.getAttribute('object-height'),clockDiv.getAttribute('object-font'));\n\n }\n\n clockTimer = setTimeout(function() {createTimeObject(clockDiv.getAttribute('top'),clockDiv.getAttribute('left'),clockDiv.id,clockDiv.getAttribute('object-style'),\"no-time\",clockDiv.getAttribute('object-width'),clockDiv.getAttribute('object-height'),clockDiv.getAttribute('object-font'),clockDiv.getAttribute('seconds')) }, 1000);\n\n}", "render() {\n const me = this;\n me.resize && me.resize.destroy();\n me.resize = me.createResizeHelper();\n\n if (me.showTooltip) {\n me.clockTemplate = new ClockTemplate({\n scheduler: me.client\n });\n }\n }", "function refreshClock() {\n $('#timer').html(CustomTime.getTime);\n}", "function displayResize(evt) {\n var available_height = window.innerHeight - 100,\n available_width = window.innerWidth;\n var tmp_square_height = available_height >> 3,\n tmp_square_width = available_width / 11.5;\n var tmp = tmp_square_height > tmp_square_width ?\n tmp_square_width : tmp_square_height;\n var tmp_square = tmp < 30 ? 30 : tmp;\n game.render_elements(tmp_square, tmp_square);\n var pieces = game.elements.pieces;\n for (var y = 9; y > 1; y--){\n for(var x = 1; x < 9; x++){\n var i = y * 10 + x;\n pieces[i].height = tmp_square;\n pieces[i].width = tmp_square;\n }\n }\n}", "function ClockAnimation(){\n // Default potiton of animation of the clockanimation.\n // Pos X\n var animationPosX = 300;\n \n // Pos Y\n var animationPosY = 500;\n\n // Size and propotion in animation\n var sizeWidthMinut = 300;\n var defaultArcSize = 50;\n\n // The edge of the animation\n var animationsixeLeft = animationPosX - sizeWidthMinut / 2;\n var animationsixeRight = animationPosX + sizeWidthMinut / 2;\n\n // Getting time \n var date10basehoure = get10BaseTimeHoure();\n var date10baseminute = get10BaseTimeMinute();\n\n var animationPosXMinut = animationPosX;\n var sizeWidthMinut = 300;\n var animationPosYMinut = animationPosY + 200;\n\n crateHourBox(date10basehoure, animationPosX, animationPosY, defaultArcSize, \"Hour\", sizeWidthMinut );\n crateMinutBox(date10baseminute, animationPosXMinut , animationPosYMinut , defaultArcSize, \"Minute\", sizeWidthMinut) ;\n}", "function resizeDiv() {\r\n\t\t$this = $['mapsettings'].element;\r\n\t\tvar divsize = \"width:\" + $this.parent().get(0).clientWidth + \"px; height: \" + $(window).height() + 'px;';\r\n\t $this.attr('style', divsize);\t\t\r\n\t\tvar divsize = \"width:\" + ($this.parent().get(0).clientWidth - $this.get(0).offsetLeft) + \"px; height: \" + ($(window).height()-$this.get(0).offsetTop) + 'px;';\r\n\t $this.attr('style', divsize);\t\t\r\n\t\tloadImages();\r\n\t}", "_onResize() {\n this.refresh();\n }", "function initClockApp()\r\n{\r\n\t// Register our callback on window resize event.\r\n\twindow.addEventListener('resize', resizeCanvas, false);\r\n\r\n\t// Resize 2d canvas to fill the whole window.\r\n\tresizeCanvas();\r\n\r\n\t// Paint the clock image for first time.\r\n paintClock();\r\n\r\n\t// Repaint the clock image every second.\r\n\tsetInterval(paintClock, 1000 /*millisec*/);\r\n}", "function updateClock(){\n let now = new Date(); //pegando horário atual\n let hour = now.getHours(); //pegando hora atual\n let minute = now.getMinutes(); //pegando minuto atual\n let second = now.getSeconds(); //pegando segundo atual\n\n digitalElemtent.innerHTML = `${fixZero(hour)}:${fixZero(minute)}:${fixZero(second)}`; //colocando a hora atual no relógio digital\n //ponteiro dos segundos\n let sDeg = ((360/60) * second) - 90; //identificando a posição de cada segundo. o 90 é para ajustar o ponteiro para iniciar as 12hrs. sem ele o início fica ás 3 horas \n sElement.style.transform = `rotate(${sDeg}deg)`; //colocando uma propriedade CSS através do JS no \"sElement\"\n //ponteiro dos minutos\n let mDeg = ((360/60) * minute) - 90;\n mElement.style.transform = `rotate(${mDeg}deg)`;\n //ponteiro das horas\n let hDeg = ((360/12) * hour) - 90;\n hElement.style.transform = `rotate(${hDeg}deg)`;\n}", "initialize_clock() {\n\t\tthis.$clock.html( theme_utils.get_current_localized_time() );\n\n\t\tsetInterval( () => _self.$clock.html( theme_utils.get_current_localized_time() ), 60000 );\n\t}", "function refreshClock() {\n $now = new Date($localTime.format('YYYY'), $localTime.format('M') - 1, $localTime.format('DD'), $localTime.format('hh'), $localTime.format('mm'), $localTime.format('ss'));\n $diff = Math.round(Math.abs($now.getTime() - $startTime.getTime()) / 1000);\n $degS = ($startS + $diff) / 60 * 360;\n $degM = ($startM + $diff) / 3600 * 360;\n $degH = ($startH + $diff) / 43200 * 360;\n\n $this.find('.hour').css(rotate($degH));\n $this.find('.minute').css(rotate($degM));\n $this.find('.second').css(rotate($degS));\n\n setTimeout(refreshClock, 1000);\n }", "onTimeChanged () {\n this.view.renderTimeAndDate();\n }", "function initializeTimelineDuration() {\n var totalHours = findTotalHours();\n if (totalHours > 48) {\n TIMELINE_HOURS = totalHours;\n TOTAL_HOUR_PIXELS = TIMELINE_HOURS * HOUR_WIDTH;\n SVG_WIDTH = TIMELINE_HOURS * 100 + 50;\n XTicks = TIMELINE_HOURS * 2;\n redrawTimeline();\n }\n}", "function update_clock (current_time_panel, current_time) {\n\tvar min = Math.floor((current_time/60) % 60);\n\tvar sec = Math.floor(current_time % 60);\n\n\tif (sec <= 9) {\n\t\tvar sec = \"0\" + sec;\n\t}\n\n\tcurrent_time_panel.innerHTML = min + \":\" + sec;\n}", "function resize(e) {\n window.clearTimeout(resizetimer);\n resizetimer = setTimeout(function() {\n }, 60);\n }", "function onWindowResize() {\n updateSizes();\n }", "function drawClock()\n{\n\tclockCtx.clearRect(0,0,clockCWidth, clockCHeight);\n\tdrawClockOutline();\n\tdrawNumbers();\n\tdrawHands();\n\tsetTimeout(drawClock, 20);\n}", "function clock() {\n\t\tconst d = new Date();\n\t\tlet hour = d.getHours();\n\t\tlet min = d.getMinutes();\n\t\tlet sec = d.getSeconds();\n\t\tif(hour > 12) {\n\t\t\thour-=12;\t\t\t\n\t\t}\n\t\tif(min < 10) {\n\t\t\tmin=\"0\"+min;\n\t\t}\n\t\tif(sec < 10) {\n\t\t\tsec=\"0\"+sec;\n\t\t}\n\t\t$(\"#clock-time\").html(hour+\":\"+min+\":\"+sec);\t\t\n\t\tsetTimeout(clock, 250);\n\t}", "function updateClock() {\n // Destructuring hour, minute and second from resultant array\n let [hour, minute, second] = new Date()\n .toLocaleTimeString('en-US')\n .split(/:| /);\n // Convert hour in 24-hour format to 12-hour format\n hour = hour > 12 ? hour - 12 : hour;\n\n // Calculate the rotation value based on the current time\n const secondHandRotation = second * 6 + 'deg';\n const secondRatio = second / 60;\n const minuteHandRotation = (secondRatio + parseInt(minute)) * 6 + 'deg';\n const minuteRatio = minute / 60;\n const hourHandRotation = (minuteRatio + parseInt(hour)) * 30 + 'deg';\n\n // Perform changes in the DOM\n hourHand.style.setProperty('--rotation', hourHandRotation);\n minuteHand.style.setProperty('--rotation', minuteHandRotation);\n secondHand.style.setProperty('--rotation', secondHandRotation);\n}", "handleResize() {\n this.refresh();\n }", "function crateMinutBox(date10baseminute, xpos, ypos, size, text, sizewidth){\n createBorder(xpos, ypos, size, text);\n\n var sizeWidthMinut = 300;\n var boxSixeMinute = sizeWidthMinut / 100;\n\n var j = 0;\n for (i = 0; i < date10baseminute; i++) {\n j++;\n drawHoureBoxes(xpos - (sizewidth / 2) + (i * boxSixeMinute) + (j * 1), ypos, boxSixeMinute, size * 2);\n }\n}", "function updateContainers() {\n\n\t\tvar width = editor.duration * scale;\n\n\t\telements.setWidth( width + 'px' );\n\t\t// curves.setWidth( width + 'px' );\n\n\t}", "function bindTextClockEvent() {\n var parisTimeZone = 1;\n if (isBSTinEffect())\n parisTimeZone = 2;\n $('#paris_time').textClock(parisTimeZone);\n $('#shanghai_time').textClock(8);\n setInterval(function () {\n $('#paris_time').textClock(parisTimeZone);\n $('#shanghai_time').textClock(8);\n }, 1000 * 30);\n}", "function resize() {\n getNewSize();\n rmPaint();\n}", "function enableClock() {\n\t$(\".clock\").css(\"visibility\", \"visible\");\n\tupdateTime();\n\twindow.setInterval(updateTime, 1000);\n}", "changeSizeRond(val) {\r\n this.cercle.style.width = val + \"px\";\r\n this.cercle.style.height = val + \"px\";\r\n}", "function updateTime(){\n setTimeContent(\"timer\");\n}", "function resizeDiv() {\n\tconst displayStyles = document.getElementById(\"outer_container\");\n\n\t// Changing Div Element\n\tdisplayStyles.style.transition = \"1.25s\";\n\tdisplayStyles.style.color = \"#fff\";\n\tdisplayStyles.style.backgroundColor = \"#ff0055\";\n\tdisplayStyles.style.padding = \"1.5rem\";\n}", "function windowResized() {\n\n getWrapperWidth();\n resizeCanvas(wrapperWide, wrapperWide);\n\n widthVar = (width - 40) / 100;\n drawArea = (width - 40);\n\n switchBox();\n}", "function resizedw(){\n\t\n}", "function setDivSize() {\n\t\tvar wsize = getWindowSize();\n\t\tvar winh = wsize[0] - headerH - 80;\n\t\tvar winw = wsize[1] - 110;\n\t\t$('#controls').css('height','80').css('width',winw);\n\t\tfor (var i=1; i<=maxGraphs; i++ ) {\n\t\t\t$('#graphdiv'+i).css('height','240px').css('width',winw);\n\t\t\t$('#chart'+i).css('height','240px').css('width',winw);\n\t\t}\n\t}", "function displayTime() {\n\t\t// Get the current time.\n\t var now = new Date();\n\t var h = now.getHours() > 12 ? now.getHours() % 12 : now.getHours();\n\t var m = now.getMinutes();\n\t var s = now.getSeconds();\n\n\t // Create a formatted string for the time.\n\t var timeString = (h < 10 ? \"\" : \"\") + now.toLocaleTimeString();\n\n\t // Set the time label's value to the time string.\n\t document.getElementById(\"current-time\").innerHTML = timeString;\n\t\t\n\t\t\n\t\t// Draw the clock using SVG\n\t\tfunction svgClock() {\n\t\t\t// Get current time.. again\n\t\t\tvar now = new Date();\n\t\t\tvar h, m, s;\n\t\t\th = 30 * ((now.getHours() % 12) + now.getMinutes() / 60);\n\t\t\tm = 6 * now.getMinutes();\n\t\t\ts = 6 * now.getSeconds();\n\n\t\t\t// Find pointers of the clock, rotate\n\t\t\tdocument.getElementById('h_pointer').setAttribute('transform', 'rotate(' + h + ', 50, 50)');\n\t\t\tdocument.getElementById('m_pointer').setAttribute('transform', 'rotate(' + m + ', 50, 50)'); \n\t\t\tdocument.getElementById('s_pointer').setAttribute('transform', 'rotate(' + s + ', 50, 50)');\n\t\t\t\n\t\t\t// Loop every second\n\t\t\tsetTimeout(svgClock, 1000);\n\t\t}\n\t svgClock();\n\t}", "function runTheClock(){\n \n //this segment (2nd block) is added to keep sec hand animation but we no longer rely on DATE query to keep real time but on the browser to do the math. \n //we could place the first block here insted to keep a more accurate clock w/o animation. Dependent on DATE query.\n //increment in degrees\n \n //#####seconds hand#####\n // multiply times 10 for non sweeping seconds hand option.\n \n secPosition = (secPosition+0.6);\n minPosition = minPosition+(6/600);\n hrPosition = hrPosition+(3/3600);\n \n //apply as degrees in inline style\n //transform:rotate() is used to move hands in a circular path\n HOURHAND.style.transform = \"rotate(\" + hrPosition + \"deg)\";\n MINUTEHAND.style.transform = \"rotate(\" + minPosition + \"deg)\";\n SECONDHAND.style.transform = \"rotate(\" + secPosition + \"deg)\";\n \n //if we placed second block here. time would be a sec behind. We cold add 1 sec to secPosition definition but it is not a good solution. \n \n \n}", "function drawTimeSlide() {\n let bgCtx = sliderBGCanvas.getContext(\"2d\");\n let handleCtx = sliderHandleCanvas.getContext(\"2d\");\n\n sliderBGCanvas.width = timeSlider.clientWidth*window.devicePixelRatio;\n sliderBGCanvas.height = timeSlider.clientHeight*window.devicePixelRatio;\n\n sliderHandleCanvas.width = 20*window.devicePixelRatio;\n sliderHandleCanvas.height = 20*window.devicePixelRatio;\n\n bgCtx.setTransform(window.devicePixelRatio, 0, 0, window.devicePixelRatio, 0, 0);\n handleCtx.setTransform(window.devicePixelRatio, 0, 0, window.devicePixelRatio, 0, 0);\n\n let gridWidth = timeSlider.clientWidth/(83+4);\n\n bgCtx.clearRect(0,0,sliderBGCanvas.width,sliderBGCanvas.height);\n handleCtx.clearRect(0,0,sliderHandleCanvas.width,sliderHandleCanvas.height);\n\n bgCtx.fillStyle = \"#FFFFFF\";\n if (currentlyMax)\n bgCtx.fillStyle = \"#777777\";\n else\n bgCtx.fillStyle = \"#FFFFFF\";\n //sides\n bgCtx.fillRect(gridWidth*2-1,12,2,10);\n bgCtx.fillRect(gridWidth*85-1,12,2,10);\n //current hour\n bgCtx.fillRect(gridWidth*(2+thisHour)-1,12,2,10);\n //top\n bgCtx.fillRect(gridWidth*2-1,12,gridWidth*83+1,2);\n if (!currentlyMax) {\n //text\n bgCtx.font = \"12px Mukta\";\n bgCtx.textAlign = \"center\";\n bgCtx.fillStyle = \"#FFFFFF\";\n let timeString;\n if (currentHourSetting - thisHour > 0)\n timeString = \"+\" + (currentHourSetting - thisHour).toString() + \" hr\";\n else if (currentHourSetting - thisHour < 0)\n timeString = currentHourSetting - thisHour + \" hr\";\n else\n timeString = \"now\";\n bgCtx.fillText(\n timeString,\n Math.max(20, Math.min(timeSlider.clientWidth - 20, gridWidth * (2 + currentHourSetting) - 1)),\n 35\n );\n\n sliderHandleCanvas.style.left = (gridWidth * (2 + currentHourSetting)) - 10 + \"px\";\n handleCtx.fillStyle = \"#171717\";\n handleCtx.lineWidth = 2;\n handleCtx.strokeStyle = \"#FFFFFF\";\n handleCtx.beginPath();\n handleCtx.arc(10, 10, 9, 0, 2 * Math.PI);\n handleCtx.fill();\n handleCtx.stroke();\n //hour hand\n handleCtx.lineWidth = 1;\n handleCtx.beginPath();\n handleCtx.moveTo(10, 10);\n let hourHandPos = (parseInt(models[\"ChesapeakeBay_ADCIRCSWAN\"][\"lastForecast\"].format(\"hh\")) + currentHourSetting) / 12 - 0.25;\n handleCtx.lineTo(10 + Math.cos(2 * Math.PI * hourHandPos) * 5, 10 + Math.sin(2 * Math.PI * hourHandPos) * 5);\n handleCtx.stroke();\n //minute hand\n handleCtx.lineWidth = 1;\n handleCtx.beginPath();\n handleCtx.moveTo(10, 10);\n handleCtx.lineTo(10, 3);\n handleCtx.stroke();\n }\n\n //popup\n let popup = $('#timePopup');\n popup.text(models[\"ChesapeakeBay_ADCIRCSWAN\"][\"lastForecast\"].clone().add(currentHourSetting, 'hours').format(\"ddd HH:mm [UTC]\"));\n popup.css({\n 'left':Math.max(Math.min(sliderHandleCanvas.offsetLeft+10+timeSlider.offsetLeft,timeSlideContainer.clientWidth-50),50)\n })\n}", "function updateClock() {\n let d = new Date();\n let hours24 = d.getHours();\n let hours = hours24 % 12;\n let mins = d.getMinutes();\n let secs = d.getSeconds();\n\n // Set clock face\n hourHand.groupTransform.rotate.angle = hoursToAngle(hours, mins, secs);\n minHand.groupTransform.rotate.angle = minutesToAngle(mins, secs);\n secHand.groupTransform.rotate.angle = secondsToAngle(secs);\n \n // Set always Info\n setMonthDate(setMonth(d.getMonth()) + \"/\" + setDate(d.getDate()));\n setDay(d.getDay());\n setBattery();\n \n // Set touch Info\n time.text = util.zeroPad(hours24) + \":\" + util.zeroPad(mins) + \":\" + util.zeroPad(secs);\n setSteps();\n setHeartRate();\n}", "function initClocks() {\n var $rail = $('#WikiaRail');\n \n if ($rail.length === 0)\n return;\n \n var htmlClocksContainer = '<section id=\"wiki-custom-clockModule\" class=\"module\">';\n for (i = 0; i < clocksModuleLabels.length; ++i) {\n htmlClocksContainer = htmlClocksContainer + \n '<div class=\"clocksModule ' + clocksModuleLabels[i] + '\">'+\n '<b>' + clocksModuleLabels[i] + '</b> <br/>' +\n '<span id=\"clock'+ clocksModuleLabels[i] + '\">' + \n '</span>'+\n '</div>';\n }\n \n htmlClocksContainer = htmlClocksContainer + '</section>';\n $(htmlClocksContainer).appendTo($rail);\n \n setInterval( function () {\n refreshClock();\n }, 1000\n );\n }", "function resizeCanvas() {\n canvas.width = window.innerWidth / 2.5;\n canvas.height = window.innerWidth / 2.5;\n radius = canvas.width / 2;\n\n ctx.translate(radius, radius);\n radius = radius * 0.88;\n\n drawClock;\n}", "updateTimeSlider() {\n this.cAttackTime = 1 / this.settings.totalAS // current attack time\n let bWindupTime = 1 / this.settings.baseAS * this.settings.windup, // base windup time\n dWindupTime = (this.cAttackTime * this.settings.windup) - bWindupTime; // diff between bWindupTime and cWindupTime, assuming mod = 1\n\n this.cWindupTime = dWindupTime * this.settings.windupMod + bWindupTime;\n\n let cWindup = this.cWindupTime / this.cAttackTime\n\n this.$timeSliderWindup.css({ width: `${cWindup * 100}%` })\n }", "_updateFontSizes() {\n const timezoneFontSize = Math.max(Math.min(this._timezoneElm.parentElement.clientWidth / (2 * 10), parseFloat(25)), parseFloat(15));\n const dateFontSize = Math.max(Math.min(this._dateElm.clientWidth / (2 * 10), parseFloat(25)), parseFloat(15));\n const clockFontSize = Math.max(Math.min(this._clockElm.clientWidth / (0.8 * 10), parseFloat(100)), parseFloat(30));\n if (timezoneFontSize + dateFontSize + clockFontSize + Utils.convertRemToPixels(2) <= this._clock.container.clientHeight) {\n this._timezoneElm.style.fontSize = `${timezoneFontSize}px`;\n this._dateElm.style.fontSize = `${dateFontSize}px`;\n this._clockElm.style.fontSize = `${clockFontSize}px`;\n }\n }", "function screenResizeHandler() {\n\n\t\t// resize the div by css, returns the new size\n\t\tgameDivSize = screenSize(gameDiv, Config.boardRatio);\n\n\t\t// change canvas size by pixels\n\t\tgameDiv.width = gameDivSize.x;\n\t\tgameDiv.height = gameDivSize.y;\n\n\t\t// resize the title div by css\n\t\tscreenSize(titleDiv, Config.boardRatio);\n\n\t\t// scale text\n\t\t$(titleDiv).css(\"font-size\", 52/500*gameDivSize.x+\"px\");\n\t\t$(\"#title button\").css(\"font-size\", 22/500*gameDivSize.x+\"px\");\n\t}", "function updateTime() {\n\t\tvar dateTime = tizen.time.getCurrentDateTime(), secondToday = dateTime.getSeconds() + dateTime.getMinutes() * 60 + dateTime.getHours() * 3600,\n\t\tminDigitLeft = document.querySelector(\"#time-min-digit-left\"),\n\t\tminDigitRight = document.querySelector(\"#time-min-digit-right\"),\n\t\thourDigitLeft = document.querySelector(\"#time-hour-digit-left\"), \n\t\thourDigitRight = document.querySelector(\"#time-hour-digit-right\");\n\n\t\tvar minutesNow = (secondToday % 3600) / 60;\n\t\tvar hourNow = (secondToday / 3600);\n\t\tslideDigit(minDigitRight, minutesNow % 10.0);\n\t\tslideDigit(minDigitLeft, minutesNow / 10.0);\n\t\tslideDigit(hourDigitRight, hourNow % 10.0);\n\t\tslideDigit(hourDigitLeft, hourNow / 10.0);\n\t}", "_update() {\n // Get time now\n const time = zbTime.getNow();\n\n // If there is a current time\n if (this._currentTime) {\n // If nothing has changed then stop here\n if (this._currentTime.hour === time.hour && this._currentTime.minute === time.minute) return;\n }\n\n // Update current time\n this._currentTime = time;\n\n // Set show 24 hour clock\n let show24HourClock = false;\n\n // If there is a show 24 hour clock attribute\n if (this.hasAttribute('show24hour') === true) {\n // Set to show 24 hour clock\n show24HourClock = true;\n }\n\n // Set hour\n let hour = time.hour;\n\n // If showing 12 hour clock and over 12 hours\n if (show24HourClock === false && hour > 12) {\n // Minus 12 hours\n hour -= 12;\n }\n\n // Set digit numbers\n let digit1Number = Math.floor(hour / 10);\n const digit2Number = hour % 10;\n const digit3Number = Math.floor(time.minute / 10);\n const digit4Number = time.minute % 10;\n\n // If showing 12 hour clock and digit 1 number is zero\n if (show24HourClock === false && digit1Number === 0) {\n // Set the digit 1 number so that it hides the number\n digit1Number = -1;\n }\n\n // Set the digit lines\n this._setDigitLines(this._digit[0], digit1Number);\n this._setDigitLines(this._digit[1], digit2Number);\n this._setDigitLines(this._digit[2], digit3Number);\n this._setDigitLines(this._digit[3], digit4Number);\n\n // If 12 hour clock shown\n if (show24HourClock === false) {\n // If AM\n if (this._currentTime.hour < 12) {\n // Show AM\n this._amChildDomElement.className = 'ampm-child ampm-on';\n this._pmChildDomElement.className = 'ampm-child ampm-off';\n } else {\n // Show PM\n this._amChildDomElement.className = 'ampm-child ampm-off';\n this._pmChildDomElement.className = 'ampm-child ampm-on';\n }\n }\n }", "function bindTextClockEvent() {\n var parisTimeZone = 1;\n if (isBSTinEffect())\n parisTimeZone = 2;\n $('#paris_time').textClock(parisTimeZone);\n $('#shanghai_time').textClock(8);\n\t$('#nyk_time').textClock(-5);\n setInterval(function () {\n $('#paris_time').textClock(parisTimeZone);\n $('#shanghai_time').textClock(8);\n\t\t$('#nyk_time').textClock(-5);\n }, 1000 * 30);\n}", "function onWindowResize() {\n last = $.now();\n timer = timer || setTimeout(checkTime, 10);\n }", "function startclockTime(){\n clockId = setInterval(() => {\n time++;\n displayTime();\n },1000);\n}", "function update() {\n resize();\n controls.update();\n }", "function render() {\n timer.innerHTML = (clock / 1000).toFixed(3);\n }", "_changeSliderSize() {\n\t\t\t\tlet width = this.model.get('width'),\n\t\t\t\t\theight = this.model.get('height');\n\n\t\t\t\tthis.$el.css({width, height});\n\t\t\t}", "function time() {\n\t$(\"#clock\").html(number);\n}", "drawTimeAreaContent(changedType) {\n const ctx = this.context;\n const timeType = this.options.timeTypeName;\n // init coordinate by time type\n if (!changedType) {\n timeType.forEach((type) => {\n this.coordinate.timeArea[type].data = [];\n const timeAreaType = this.coordinate.timeArea[type].total;\n const oneBoxWidth = timeAreaType.width / this.options.timeArea.columnCount;\n const oneBoxHeight = timeAreaType.height / this.options.timeArea.rowCount;\n const maxNumber = type === 'hour' ? 24 : 60; // minute, second = 60\n let timeAreaObj = {};\n for (let ix = 0, ixLen = maxNumber; ix < ixLen; ix++) {\n const columnIdx = ix % this.options.timeArea.columnCount;\n const page = parseInt(ix /\n (this.options.timeArea.columnCount * this.options.timeArea.rowCount), 0) + 1;\n let rowIdx = 1;\n if (ix % (this.options.timeArea.columnCount * this.options.timeArea.rowCount)\n < this.options.timeArea.columnCount) {\n rowIdx = 0;\n }\n timeAreaObj = {\n startX: timeAreaType.startX + (columnIdx * oneBoxWidth),\n width: oneBoxWidth,\n startY: timeAreaType.startY + (rowIdx * oneBoxHeight),\n height: oneBoxHeight,\n page,\n styleObj: {\n fillText: {\n show: true,\n text: `${ix}`,\n },\n fill: {\n show: true,\n color: this.options.colors.thisMonthFill,\n },\n align: 'center',\n padding: {\n bottom: 13,\n },\n },\n };\n this.coordinate.timeArea[type].data.push(timeAreaObj);\n }\n });\n\n // DRAW box\n timeType.forEach((type) => {\n this.coordinate.timeArea[type].data.forEach((v) => {\n if (v.page === this.coordinate.timeArea[type].page) {\n this.dynamicDraw(ctx, v.startX, v.startY, v.width, v.height, v.styleObj);\n }\n });\n });\n } else {\n // DRAW box\n timeType.forEach((type) => {\n if (changedType === type) {\n this.coordinate.timeArea[type].data.forEach((v) => {\n if (v.page === this.coordinate.timeArea[type].page) {\n this.dynamicDraw(ctx, v.startX, v.startY, v.width, v.height, v.styleObj);\n }\n });\n }\n });\n }\n }", "_resizeHandler() {\n const that = this;\n\n that.$.container.style.width = that.$.container.style.height = Math.min(that.offsetWidth, that.offsetHeight) + 'px';\n }", "function set_clock(message) { document.getElementById(\"clock\").innerHTML = message; }", "function startClock() { \n timer = setInterval(displayTime, 500); \n }", "function changeSize() {\n carouselWrapWidth = carouselWrap.offsetWidth;\n isResizing = true;\n carouselList.style.transition = \"\";\n moveCarousel();\n}", "function updateTimerLengths() {\n if (sessionLength < 0) {\n sessionLength = 0;\n }\n if (breakLength < 0) {\n breakLength = 0;\n }\n $('#worklength').html(sessionLength / 60);\n $('#breaklength').html(breakLength / 60);\n }", "refreshClock() {\n if (this.alarmMode) {\n // Apply new values to all the sliders for this clock\n this.alarm.updateTime();\n // Re-apply old values since the dial positions are from a\n // previous clock and need changing to reflect this clock again\n this.alarm.refresh();\n }\n else if (this.timerMode) {\n // Apply new values to all the sliders for this clock\n this.timer.updateTime();\n // Re-apply old values since the dial positions are from a\n // previous clock and need changing to reflect this clock again\n this.timer.refresh();\n }\n else {\n this.updateClock();\n this.clock.refresh();\n }\n }", "function updateWidth(idNum, hrs, min) {\n var newWidth = (hrs * 100) + (min/15*25);\n var newX = $(\"#rect_\" + idNum).get(0).x.animVal.value + newWidth;\n\n $(\"#rt_rect_\" + idNum).attr(\"x\", newX);\n $(\"#handoff_btn_\" + idNum).attr(\"x\", newX-18);\n $(\"#collab_btn_\" + idNum).attr(\"x\", newX-38);\n\n var indexOfJSON = getEventJSONIndex(idNum);\n for (i = 1; i <= flashTeamsJSON[\"events\"][indexOfJSON].members.length; i++) {\n $(\"#event_\" + idNum + \"_eventMemLine_\" + i).attr(\"width\", newWidth-8);\n }\n\n $(\"#rect_\" + idNum).attr(\"width\", newWidth);\n updateTime(idNum);\n}", "function onResize() {\n\trender();\n}", "function grow() {\n timer = setInterval(function() {\n $(\".circle\").css(\"height\", function(idx, old) {\n return parseInt(old) + parseInt(growthAmount) + \"px\";\n });\n $(\".circle\").css(\"width\", function(idx, old) {\n return parseInt(old) + parseInt(growthAmount) + \"px\";\n });\n $(\".circle\").css(\"border-radius\", function(idx, old) {\n return parseInt(old) + parseInt(growthAmount) + \"px\";\n });\n }, growRate)\n }", "function onTimeSelectionChange() {\n drawTimeBlocks();\n drawInfoBox(timeSelectionControl.value);\n updateTimeSelectionIndicator(timeSelectionControl.value);\n }", "function updateClock() {\n let today = new Date();\n let hours = today.getHours() % 12;\n let mins = today.getMinutes();\n let secs = today.getSeconds();\n\n hourHand.groupTransform.rotate.angle = hoursToAngle(hours, mins);\n minHand.groupTransform.rotate.angle = minutesToAngle(mins);\n secHand.groupTransform.rotate.angle = secondsToAngle(secs);\n}", "function windowResized() {\r\n canvas_resize();\r\n set_origin();\r\n set_speed();\r\n bars[it].display();\r\n}", "function help_resize() {\n\t\tvar h_height = inner_size()[1];\n\t\tdocument.getElementById('general').style.height = h_height-45;\n\t\tdocument.getElementById('chat').style.height = h_height-45;\n\t\tdocument.getElementById('calendar').style.height = h_height-45;\n\t\tdocument.getElementById('inbox').style.height = h_height-45;\n\t\tdocument.getElementById('compose').style.height = h_height-45;\n\t\tdocument.getElementById('address').style.height = h_height-45;\n\t\tdocument.getElementById('folders').style.height = h_height-45;\n\t\tdocument.getElementById('search').style.height = h_height-45;\n\t\tdocument.getElementById('preferences').style.height = h_height-45;\n\t\tdocument.getElementById('credits').style.height = h_height-45;\n\t}", "function timeLine() {\n let width = 0;\n let itId = setInterval(() => {\n timeLineDiv.style.width = `${width}%`;\n width += 0.6;\n if (width > 100) {\n clearInterval(itId);\n if (heartsFave[0].classList.contains(\"fas\")) {\n heartsFave[0].classList.remove(\"fas\");\n heartsFave[0].classList.add(\"far\");\n }\n random();\n width = 0;\n timeLineDiv.style.width = `0%`;\n timeLine();\n }\n }, 100);\n}", "function reClock() {\n self.clock();\n }", "function sizeChange() {\n\n // Resize the timeline\n var wide = container.width(),\n high = container.height();\n var scale = wide / outerWidth;\n d3.select(\".topGroup\").attr(\"transform\", \"scale(\" + scale + \")\");\n $(\".svg-chart\").height(wide * (1.0 / aspect));\n\n}", "function PaintPeriodTime()\n{\t\n\tvar Static = true;\n\n\tif (TimeCard.View == 4 && TimeCard.Status != 2 && TimeCard.Status != 3)\n\t{\n\t\tStatic = false;\n\t}\t\n\t\n\tvar divObj = self.TABLE.document.getElementById(\"paneBody2\");\t\n\tdivObj.innerHTML = PaintTimeCard(\"Period\", Static);\n\t\n\tself.TABLE.stylePage();\n\tfitToScreen();\n\n\tif (!Static)\n\t{\n\t\tFillValues(\"Period\");\t\n\t}\t\n}", "function resizeCanvas() {\n let parent = canv.parentNode;\n if (parent == document.body) {\n parent = window;\n canv.style.width = parent.innerWidth + \"px\";\n\n canv.width = parent.innerWidth;\n canv.height = parent.innerHeight;\n }\n else {\n //Take the canvas out of the parent div sive calculation momentarily\n can.style.height = \"0px\";\n can.style.width = \"0px\";\n can.width = 0\n can.height = 0;\n //Then on the next tick put it back in.\n setTimeout(function () {\n let width = parent.clientWidth;\n let height = parent.clientHeight;\n can.style.width = width + \"px\";\n can.style.height = height + \"px\";\n can.width = width;\n can.height = height;\n //console.log(`${parent.clientWidth}-${parent.innerWidth}-${parent.offsetWidth}`)\n console.log(`${can.style.height} ${can.height}`)\n }, 0);\n\n }\n }", "function renderOnResize() {\n document.querySelector(\"#spacetime\").innerHTML = \"\"\n\n for(const event of events) {\n renderEvent(event)\n }\n renderTopBar()\n for(let series of seriesToPlot) {\n series.canvas.setAttribute(\"width\", document.body.clientWidth)\n }\n refresh()\n document.querySelector(\"#overlayCanvas\").setAttribute(\"width\", document.body.clientWidth)\n document.querySelector(\"#overlayCanvas\").setAttribute(\"height\", window.innerHeight)\n }", "onCustomWidgetResize(_width, _height){\r\n\t\t\t\r\n\t\t\tthis.wdth = _width;\r\n\t\t\tthis.hght = _height;\r\n\t\t\t//dispatching new custom event to capture width & height changes\r\n\t\t\tthis.dispatchEvent(new CustomEvent(\"propertiesChanged\", {\r\n\t\t\t\t\tdetail: {\r\n\t\t\t\t\t\tproperties: {\r\n\t\t\t\t\t\t\tchWidth: this.chWidth,\r\n\t\t\t\t\t\t\tchHeight: this.chHeight\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t}));\r\n\t\t\t\r\n\t\t\td3.select(this.shadowRoot).select(\"svg\").remove();\r\n\t\t\tthis.redraw();\r\n\t\t}", "function ResizeControl() {\n\t\t\t\ttry {\n\t\t\t\t\tiLog(\"ResizeControl\", \"Called\");\n\n\t\t\t\t\t// Do not update elements which have no or wrong size! (hidden)\n\t\t\t\t\tvar w = self.GetWidth();\n\t\t\t\t\tvar h = self.GetHeight();\n\t\t\t\t\tif (w < 1 || h < 1)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\n\t\t\t\t\tinput.width(w).height(h);\n\t\t\t\t\tspan.width(w).height(h);\n\t\t\t\t} catch (err) {\n\t\t\t\t\tiLog(\"ResizeControl\", err, Log.Type.Error);\n\t\t\t\t}\n\t\t\t}", "function updateClock() {\n // INSTANT PRESENT\n var now = new Date();\n\n // JOURS DE LA SEMAINE\n var weekday = new Array(7);\n weekday[0] = \"Sunday\";\n weekday[1] = \"Monday\";\n weekday[2] = \"Tuesday\";\n weekday[3] = \"Wednesday\";\n weekday[4] = \"Thursday\";\n weekday[5] = \"Friday\";\n weekday[6] = \"Saturday\";\n var day = weekday[now.getDay()];\n\n // MOIS DE L'ANNEE\n var month = new Array();\n month[0] = \"January\";\n month[1] = \"February\";\n month[2] = \"March\";\n month[3] = \"April\";\n month[4] = \"May\";\n month[5] = \"June\";\n month[6] = \"July\";\n month[7] = \"August\";\n month[8] = \"September\";\n month[9] = \"October\";\n month[10] = \"November\";\n month[11] = \"December\";\n var TodaysMonth = month[now.getMonth()];\n\n // HEURES\n var heures = now.getHours();\n if (heures < 10) {\n heures = \"0\" + now.getHours();\n }\n\n // MINUTES\n var minutes = now.getMinutes();\n if (minutes < 10) {\n minutes = \"0\" + now.getMinutes();\n }\n\n // SECONDES\n // var secondes = now.getSeconds();\n // if (secondes < 10) {\n // secondes = \"0\" + now.getSeconds();\n // }\n\n // AFFICHAGE DATE PAGE LOCK\n $('#date h1').text(heures + \":\" + minutes);\n $('#date p').text(day + \" \" + now.getDate() + \" \" + TodaysMonth);\n\n // AFFICHAGE HEURE HEADER\n $('.currentHour').text(heures + \":\" + minutes);\n setTimeout(updateClock, 1000);\n }", "function timer_display() {\n if (timer_for_ques == 0) {\n resetTimer();\n } else {\n timer_for_ques--;\n document.getElementById('CLK').innerHTML = timer_for_ques + \"s\";\n }\n}", "function updateClock(){\n var ahora = new Date();\n var hora = ahora.getHours();\n\tif(hora < 10) hora = \"0\" + hora;\n var min = ahora.getMinutes();\n\tif(min < 10) min = \"0\" + min;\n var sec = ahora.getSeconds();\n\tif(sec < 10) sec = \"0\" + sec;\n/* Se muestra por pantalla el reloj actualizando por segundo */\n\tclock.html(hora + \" : \" + min + \" : \" + sec);}", "function lclock() {\r\n dt = new Date();\r\n hrs = dt.getHours();\r\n min = dt.getMinutes();\r\n sec = dt.getSeconds();\r\n\r\n hrs = Clock(hrs);\r\n min = Clock(min);\r\n sec = Clock(sec);\r\n\r\n document.getElementById('dc').innerHTML = hrs + \":\" + min;\r\n document.getElementById('dc_second').innerHTML = sec;\r\n\r\n if (hrs > 12) { \r\n document.getElementById('dc_hour').innerHTML = 'PM'; \r\n }\r\n else { \r\n document.getElementById('dc_hour').innerHTML = 'AM'; \r\n }\r\n\r\n time = setInterval('lclock()', 1000);\r\n}", "_updateSize(getter) {\n const that = this;\n\n if (that.sizeMode === 'circle' && getter === undefined) {\n return;\n }\n\n const minCoordinates = that._minCoordinates,\n maxCoordinates = that._maxCoordinates;\n let top = minCoordinates[0],\n bottom = maxCoordinates[0];\n\n for (let i = 1; i < minCoordinates.length; i++) {\n top = Math.min(top, minCoordinates[i]);\n }\n\n for (let i = 1; i < maxCoordinates.length; i++) {\n bottom = Math.max(bottom, maxCoordinates[i]);\n }\n\n const gaugeClientRect = that.getBoundingClientRect();\n\n if (that.digitalDisplay) {\n const digitalDisplayClientRect = that.$.digitalDisplay.getBoundingClientRect();\n\n top = Math.min(top, digitalDisplayClientRect.top - gaugeClientRect.top);\n bottom = Math.max(bottom, digitalDisplayClientRect.bottom - gaugeClientRect.top);\n }\n\n if (that.analogDisplayType !== 'needle') {\n const trackBBox = that._track.getBBox();\n\n top = Math.min(top, trackBBox.y);\n bottom = Math.max(bottom, trackBBox.y + trackBBox.height);\n }\n\n for (let i = 0; i < that._ranges.length; i++) {\n const rangeBBox = that._ranges[i].getBBox();\n\n top = Math.min(top, rangeBBox.y - gaugeClientRect.top);\n bottom = Math.max(bottom, rangeBBox.y + rangeBBox.height - gaugeClientRect.top);\n }\n\n top -= 2;\n\n const newHeight = bottom - top;\n\n if (getter === undefined) {\n that._preventResizeHandler = true;\n\n that.style.height = newHeight + 'px';\n that.$.container.style.marginTop = -1 * top + 'px';\n\n that._measurements.cachedHeight = newHeight;\n }\n else {\n return Math.round(newHeight);\n }\n }", "function changeMode(){\n $('.fill').css('height','0%');\n $('.clock').addClass('shadow-pulse');\n $('.clock').on('animationend', function(){\n $('.clock').removeClass('shadow-pulse');\n });\n if(mode==\"session\"){\n $('.clock .session_time').css('display','none');\n $('.clock .break_time').css('display','block');\n $('.clock .break_time').html($('.span_break').html());\n mode=\"break\";\n $('.action').html(\"Break\");\n sec=0;\n min=parseInt($('.span_break').html());\n clearInterval(each_sec_interval);\n clock=false;\n $('.clock').click();\n }\n else if(mode==\"break\"){\n $('.clock .break_time').css('display','none');\n $('.clock .session_time').css('display','block');\n $('.clock .session_time').html($('.span_session').html());\n mode=\"session\";\n $('.action').html(\"Session\");\n sec=0;\n min=parseInt($('.span_session').html());\n clearInterval(each_sec_interval);\n clock=false;\n $('.clock').click();\n }\n }", "function hexClock() {\n\nvar time = new Date();\nvar hours = (time.getHours() % 12); // TO STRING IS BECAUSE ITS A NUMBER AND YOU CANT CHECK LENGTH WITH OUT IT BEING A STRING.\nvar minutes = time.getMinutes();\nvar seconds = time.getSeconds(); //**** THIS IS HOW YOU GET TIME *******\nif (hours.length < 2){\n hours = '0' + hours; //THIS IS TO GET TIME TO SHOW ZERO IN FRONT INCASE ITS 1 DIGIT\n}\nif (minutes.length <2){\n minutes = '0' + minutes;\n}\nif (seconds.length <2){\n seconds = '0' + seconds;\n}\n var colorHex = time.getHours().toString();\n if (hours.lenth < 2){\n hours = '0'+ hours;\n}\n\n//***ADDED IN CLASS***\n// COLOR BACKGROUND HEX\nvar currentRed = ( '0' + hours.toString(16)).slice(-2);\nvar currentGreen = ('0' + minutes.toString(16)).slice(-2);\nvar currentBlue = ('0' + seconds.toString(16)).slice(-2);\nvar colorCode = '#' + currentRed + currentGreen + currentBlue;\nbackground.style.backgroundColor = colorCode;\n\n\n// var colorClock = hours + ':' + minutes + ':' + seconds;\nvar percentageForStatusbar = ((seconds/60)*100).toFixed();\n\n\n\n//***EDITED IN CLASS****** THIS IF FOR EXECUTING HEX VS REG. CLOCK\nif(hoverOverClock == true){\n hoursContainer.textContent = currentRed;\n minutesContainer.textContent = currentGreen;\n secondsContainer.textContent = currentBlue;\n\n}else{\n hoursContainer.textContent = ( '0' + hours).slice(-2);\n minutesContainer.textContent = ('0' + minutes).slice(-2);\n secondsContainer.textContent = ('0' + seconds).slice(-2);\n};\n\n\nconsole.log(seconds);\nsecondsbar.style.width = percentageForStatusbar + '%';\n\n}", "function div_update(cont,height,color)\n{\n window.setTimeout(function(){\n cont.style=\" margin:0% \" + margin_size + \"%; width:\" + (100/arraySize-(2*margin_size)) + \"%; height:\" + height + \"%; background-color:\" + color + \";\"\n + \"border-top-left-radius: 35px; border-top-right-radius: 35px; border-bottom-left-radius: 35px; border-bottom-right-radius: 35px;\";\n },c_delay+=delay_time);\n\n //setTimeout() calls a function or evaluates an expression after a specified number of milliseconds.\n}", "function adjustTimer() {\r\n\tif (timerLength < 10) duration.innerText = '0' + timerLength;\r\n\telse duration.innerText = timerLength;\r\n\t//adjusts display for time (minutes) when app is static\r\n\tif (running === false) { minutes.innerText = timerLength; }\r\n}", "function startClock(containerId){\n window.setTimeout(function(){\n startClock(containerId);\n }, 10);//10 ms\n\n var now = new Date();//Get the current time and date\n //Get the time parts from the current date\n var hours = now.getHours();\n var minutes = now.getMinutes();\n var seconds = now.getSeconds();\n var mseconds = now.getMilliseconds();\n\n //Calculate the degrees\n var hoursDegrees = 360*(hours+minutes/60)/12;\n var minutesDegrees = 360*(minutes+seconds/60)/60;\n var secondsDegrees = 360*(seconds+mseconds/1000)/60;\n\n //Make two digits for eacht time part\n var hStr = (hours < 10)?'0'+hours:hours.toString();\n var mStr = (minutes < 10)?'0'+minutes:minutes.toString();\n var sStr = (seconds < 10)?'0'+seconds:seconds.toString();\n\n //Assign parts to UI --> HTML Elements\n $(containerId + ' .clock-indicator-hours.led1').html(hStr.charAt(0));\n $(containerId + ' .clock-indicator-hours.led0').html(hStr.charAt(1));\n $(containerId + ' .clock-indicator-minutes.led1').html(mStr.charAt(0));\n $(containerId + ' .clock-indicator-minutes.led0').html(mStr.charAt(1));\n $(containerId + ' .clock-indicator-seconds.led1').html(sStr.charAt(0));\n $(containerId + ' .clock-indicator-seconds.led0').html(sStr.charAt(1));\n\n //$(containerId).css('transform','rotate(' + secondsDegrees + 'deg)');\n /*\n -webkit-transform:rotate(0deg);\n -moz-transform:rotate(0deg);\n -o-transform:rotate(0deg);\n -ms-transform:rotate(0deg);\n transform:rotate(0deg);\n */\n $(containerId + ' .clock-compass .clock-compass-indicator').css('-webkit-transform', 'rotate(' + secondsDegrees + 'deg)');\n $(containerId + ' .clock-compass .clock-compass-indicator').css('-moz-transform', 'rotate(' + secondsDegrees + 'deg)');\n $(containerId + ' .clock-compass .clock-compass-indicator').css('-o-transform', 'rotate(' + secondsDegrees + 'deg)');\n $(containerId + ' .clock-compass .clock-compass-indicator').css('-ms-transform', 'rotate(' + secondsDegrees + 'deg)');\n $(containerId + ' .clock-compass .clock-compass-indicator').css('transform', 'rotate(' + secondsDegrees + 'deg)');\n\n var l = $(containerId).css('left');\n var il = parseFloat(l.substring(0, l.indexOf('px')));\n var speed = parseFloat($(containerId).data('speed'));\n\n if(il+speed >= 0 && il+speed <= $(window).width()-$(containerId).width()){\n il += speed;\n }\n else{\n speed *= -1;\n }\n $(containerId).data('speed', speed);\n $(containerId).css('left', il+'px');\n $(containerId).css('-webkit-transform', 'rotate(' + secondsDegrees + 'deg)');\n}" ]
[ "0.70080316", "0.66039807", "0.6589867", "0.6363707", "0.621936", "0.6183913", "0.6150003", "0.61463803", "0.612782", "0.6108592", "0.60831994", "0.60551375", "0.6032234", "0.6031214", "0.60196763", "0.6014489", "0.6008291", "0.5998556", "0.598506", "0.5978489", "0.59771335", "0.596694", "0.5955628", "0.59495467", "0.59467036", "0.5933601", "0.59077173", "0.5885308", "0.587435", "0.5867512", "0.58670425", "0.58545643", "0.5849284", "0.5847645", "0.58344775", "0.58192545", "0.5817966", "0.5808845", "0.5807901", "0.57578725", "0.57440436", "0.57376564", "0.5736662", "0.57297903", "0.5723595", "0.5712277", "0.57076436", "0.57040125", "0.5703058", "0.5702155", "0.57017535", "0.56919837", "0.5686168", "0.5677862", "0.5675669", "0.56669843", "0.5663478", "0.56622916", "0.5661535", "0.56599796", "0.56503177", "0.5647971", "0.564716", "0.5646083", "0.5643196", "0.56419927", "0.56286055", "0.56258154", "0.5625676", "0.562445", "0.5623227", "0.5619994", "0.56197524", "0.5619578", "0.5613735", "0.5603864", "0.56034577", "0.5603003", "0.55963826", "0.5590478", "0.5580347", "0.55774117", "0.55729717", "0.5572412", "0.5570145", "0.55701", "0.5568387", "0.5557149", "0.5557007", "0.5555961", "0.55541855", "0.5552796", "0.5550954", "0.554924", "0.5547223", "0.5545866", "0.5543043", "0.5542362", "0.55323714", "0.55266756" ]
0.707742
0
Write a function that returns a boolean indicating whether or not a string is a palindrome.
function palinChecker(string){ var backword = string.split('').reverse().join(''); console.log(backword); if (backword == string){ console.log("You have a palindrome."); return true; } else{ console.log("Not a palindrome."); return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function palindrome(str) {\n return true;\n}", "function palindrome(str) {\r\n // Good luck!\r\n return true;\r\n}", "function palindrome(str) {\n // Compare if original string is equal with reversed string\n return str === reverse(str)\n}", "function palindrome(str){\r\n return reverseString(str) === str;\r\n}", "function isPalindrome(str) {\n\n}", "function isPalindrome(string) {\n\n function reverse() {\n return string.split('').reverse().join('')\n }\n\n return string === reverse();\n}", "function isPalindrome(str) {\r\n if (str === reverseString(str)) {\r\n return true;\r\n }\r\n return false;\r\n}", "function isPalindrome(str) {\r\n if(str === reverseString(str))\r\n return true;\r\n return false;\r\n}", "function isPalindrome(s) {\n var pal = s.split('').reverse().join('');\n return s == pal;\n}", "function isPalindrome(str)\n{\n var reverse = reverseStr(str);\n if(str === reverse)\n {\n return true;\n }\n return false;\n\n}", "function palindrome(string) {\n let lower = string.toLowerCase();\n return lower === reverse(lower);\n}", "function palindrome(string) {\n return string.toLowerCase() === reverse(string.toLowerCase());\n}", "function palindrome(str) {\n \n // pre-process\n str = str.toLowerCase();\n \n // find unwanted characters and replace\n const re = /[^a-z\\d]+/g;\n\tstr = str.replace(re, '');\n\t\n // for reversing a string\n function reverseString(txt) {\n return txt.split('').reverse().join('');\n\t}\n\n\t// A question of symmetry:\n // find length & middle, split and reverse one piece\n // then check for equality\n \n\t// even if odd length string, this will give us enough to\n\t// check two halves are palindromic\n\tconst half = Math.floor(str.length / 2);\n\t\n\tconst flipped = reverseString(str.substring(str.length - half));\n\t\n\treturn str.substring(0, half) === flipped;\n \n}", "function isPalindrome (inputStr) {\n\treturn inputStr.split('').reverse().join('') === inputStr ? true : false; \n}", "function palindrome(string) {\n // reverse string\n const reversed = string\n .split(\"\")\n .reverse()\n .join(\"\");\n return string === reversed;\n}", "function isPalindrome(str) {\n // const revString = str\n // .split(\"\") // turn a string into an array\n // .reverse() // reverse, duh\n // .join(\"\"); // method returns the array as a string.\n // return revString === str;\n}", "function isPalindrome(str) {\n return str.split('').reverse().join('') === str\n}", "function palindrome(str) {\n const rev = str.split('').reverse().join('');\n return str === rev;\n}", "function isPalindrome(str) {\n const revString = str.split('').reverse().join('');\n return str === revString;\n}", "function isPalindrome(str) {\n return (\n str ===\n str\n .split(\"\")\n .reverse()\n .join(\"\")\n );\n}", "function isPalindrome(str) {\n // NOTE Reverse the string\n const reversed = str\n .split(\"\")\n .reverse()\n .join(\"\");\n // NOTE Check if reversed string matches the original\n\n if (reversed === str) {\n return true;\n } else {\n return false;\n }\n // NOTE This returns the same.\n //return reversed === str;\n}", "function palindrome(str) {\n if (str === str.split(\"\").reverse().join(\"\")) {\n return true;\n } else {\n return false;\n }\n}", "function isPalindrome(str){\n const revString = str.split('').reverse().join(''); \n return revString === str; // will give true or false\n \n}", "function isPalindrome(string) {\n var reversedString = string.split('').reverse().join('');\n return reversedString === string;\n}", "function palindrome(string) {\n let processedContent = string.toLowerCase();\n return processedContent === reverse(processedContent);\n}", "function palindrome(str) {\n let pal = str.split('').filter(char => /[a-z]| */.test(char));\n\n return pal.join('') === pal.reverse().join('') ? true : false;\n}", "function palindrome(string) {\n let processedContent = string.toLowerCase();\n return processedContent() === reverse(this.processedContent());\n}", "function palindrome(str) {\n\t// Array.prototype.every -- is used to do a boolean check on every element within an array\n\t// arr.every((val) => val > 5);\n\t// If any function returns false, then the overall expression returns false as well\n\treturn str.split('').every((char,i) => {\n\t\treturn char === str[str.length -i -1]; // mirrored element\n\t});\n}", "function isPalindrome(s) {\n var str = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase()\n var half = Math.floor(str.length / 2)\n var lastIndex = str.length - 1\n for (var i = 0; i < half; i++) {\n if (str[i] !== str[lastIndex - i]) {\n return false\n }\n }\n\n return true\n}", "function isPalindrome(string) {\n let leftIdx = 0;\n let rightIdx = string.length - 1;\n while (leftIdx < rightIdx) {\n if (string[leftIdx] !== string[rightIdx]) return false;\n leftIdx++;\n rightIdx--\n }\n return true\n}", "function isPalindrome(string) {\n let reverseString = string.split(\"\").reverse().join(\"\");\n return reverseString === string;\n}", "function isPalindrome_V2(str){\n if(str.split('').reverse().join('')==str){\n return true;\n }\n return false;\n \n}", "function isPalindrome(str) {\n // Strategy: reverse the string and then check if equal\n\n // With accumulator of out = \"\"\n // if (i === str.length) return str === out;\n // out = str[i] + out;\n // return isPalindrome(str, out, i + 1);\n\n let reversed = \"\";\n\n function _reverseStr(str, i) {\n if (i === str.length) return;\n reversed = str[i] + reversed;\n return _reverseStr(str, i + 1);\n }\n _reverseStr(str, 0);\n return str === reversed;\n}", "function isPalindrome(str){\n // add whatever parameters you deem necessary - good luck!\n if (str.length === 1) return true;\n \n return str[0] === str[str.length - 1] && isPalindrome(str.slice(1, str.length - 1));\n}", "function checkForPalindrome(word) {\r\n if (word === reverseString(word)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n}", "function palindrome(str) {\n const string = str.toLowerCase().replace(/[^0-9a-z]/gi, '').trim(),\n reversed = string.split('').reverse().join('');\n\n if (reversed === string) {\n return true;\n }\n\n return false;\n}", "function isPalindrome(string) {\n let revIdx = string.length - 1\n let idx = 0\n\n while (idx < revIdx) {\n if (string[revIdx] !== string[idx]) {\n return false\n }\n idx += 1\n revIdx -= 1\n } \n return true\n }", "function isPalindrome(str) {\n const copy = str.split('').reverse().join('');\n return copy === str;\n}", "function isPalindrome(palindrome) {\n palindrome = uniformString(palindrome);\n\tfor ( var i=0; i <palindrome.length/2; i++) {\n\t\treturn (palindrome.charAt(i) === palindrome.charAt(palindrome.length-1));\n //Compares characters starting at both ends of the String\n\t}\n}", "function palindrome(str) {\n let regex = /[a-z0-9]/;\n let strArr = str.toLowerCase().split(\"\").filter(ele => regex.test(ele));\n let inverseArr = [];\n\n strArr.forEach(ele => {inverseArr.unshift(ele)});\n\n return strArr.join(\"\") == inverseArr.join(\"\")? true: false;\n}", "function palindromeCheck(str) {\n if (str.length === 1) { // if the length of a word is only 1 character, \n return false; // take it out because a palindrome cannot be created. \n }\n\n str = str.toLowerCase(); // make lower case to make sure algo accounts for all characters in string\n\n let reverseStr = ''; // instantiate blank palindrome holder; \n\n for (let i = str.length - 1; i >= 0; i--) { // loop through string backwards and see what comes out as a palindrome. \n reverseStr += str[i]; // count the number of times a palindrome was able to be found and with what words in string. \n }\n\n return reverseStr === str; // return all palindromes that are the same as the existing words in the string.\n}", "function isPalindrome(string) {\n const reversedChars = [];\n for (let i = string.length - 1; i >= 0; i--) {\n reversedChars.push(string[i])\n }\n return string === reversedChars.join(\"\");\n}", "function palindrome(string){\n let len = string.length;\n for(let i = 0; i < string.length; i++){\n if(string[i] != string[len - i - 1]){\n return false;\n }\n }\n return true;\n}", "function palindrome(string) {\n for (var i = 0; i < Math.floor(string.length / 2); i++) {\n if (string[i] !== string[string.length - 1 - i]) {\n return false;\n }\n }\n return true;\n}", "function isPalindrome(str) {\n var re = /[^A-Za-z0-9]/g; //set up our regular expression that will do a global(g modifier) search for the character-span that is not from A-Z, a-z, and 0-9;\n var myString = str.toLowerCase().replace(re, \"\"); //set our string to lower case and remove anything that is not from A-Z, a-z, and 0-9 replace with an empty quotation mark(\"\");\n var reverseString = myString.split(\"\").reverse().join(\"\"); //split our string, reverses it and join back together for comparsion;\n return myString === reverseString; //check to see if our string is palindrome, returns true or false value;\n}", "function isPalindrome1(string) {\n const compareString = \n string.split('')\n .reverse()\n .join('')\n if(string === compareString) return true;\n else return false\n}", "function isPalindrome(someStr) {\r\n \r\n thePalin = someStr.split('').reverse().join('');\r\n if (thePalin == someStr)\r\n return true;\r\n else\r\n return false;\r\n \r\n}", "function isPalindrome(str) {\n return str.split('').reverse().join('').toLocaleLowerCase() === str.toLocaleLowerCase();\n}", "function isPalindrome (string) {\n var halfString = Math.floor(string.length / 2);\n for (var i = 0; i < halfString; i++)\n if (string[i] !== string[string.length - i - 1])\n return false;\n return true;\n}", "function palindrome(str) {\n return str.toLowerCase().split('').reverse().join('') === str.toLowerCase();\n}", "function isPalindrome(str) {\n const len = str.length;\n\n for (let i = 0; i < len / 2; i++) {\n if (str[i] !== str[len - 1 - i]) {\n return false;\n }\n }\n\n return true;\n}", "function palindrome(str) {}", "function isPalindrome(x) {\n return x.toLowerCase() === x.toLowerCase().split('').slice().reverse().join('') ? true : false;\n}", "function palindrome(str) {\n var filteredString = str.toLowerCase().replace(/[^A-Za-z0-9]/g,'');\n var reverseString = filteredString.split('').reverse().join('');\n \n if (filteredString === reverseString) {\n return true;\n }\n return false;\n}", "function isPalindrome(s) {\n s = s.replace(/( |[^a-zA-Z0-9])/g, '').toLowerCase()\n var i = 0\n var j = s.length - 1\n\n while (i < j){\n if (s[i] === s[j]) {\n i++\n j--\n } else {\n return false\n }\n }\n\n return true\n}", "function isPalindrome( string ) {\n\tstring = onlyLetters( string );\n\tfor ( var i = 0; i < Math.floor( string.length / 2 ); i++ ) {\n\t\tif ( string[ i ].toUpperCase() !== string[ string.length - i - 1 ].toUpperCase() ) {\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn true;\n}", "function isPalidrome(str){\n let reverseStrArray = str.split('').reverse();\n let reverseStr = reverseStrArray.join(''); \n \n if (str === reverseStr){\n return true;\n }\n \n return false;\n }", "function isPalindrom(str) {\n const revString = str\n .split(\"\")\n .reverse()\n .join(\"\");\n return revString === str;\n}", "function isPalindrome(str){\n if(!str) return true;\n return (str[0] === str[str.length - 1]) && isPalindrome(str.slice(1,-1));\n}", "function isPalindrome(str) {\r\n return str === str.split('').reverse().join('');\r\n}", "function palindrome(string) {\n const arr = string\n .toLowerCase()\n .replace(/[^a-z0-9+]+/gi, \"\")\n .split(\"\");\n while (arr.length > 0) {\n if (arr[0] === arr[arr.length - 1]) {\n arr.splice(0, 1);\n arr.splice(arr.length - 1, 1);\n } else return false;\n }\n return true;\n}", "function palindrome(string) {\n\n}", "function isPalindrome(str) {\n return str == str.split('').reverse().join('');\n}", "function palindrome(string){\n let len = string.length;\n let str = string.toLowerCase();\n for(let i = 0; i < str.length/2; i ++){\n if(str[i] != str[len - i - 1]){\n return false;\n }\n }\n return true;\n}", "function isPalindrome(str) {\r\n\r\n //Compare if the str getting passed is equal to the reversed of the string\r\n //If it matches then return true\r\n //else false\r\n if(str === reverseString(str)){\r\n console.log(\"True\");\r\n return true;\r\n }\r\n else{\r\n console.log(\"false\");\r\n return false;\r\n }\r\n}", "function isPalindrome(str) {\n let revStr;\n function reverse(str) {\n if (str === \"\") {\n return str;\n }\n return reverse(str.substring(1)) + str.charAt(0);\n }\n revStr = reverse(str);\n if (revStr === str) {\n return true;\n } else {\n return false;\n }\n}", "function isPalindrome(string) {\r\n left = 0\r\n right = string.length - 1\r\n while (left < right) {\r\n if (string[left] != string[right]) return false\r\n left++\r\n right--\r\n }\r\n return true\r\n}", "function is_palindrome(s) {\n s = s.toLowerCase().replace(/[^a-zA-Z0-9]/g, '');\n\n const regularString = new Stack();\n for (let i = 0; i < s.length; i++) {\n regularString.push(s[i]);\n }\n\n // racecar front to back, racecar back to front\n const reverseString = new Stack();\n for (let i = s.length - 1; i >= 0; i--) {\n reverseString.push(s[i]);\n }\n\n while (regularString.top !== null) {\n if (regularString.top.data !== reverseString.top.data) {\n return false;\n }\n regularString.top = regularString.top.next;\n reverseString.top = reverseString.top.next;\n }\n\n return true;\n}", "function isPalindrome(str){\n//base case\nif (str.length === 1) return true;\nif (str.length === 2) return str[0] === str[1] //boolean\n\nif (str[0] === str.slice(-1)) return isPalindrome(str.slice(1, -1)) //.slice(-1) is the end of the word \n\nreturn false \n\n}", "function isPalindromeMrBludworth(str){\n const temp = reverseString(str);\n if (temp !== str){\n return false;\n } else {\n return true;\n }\n}", "function isPalindrome(string){\n for (var i = 0; i < string.length / 2; i++){\n if (string[i] !== string[string.length - 1 -i]) {\n return false\n }\n }\n return true\n }", "function isPalindrome (n) {\n n = n.toString()\n\n var parts = split(n)\n\n return parts[0] === reverse(parts[1])\n}", "function isPalindrome(string) {\n string = string.toLowerCase();\n var charactersArr = string.split(\"\");\n var validCharacters = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n\n var lettersArr = [];\n charactersArr.forEach(char => {\n if (validCharacters.indexOf(char) > -1) lettersArr.push(char);\n });\n\n if (lettersArr.join(\"\") === lettersArr.reverse().join(\"\")) return true;\n else return false;\n}", "function isPalindrome(stringValue) {\n\n if (reverseText(stringValue) === stringValue)\n return true;\n else\n return false;\n\n}", "function isPalindrome(str) {\n var toLower = str.toLowerCase();\n var noSpace = toLower.replace(\" \", \"\");\n var letterArray = noSpace.split(\"\");\n var reversed = letterArray.reverse();\n var final = reversed.join(\"\");\n\n return str.toLowerCase() === final;\n}", "function isPalindrome(s) {\n\tvar str = s.replace(/\\W/g,\"\").toLowerCase();\n\treturn str == str.split(\"\").reverse().join(\"\")\n}", "function palindrome(str) {\n\tlet reversedStr = str\n\t\t.toLowerCase()\n\t\t.split(\"\")\n\t\t.reverse()\n\t\t.join(\"\");\n\treturn reversedStr === str;\n}", "function validPalindrome(s) {\n // only have alphanumeric\n s = s.replace(/[^0-9a-zA-Z]+/gim, \"\")\n s = s.toLowerCase()\n\n // using two pointer\n // one starts at the beginning\n // one at end of s\n let l = 0\n let r = s.length - 1\n // while 0 < length - 1\n while (l <= r) {\n // if char doesn't match return false right away\n if (s[l] !== s[r]) {\n return false\n }\n // else increment the pointer\n l++\n r--\n }\n // once all string has been traversed return true\n return true\n}", "function checkIsPalindrome(inputString) {\n\n if (typeof inputString !== \"string\") {\n return \"no\";\n }\n\n // checking palindromes is kind of weird.\n // take the length of the string.\n // grab string [0] and string [n]; compare for sameness\n // iterate until floor(n/2), I guess\n // as long as the bit is true, it's a palindrome?\n\n let wordArr = inputString.split('');\n for (let i = 0; i < wordArr.length / 2; i++) {\n if (wordArr[i] !== wordArr[wordArr.length - i - 1]) {\n return \"no\";\n }\n }\n return \"yes\";\n\n}", "function isPalindrome(str) {\r\n let len = str.length;\r\n if (len === 1)\r\n return true;\r\n\r\n if (str[0] === str[len - 1])\r\n return isPalindrome(str.slice(1, len - 1));\r\n\r\n return false;\r\n}", "function isPalindrome(string) {\n let charArray = Array.from(string);\n\n return charArray.reverse().join('') === string;\n}", "function isPalindrome(string) {\n string = string.toLowerCase();\n var charactersArr = string.split('');\n var validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('');\n \n var lettersArr = [];\n charactersArr.forEach(char => {\n if (validCharacters.indexOf(char) > -1) lettersArr.push(char);\n });\n \n return lettersArr.join('') === lettersArr.reverse().join('');\n}", "function isPalindrome(str){\r\n // add whatever parameters you deem necessary - good luck!\r\n \r\n function reverse(str){\r\n //console.log(\"STR: \"+str);\r\n if(str === ''){ \r\n return '';\r\n }\r\n \r\n return str.charAt(str.length-1)+reverse(str.substr(0,str.length-1));\r\n }\r\n \r\n return str === reverse(str) ? true : false;\r\n \r\n }", "function isPalindrome(str) {\n\tfor(var i = 0; i < str.length / 2; i++) {\n\t\tvar oppositeI = str.length - 1 - i;\n\n\t\t// The letters on the other end better match!\n\t\tif(str[i] !== str[oppositeI]) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\treturn true;\n}", "function isPalindrome(string) {\n //initialize left and right pointers\n let left = 0;\n let right = string.length - 1;\n while (left < right) {\n //check to see if letters at left and right pointers are equal\n if (string[left] === string[right]) {\n //if so increment/decrement the pointers\n left++;\n right--;\n } else {\n return false;\n }\n }\n //if you have reached this point, it means the string is palindrome so return true\n return true;\n}", "function isPalindromic(string) {\n var i;\n var stringMinusSpaces = '';\n for (i = 0; i < string.length; i++) {\n if (string[i] !== ' ') {\n stringMinusSpaces += string[i];\n }\n }\n var stringInReverse = '';\n for (i = stringMinusSpaces.length - 1; i >= 0; i = i - 1) {\n stringInReverse += stringMinusSpaces[i];\n }\n if (stringInReverse === stringMinusSpaces) {\n return true;\n } else {\n return false;\n }\n}", "function palindromeChecker(text) {\n const reversedText = text.toLowerCase().split(\"\").reverse().join(\"\")\n return text === reversedText\n}", "function isPalindromic(string) {\n var reverse = '';\n for (var i = string.length - 1; i >= 0; i--) {\n reverse += string[i];\n }\n if (reverse.replace(' ', '') === string.replace(' ', '')) {\n return true;\n }\n return false;\n}", "function palindrome(string) {\n // build an output string\n let str = string\n .replace(/[^a-zA-z]/g, '')\n .split('')\n .map((ch) => ch.toLowerCase())\n .join('');\n\n if (str.length === 1 || str === '') return true;\n\n if (str[0] !== str[str.length - 1]) {\n return false;\n }\n\n return palindrome(str.slice(1, -1));\n}", "function isPalindrome(string) {\n\t// Write your code here.\n\tif (string.length === 1) return true\n\t\n\tlet leftPointer = 0\n\tlet rightPointer = string.length - 1\n\n\twhile (leftPointer < rightPointer) {\n\t\tif (string[leftPointer] !== string[rightPointer]) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tleftPointer++;\n\t\trightPointer--;\n\t}\n\t\n\treturn true;\n}", "function palindrome(str){\n\tconst middle = Math.floor(str.length/2);\n\n\tconst firsthalf = str.substring(0, middle);\n\tconst secondhalf = (str.length % 2 === 0)? str.substring(middle) : str.substring(middle + 1);\n\t\n\treturn (firsthalf === reverse(secondhalf));\n}", "function isPalindrome(string) {\n\tif (string.length === 1) return true;\n let firstPointer = 0;\n\tlet secondPointer = string.length - 1;\n\twhile (firstPointer <= secondPointer) {\n\t\tif (string[firstPointer] !== string[secondPointer]) {\n\t\t\treturn false;\n\t\t}\n\t\tfirstPointer++;\n\t\tsecondPointer--;\n\t}\n\treturn true;\n}", "function isPalindrome(str){\n var left = 0;\n var right = str.length - 1;\n while (left < right){\n if (str[left] != str[right]){\n return false;\n }\n left++;\n right--;\n }\n return true;\n}", "function isPalindrome(str){\n const length = str.length;\n if (length === 1) return true;\n if(str.charAt(0) !== str.charAt(str.length - 1)) {\n return false;\n }\n return isPalindrome(str.slice(1, str.length - 1));\n}", "function isPalindrome(str){\n return (str === str.split('').reverse().join('')); \n}", "function isPalindrome(str){ \n if(str.length <= 1) {\n return true;\n } else {\n if (str[0] === str[str.length - 1]) {\n return isPalindrome(str.substring(1, str.length - 1))\n } else {\n return false;\n }\n }\n}", "function palindrome2(str) {\n str = str.match(/[A-Za-z0-9]/gi).join(\"\").toLowerCase();\n var polindromo = str.split('').reverse().join('');\n return polindromo === str;\n}", "function isPalindrome(word) {\n const reverse = word\n .split(\"\")\n .reverse()\n .join(\"\");\n return word === reverse;\n}", "function isPalindrome(string){\n string = string.toLowerCase()\n const charactersArr = string.split('')\n const validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('')\n\n let lettersArr = charactersArr.filter(char => validCharacters.includes(char))\n \n return lettersArr.join('') === lettersArr.reverse().join('')\n //if (lettersArr.join('') === lettersArr.reverse().join('')) return true; else return false\n}", "function palindrome(str) {\n //assign a front and a back pointer\n let front = 0\n let back = str.length - 1\n \n //back and front pointers won't always meet in the middle, so use (back > front)\n while (back > front) {\n //increments front pointer if current character doesn't meet criteria\n if ( str[front].match(/[\\W_]/) ) {\n front++\n continue\n }\n //decrements back pointer if current character doesn't meet criteria\n if ( str[back].match(/[\\W_]/) ) {\n back--\n continue\n }\n //finally does the comparison on the current character\n if ( str[front].toLowerCase() !== str[back].toLowerCase() ) return false\n front++\n back--\n }\n \n //if the whole string has been compared without returning false, it's a palindrome!\n return true\n \n }", "function palindrome(input) {\n let cleanedInput = input.split(\" \").join(\"\");\n let reversedCleanedInput = cleanedInput.split(\"\").reverse().join(\"\")\n if (cleanedInput == reversedCleanedInput) {\n return true\n } else {\n return false\n }\n}" ]
[ "0.86665916", "0.85041326", "0.84377784", "0.83795154", "0.8357682", "0.8331101", "0.8313112", "0.8280678", "0.8265561", "0.82470965", "0.8241521", "0.82032156", "0.8177709", "0.8172808", "0.81659514", "0.8157817", "0.8136953", "0.81322205", "0.81254363", "0.8121037", "0.81200314", "0.8103979", "0.8093258", "0.8091143", "0.80746067", "0.80588216", "0.80494636", "0.8048541", "0.80430895", "0.8012788", "0.800719", "0.8006416", "0.8000018", "0.7988869", "0.79827666", "0.7981883", "0.79721105", "0.79676306", "0.79647917", "0.79488635", "0.79464877", "0.7946254", "0.79227006", "0.7899855", "0.7899195", "0.78918254", "0.78849393", "0.7884778", "0.7883394", "0.7877167", "0.78770006", "0.7869639", "0.7858526", "0.7856898", "0.7852328", "0.7842549", "0.7841314", "0.7840266", "0.78383505", "0.78344244", "0.7828497", "0.7826033", "0.78246844", "0.782363", "0.7822337", "0.7811441", "0.78065", "0.78014517", "0.7788316", "0.7787166", "0.7781448", "0.7777815", "0.77696455", "0.77578807", "0.7754544", "0.7752904", "0.77490443", "0.774495", "0.7725378", "0.77240074", "0.7721081", "0.77179813", "0.7716142", "0.77130973", "0.77093107", "0.7700574", "0.7698607", "0.7691601", "0.76848614", "0.768312", "0.76816106", "0.7680789", "0.7678487", "0.7675178", "0.7668593", "0.7667271", "0.7666969", "0.76561415", "0.765614", "0.76559573", "0.7653362" ]
0.0
-1
Takes a string that is a sentence, and returns the number of words and average word length.
function sentenceInfo(sentence){ var numLetters = sentence.replace(/ /g,"").length; var numWords = sentence.split(" ").length; var avgWrdLength = numLetters/numWords; console.log("There are "+numWords+" words in this sentence, and the average word length is "+avgWrdLength+" words.") }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function findAvgWordLength(txt) {\n let words = getWords(txt);\n let count = 0;\n for (let i = 0; i < words.length; i++) {\n \tcount += words[i].length;\n }\n\n return count / words.length;\n}", "function averageWordLength (words) {\n var totalLength = words.join(\"\").length;\n return (totalLength / words.length).toFixed(2);\n}", "function getAverageWordLength(words){\n\t\n\tvar numWords = getNumNonEmptyStrings(words);\n\tvar lengthOfAllWords = 0;\n\n\tfor(var i = 0; i < words.length; i++){\n\t\tlengthOfAllWords += words[i].length;\n\t}\n\n\treturn lengthOfAllWords / numWords;\n}", "countWords(sentence) {\n \tvar sentenceWords = sentence.split(\" \");\n \treturn sentenceWords.length;\n }", "function countNumOfWords(str) {\n\n}", "function wordscount(str){\n\treturn str.split(/\\s+/).length;\n}", "function computeAverageLengthOfWords(word1, word2) {\n var wordAverage = (word1.length + word2.length) / 2\n return \"O comprimento médio de \" + word1 + \" e \" + word2 + \" é de \" + wordAverage + \" caracteres.\"\n}", "function wordCount(str) \n{ \n\treturn str.split(\" \").length;\n}", "function WordCount(str) {\n //split string into array\n var arr = str.split(\" \");\n\n //return array length\n return arr.length;\n\n}", "function countWords(input){\n var str = input.split(\" \");\n console.log(str.length);\n }", "function wordCount(str){\nreturn str.split(\" \").length;\n}", "function WordCount(str){\n return str.split(\" \").length;\n}", "function countWords(str) {\n return str.split(\" \").length;\n}", "function WordCount(str) {\n\n return str.split(\" \").length;\n}", "function WordCount(str) { \n return str.split(' ').length;\n }", "function WordCount(str) {\n\n\n return str.split(' ').length;\n\n}", "function countWords(str) {\n\treturn str.split(/\\s/).filter(val => val).length;\n}", "function wordCount(str) {\n\tvar results = str.split(\" \");\n\tconsole.log((results.length));\n\n}", "function countWords(stringValue) {\n\n let wordsCount = stringValue.split(' ');\n return wordsCount.length;\n\n}", "function wordLengths(string) {\n var acc = [];\n var words = string.split(\" \");\n for (var i = 0; i < words.length; i++) {\n acc.push(words[i].length);\n }\n return acc;\n}", "function WordCount(str) { \n var words = str.split(\" \");\n var sortedWords = words.sort(function(a,b) {\n if(a.length<b.length) return -1;\n else if(a.length>b.length) return 1;\n else return 0;\n });\n return sortedWords[0].length; // remove .length to return the word itself\n }", "function countWords(s) {\n s = s.replace(/(^\\s*)|(\\s*$)/gi, \"\");//exclude start and end white-space\n s = s.replace(/[ ]{2,}/gi, \" \");//2 or more space to 1\n s = s.replace(/\\n /, \"\\n\"); // exclude newline with a start spacing\n return s.split(' ').length;\n}", "function countWords(s){\n s = s.replace(/(^\\s*)|(\\s*$)/gi,\"\");//exclude start and end white-space\n s = s.replace(/\\n/g,\" \"); // exclude newline with a start spacing\n s = s.replace(/[ ]{2,}/gi,\" \");//2 or more space to 1\n if( s==\"\" || s == \" \") return 0\n return s.split(' ').length; \n}", "function count_words(str) {\n let matches = str.match(/[\\w\\d]+/gi);\n return matches ? matches.length : 0;\n}", "function countWords(str) {\n str = str.split(' ')\n console.log(str);\n console.log(str.length);\n}", "function wordCounter(text) {\r\n const summary = text.split(\" \");\r\n let wordCount = 0;\r\n for (let i = 0; i < summary.length; i++) {\r\n if (text[i] !== \" \") {\r\n wordCount++;\r\n }\r\n }\r\n return wordCount;\r\n\r\n}", "function countWords(text) {\n return text.split(' ').length;\n}", "function _wordSizes(str) {\n const newStr = str.toLowerCase().split(\"\").filter(el => \"abcdefghijklmnopqrtstuvwxyz0123456789 \".includes(el));\n console.log(newStr.join(\"\"));\n return _letterCounter(newStr.join(\"\"));\n}", "function solution(S) {\n // we need regex\n // First, we seperate everything by sentences, this includes delimiters (needs to be removed)\n var sentArr = S.match(/[^\\.!\\?]+[\\.!\\?]+/g);\n // Next we clean up each sentence. Remove trailing spaces. Convert multiple sequential spaces to one\n sentArr = sentArr.map(item => {\n return item.trim().replace(/ +/g, \" \");\n });\n // Next we clean up any edge cases \"Save time .\" should be \"Save time.\"\n\n console.log(sentArr);\n // Next, we count number of spaces. If there's 2 spaces, that means there's 3 words\n var result = 0;\n for (let i = 0; i < sentArr.length; i++) {\n let numWordsInSentence = sentArr[i].split(\" \").length;\n if (result < numWordsInSentence) {\n result = numWordsInSentence;\n }\n }\n return result;\n}", "function wordSizes(sentence) {\n let words = sentence.split(' ');\n let wordSizes = {};\n let i;\n let size;\n\n for (i = 0; i < words.length; i += 1) {\n size = words[i].length.toString();\n \n if (size === '0') {\n continue;\n }\n \n wordSizes[size] = wordSizes[size] || 0;\n wordSizes[size] += 1;\n }\n\n return wordSizes;\n}", "function countWords(string){\n const wordArray = string.trim().split(' ')\n return wordArray.filter(word => word !== \"\").length\n }", "function wordLengths(str) {\n let result = str.split(' ').reduce( (acc, word) => {\n acc[word] = word.length;\n return acc;\n }, {})\n return result;\n}", "function longWordCount(string) {\n var words = string.split(\" \");\n var count = 0;\n\n for (var i = 0; i < words.length; i++) {\n if (words[i].length > 7) {count += 1}\n }\n return count;\n}", "function longestWord(sentence){\n let words = sentence.split(\" \");\n let longest = 0;\n for (let i = 0; i < words.length; i++) {\n if(longest < words[i].length){\n longest = words[i].length;\n } \n }\n return longest;\n}", "function Words(w) {\n\tvar arr = w.split(\" \");\n\treturn arr.length;\n}", "function getFirstWordLength(string) {\r\n return string.match(/\\w+/)[0].length;\r\n }", "function longWordCount(string) {\n var stringSplit = string.split(\" \");\n var numberOfWordsLargerThanSevenCharacters = 0;\n //console.log(\"Check 1: The split words are: \" + stringSplit);\n for (var i = 0; i < stringSplit.length; i++) {\n if (stringSplit[i].length > 7) {\n numberOfWordsLargerThanSevenCharacters += 1;\n }\n }\n return numberOfWordsLargerThanSevenCharacters;\n}", "function averageWordLength(wordsArr) {\n let a = [],\n totall = 0;\n if (wordsArr.length == 0) return null;\n else {\n wordsArr.forEach(i => {\n let sum = 0;\n sum += i.length;\n totall += sum;\n a.push(sum);\n });\n return (totall / a.length);\n }\n}", "function countWords(keyword){\n return (keyword.replace(/(^\\s*)|(\\s*$)/gi,\"\").replace(/[ ]{2,}/gi,\" \").replace(/\\n /,\"\\n\").split(' ').length);\n}", "function wordsCounter(text){\n\n if(text === ''){\n return 0;\n }else if(!text.includes(' ')){\n return 1;\n }else if(text.includes(' ')){\n return spaceCount(text) + 1;\n }\n}", "function WordCount(str) {\n\n // code goes here \n arr1 = str.split(\" \");\n\n // alert(arr1.length);\n return arr1.length;\n\n\n}", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "function getFirstWordLength(string) {\n return string.match(/\\w+/)[0].length;\n }", "countBigWords(input) {\n // code goes here\n //break string into separate words\n let words = input.split(\" \");\n //create a count\n let counter = 0;\n //iterate through each word in the string\n for (let i = 0; i < words.length; i++) {\n //check if each word's length is greater that 6\n //if it is increase the counter by 1\n if (words[i].length > 6) {\n counter++;\n }\n }\n\n //return the counter\n\n return counter;\n }", "function wordLengths(str) {\n\treturn str.split(' ').map(function (s) {\n\t\treturn stringWidth(s);\n\t});\n}", "function wordLengths(str) {\n\treturn str.split(' ').map(function (s) {\n\t\treturn stringWidth(s);\n\t});\n}", "function wordLengths(str) {\n\treturn str.split(' ').map(function (s) {\n\t\treturn stringWidth(s);\n\t});\n}", "countWords(str) {\n //exclude start and end white-space\n str = str.replace(/(^\\s*)|(\\s*$)/gi,\"\");\n //convert 2 or more spaces to 1 \n str = str.replace(/[ ]{2,}/gi,\" \");\n // exclude newline with a start spacing \n str = str.replace(/\\n /,\"\\n\");\n\n return str.split(' ').length;\n }", "function countWords(str) {\n str = str.replace(/(^\\s*)|(\\s*$)/gi, \"\");\n str = str.replace(/[ ]{2,}/gi, \" \");\n str = str.replace(/\\n /, \"\\n\");\n return str.split(' ').length;\n }", "function countCensoredWords(sentence, words){\n if (typeof sentence === 'string' && typeof words === 'object'){\n const results = {}\n for (const key of words){\n results[key] = 0\n }\n results.total = 0\n sentence.toLowerCase().replace(/[^a-z\\s]/g, '').split(' ').map(item => {\n words.map(word => {\n if (item === word){\n results[word]++\n results.total++\n }\n })\n })\n return results\n } else {\n console.log('Please provide a string as the first parameter and a array as the second parameter')\n }\n}", "function countAnimals(sentence) {\n return sentence.split(' ').map(a => +a).filter(a => !isNaN(a)).reduce((a, b) => a + b, 0);\n}", "function wordSizes(str) {\n let obj = {};\n if (str.length === 0) return obj;\n let words = str.split(\" \");\n for (let index = 0; index < words.length; index++) {\n let word_size = getLength(words[index]);\n obj[word_size] = obj[word_size] || 0;\n obj[word_size] += 1;\n }\n return obj;\n}", "function wordCount(){\n var wom = $(\"#essay\").html().replace( /[^a-z0-9\\s]/g, \"\" ).split( /\\s+/ ).length;\n $(\"#demo11\").html(wom + \" word count\")\n}", "function getWordCounts(inputString){\n if(inputString !== \"\"){\n var words = inputString.split(' ');\n words.forEach(function(w) {\n if (!wordDict[w]) {\n wordDict[w] = 0;\n }\n wordDict[w] += 1;\n });\n if(showStats===1){\n dispatch(newDictionary(wordDict));\n }\n return wordDict;\n }\n \n}", "function getlength(word) {return word.length }", "function getFirstWordLength( string ) {\n\t return string.match( /\\w+/ )[ 0 ].length\n\t }", "function findNumberOfWords(string, searchString) {\n return string.match(new RegExp(searchString, \"g\")).length;\n}", "function countWords(text) {\n return tokenize.words()(text).length;\n}", "function wordLengths(str) {\n var word = str.split(' ');\n return map(word,function(element, i){\n return element.length\n })\n }", "function wordLengths(str) {\n if (str === undefined || str === '') return [];\n return str.split(' ').map(word => `${word} ${word.length}`);\n}", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function getFirstWordLength( string ) {\n return string.match( /\\w+/ )[ 0 ].length\n }", "function mostWordsFound(sentences) {\n let maxWordCount = -Infinity;\n\n for (let i = 0; i < sentences.length; i++) {\n let currentSentence = sentences[i];\n let wordCount = 0;\n\n for (let j = 0; j < currentSentence.length; j++) {\n if (currentSentence[j] == \" \" || j == currentSentence.length - 1) {\n wordCount++;\n }\n }\n\n maxWordCount = Math.max(wordCount, maxWordCount);\n }\n\n return maxWordCount;\n}", "countBigWords(input) {\n // Split the input\n let arr = input.split(\" \");\n // Start counter from 0\n let count = 0;\n //if array contains more than 6 lettes word, add 1 otherwise neglect word and keep moving further\n //until whole string input is completed\n arr.forEach(word =>{\n if (word.length > 6){\n count++;\n }\n \n });\n\n // return the count of all words with more than 6 letters\n return count;\n }", "function wordSizesTwo(string) {\n let arr = string.toLowerCase().split(' ');\n let obj = {};\n let word = 'hy';\n let word_length = string => {\n let length = 0;\n for (let char in string) {\n if (string[char] < 'a') {\n continue;\n }\n length += 1;\n }\n return length;\n }\n for (let i in arr) {\n word = arr[i];\n word_ln = word_length(word);\n if (String(word_ln) in obj) {\n obj[String(word_ln)] += 1;\n continue;\n }\n if (word_ln === 0) {\n continue;\n }\n obj[String(word_ln)] = 1;\n }\n return obj;\n}", "function findLongestWordLength(str) {\n let length = 0;\n let arr = str.split(\" \");\n for(let i = 0;i<arr.length;i++)\n length = (length<arr[i].length ? arr[i].length:length)\n return length;\n}", "function getWordCounts(text) {\n\n}", "function findLongestWordLength(str) {\n let num = 0;\n const split = str.split(' ');\n for (let i = 0; i < split.length; i++) {\n if (split[i].length > num) {\n num = split[i].length\n }\n }\n return num;\n}", "function findShort(s){\nvar split = s.split(' ')\ncounter = 100\n\nfor (var i=0; i<split.length; i++){\n if (split[i].length < counter){\n \tcounter = split[i].length\n word = split[i]\n \t}\n }\n return counter;\n}", "function getLenght(word) {\n return word.length\n}", "function getLengthOfWord(word) {\r\n return word.length;\r\n}", "function longestWord(text) {\n let sentence = text.split(' ');\n let maxLength = 0;\n for(let i = 0; i < sentence.length; i++) {\n if(sentence[i].length > maxLength){\n maxLength = sentence[i].length;\n }\n }\n return maxLength;\n}", "function calculateAccuracy() {\nvar typedText = input.value;\nvar errorCount = 0;\nfor (var i = 0; i < typedText.length; i++) {\nif (typedText[i] !== currentSentence[i]) {\nerrorCount++;\n}\n}\nreturn ((currentSentence.length - errorCount) / currentSentence.length * 100).toFixed(2);\n}", "function findShort(s){\n\n let array = s.split(\" \")\n let arraySmallToLarge = array.sort((a, b) => a.length - b.length)\n let smallestWordLength = arraySmallToLarge[0].length\n \n return smallestWordLength\n\n}", "function getFirstWordLength( string ) { // 5726\n return string.match( /\\w+/ )[ 0 ].length // 5727\n } // 5728", "function simpleScore(word) {\n\n let simplestScore = word.length;\n return simplestScore;\n\n}", "function findLongestWordLength(str) {\n let split = str.split(' ')\n let result = 0\n for (let i=0; i< split.length; i++) {\n if(split[i].length > result) {\n result = split[i].length\n }\n }\n return result\n}", "function wordcount() {\n var matches = writing_data().match(/\\w\\w+/g);\n if(!matches) return 0;\n return matches.length;\n}", "function countSentences(text) {\n return tokenizeEnglish.sentences()(text).length;\n}", "function countWord(word) {\n if (typeof word !== 'string'){\n return 'error input bukan string';\n } else if (word === \"\") {\n return '';\n } else {\n let count = 1\n for (let j = 0; j < word.length; j++) {\n if (word[j] === ' ' && word[j+1] !== ' ') {\n count++\n }\n }\n if (word === '') return '' \n else return count\n }\n}", "function Tut_CountWordsInHTML(strHTML)\n{\n\t//Not valid string?\n\tif (String_IsNullOrWhiteSpace(strHTML))\n\t\treturn 0;\n\n\t//create a fake div\n\tvar div = document.createElement(\"div\");\n\t//set the text in this div\n\tdiv.innerHTML = strHTML; // SAFE BY SANITIZATION\n\t// Get text\n\tvar text = div.textContent || div.innerText || div.innerHTML || \"\"; // SAFE\n\t//now count the words\n\tvar words = text.match(__NEMESIS_REGEX_COUNT_WORDS);\n\t//return the count\n\treturn words ? words.length : 0;\n}", "function findLargestWord(sentence) {\n\n let words = sentence.split(' ');\n let largestWord = words[0];\n\n for (let i =1; i< words.length; i++) {\n if(words[i].length > largestWord.length) {\n largestWord = words[i];\n }\n }\n\n return largestWord;\n}", "function ocurrenceCount(string, word) {\n return string.split(word).length;\n}", "function countWords(str) {\n // your code here\n var x = {};\n if (str !== \"\") {\n var arr = str.split(\" \");\n for (var i = 0; i < arr.length; i++) {\n if (typeof x[arr[i]] != \"undefined\") {\n x[arr[i]] += 1;\n } else {\n x[arr[i]] = 1;\n }\n }\n } else {\n return x = {};\n }\n return x;\n }", "function findShort(s){\r\n const splitWords = s.split(' ');\r\n const numArray = [];\r\n splitWords.map((word) => {\r\n numArray.push(word.length);\r\n })\r\n numArray.sort(function(a, b){return a - b});\r\n return numArray[0];\r\n}", "function calculateScore(word) {\n\n var strength = 1;\n // Find letter strength\n for (i = 0; i < word.length; i++) {\n strength = strength * (gameState['strength'][\n word.charAt(i)] + 1);\n }\n\n return (word.length * strength);\n }", "function getlength(word) {\r\n return word.length;\r\n\r\n}", "function countWords() {\n //get display location into variable.\n var ul = document.getElementById(\"display\", \"stats\");\n\n //remove any unordered list in DOM.\n while (ul.firstChild) ul.removeChild(ul.firstChild);\n\n //turn user input to UpperCase since all gigVoice keys are upper case. For easy matching for now.\n //will need to find a fix for apostrophe characters in a word.\n var w = document.getElementById(\"searchInput\").value.toUpperCase();\n\n //remove end spacing\n w = w.replace(/(^\\s*)|(\\s*$)/gi, \"\");\n\n //gather 2 or more spacing to 1\n w = w.replace(/[ ]{2,}/gi, \" \");\n\n //exclude new line with start spacing\n w = w.replace(/\\n /, \"\\n\");\n\n //split string\n w = w.split(' ')\n return voiceCheck(w);\n\n }", "function getLength(word) {\n return word.length;\n}", "function getWordCount(string, word) {\n var index = 0, count = 0;\n while(index < string.length) {\n var wordIndex = string.indexOf(word, index);\n if(wordIndex !== -1) {\n count++;\n index = wordIndex + 1;\n } else {\n index++;\n }\n }\n return count;\n}", "function findLongestWordLength(str) {\n\tlet String_sp = str.split(\" \");\n\tlet max_count = 0;\n\tfor (var i = 0; i < String_sp.length; i++) {\n\t\tif (String_sp[i].length > max_count) {\n\t\t\tmax_count = String_sp[i].length;\n\t\t}\n\t}\n\treturn max_count;\n}", "function findLongestWord(sentence) {\n var sentence = sentence.split(\" \");\n var longest = 0;\n var word = null;\n for (var i = 0; i < sentence.length; i++) {\n if (longest < sentence[i].length) {\n longest = sentence[i].length;\n word = sentence[i];\n }\n }\n return word;\n }" ]
[ "0.7539853", "0.7374321", "0.72900426", "0.72513944", "0.7120894", "0.7067416", "0.70612097", "0.70395035", "0.7038953", "0.7012962", "0.700803", "0.70080245", "0.6939312", "0.69013464", "0.6893938", "0.68596846", "0.6774027", "0.6746693", "0.6745428", "0.6714068", "0.6687568", "0.6614431", "0.6586723", "0.65316546", "0.65100056", "0.6507134", "0.6506724", "0.6458628", "0.6448932", "0.64416885", "0.643824", "0.6403338", "0.6388462", "0.6382913", "0.6380447", "0.6320032", "0.6303573", "0.63019747", "0.63005894", "0.6300422", "0.6291309", "0.627662", "0.627662", "0.627662", "0.6269974", "0.62696725", "0.62696725", "0.62696725", "0.6266891", "0.6259697", "0.62585604", "0.624469", "0.6233477", "0.62090164", "0.6203123", "0.61950547", "0.61873007", "0.6178809", "0.61637455", "0.6153751", "0.6153098", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6150363", "0.6146005", "0.6123518", "0.6121922", "0.61138964", "0.60793823", "0.6065849", "0.60577524", "0.6055156", "0.60539746", "0.604067", "0.60359913", "0.60287005", "0.60282105", "0.60254055", "0.60248893", "0.60142994", "0.5996096", "0.59923905", "0.59873027", "0.5982721", "0.59814084", "0.59788567", "0.5976459", "0.5971736", "0.5971662", "0.5971263", "0.5971258", "0.59643376", "0.5955504", "0.5942204" ]
0.82989645
0
create prototype of Child, that created with Parent prototype (without making Child.prototype = new Parent()) __proto__ < __proto__ ^ ^ | | Parent Child
function Surrogate(){}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function applyPrototype(parent,child){\n\tchild.prototype = Object.create(parent.prototype);\n\tchild.prototype.constructor = child;\n}", "function subclass(child, parent) {\n child.prototype.__proto__ = parent.prototype;\n}", "function inheritPrototype(childObject, parentObject) {\n var copyOfParent = Object.create(parentObject.prototype); //ECMA5 compatible\n copyOfParent.constructor = childObject;\n childObject.prototype = copyOfParent;\n}", "function inherts(child , parent) {\n child.prototype = Object.create(parent.prototype);\n child.prototype.constructor = child;\n}", "function extend(Child, Parent){\n Child.prototype = Object.create(Parent.prototype);\n Child.prototype.constructor = Child;\n }", "function inheritPrototype(childObject, parentObject) {\n // As discussed above, we use the Crockford’s method to copy the properties and methods from the parentObject onto the childObject\n // So the copyOfParent object now has everything the parentObject has \n var copyOfParent = Object.create(parentObject.prototype);\n\n //Then we set the constructor of this new object to point to the childObject.\n // Why do we manually set the copyOfParent constructor here, see the explanation immediately following this code block.\n copyOfParent.constructor = childObject;\n\n // Then we set the childObject prototype to copyOfParent, so that the childObject can in turn inherit everything from copyOfParent (from parentObject)\n childObject.prototype = copyOfParent;\n}", "function extend(Child, Parent){\n var F = function(){};\n F.prototype = Parent.prototype;\n Child.prototype = new F();\n Child.prototype.constructor = Child;\n}", "function extend(Child,Parent)\n{\n var f=function(){};\n f.prototype=Parent.prototype;\n Child.prototype=new f();\n Child.prototype.constructor=Child;\n Child.uber=Parent.prototype;\n}", "function extend(Child, Parent) {\n var F = function(){};\n F.prototype = Parent.prototype;\n Child.prototype = new F();\n Child.prototype.constructor = Child;\n Child.uber = Parent.prototype;\n}", "function extend(Child, Parent) {\n var F = function(){};\n F.prototype = Parent.prototype;\n Child.prototype = new F();\n Child.prototype.constructor = Child;\n Child.uber = Parent.prototype;\n}", "function Child() {}", "function Child() {}", "function extend(parent, child){\n child.prototype= Object.create(parent.prototype)\n child.prototype.constructor=child\n }", "function inheritsFrom (child, parent) {\n child.prototype = Object.create(parent.prototype);\n //can be used for clone\n}", "function extend(Child, Parent) {\n Child.prototype = inherit(Parent.prototype)\n Child.prototype.constructor = Child\n Child.parent = Parent.prototype\n}", "function inheritFrom(parentConstructor, childConstructor, prototypeProps, constructorProps) {\n\t // Create a child constructor if one wasn't given\n\t if (childConstructor == null) {\n\t childConstructor = function() {\n\t parentConstructor.apply(this, arguments)\n\t }\n\t }\n\t\n\t // Make sure the new prototype has the correct constructor set up\n\t prototypeProps.constructor = childConstructor\n\t\n\t // Base constructors should only have the properties they're defined with\n\t if (parentConstructor !== Concur) {\n\t // Inherit the parent's prototype\n\t inherits(childConstructor, parentConstructor)\n\t childConstructor.__super__ = parentConstructor.prototype\n\t }\n\t\n\t // Add prototype properties - this is why we took a copy of the child\n\t // constructor reference in extend() - if a .constructor had been passed as a\n\t // __mixins__ and overitten prototypeProps.constructor, these properties would\n\t // be getting set on the mixed-in constructor's prototype.\n\t extend(childConstructor.prototype, prototypeProps)\n\t\n\t // Add constructor properties\n\t extend(childConstructor, constructorProps)\n\t\n\t return childConstructor\n\t}", "function makeChild(objectName, parentName) {\n\teval(objectName + \".prototype = Object.create(\" + parentName + \".prototype);\" + \n\t\t\tobjectName + \".prototype.constructor = \" + objectName + \";\");\n}", "function inheritsFrom(child, parent){\nchild.prototype = Object.create(parent.prototype);\n}", "function inherit(proto) {\n function F() {\n };\n F.prototype = proto;\n var object = new F;\n return object;\n }", "function inherit(parent, child) {\n const obj = Object.create(child.prototype)\n child.prototype = Object.assign({}, parent.prototype, obj)\n parent.constructor = child\n}", "function $inherits(child, parent) {\n if (child.prototype.__proto__) {\n child.prototype.__proto__ = parent.prototype;\n } else {\n function tmp() {};\n tmp.prototype = parent.prototype;\n child.prototype = new tmp();\n child.prototype.constructor = child;\n }\n}", "function create(proto) {\n function Ctor() {}\n Ctor.prototype = proto;\n return new Ctor();\n }", "function inheritPrototype(subType, superType){\n var copyOfSuperType = Object.create(superType.prototype) // create object\n copyOfSuperType.constructor = subType // augment object\n subType.prototype = copyOfSuperType // assign object\n}", "function inheritPrototype(subType, superType){\n var prototype = object(superType.prototype); //create object\n prototype.constructor = subType; //augment object\n subType.prototype = prototype; //assign object\n}", "function peg$subclass(child,parent){function ctor(){this.constructor=child}ctor.prototype=parent.prototype;child.prototype=new ctor}", "function inheritsFrom(child, parent) {\n child.prototype = Object.create(parent.prototype);\n}", "function createObject(proto) {\n var f = function () { };\n f.prototype = proto;\n return new f();\n }", "function extend(child, parent, _protoFn) {\n var i;\n parent = isArray(parent) ? parent : [parent];\n var _copyProtoChain = function (focus) {\n var proto = focus.__proto__;\n while (proto != null) {\n if (proto.prototype != null) {\n for (var j in proto.prototype) {\n if (proto.prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) {\n child.prototype[j] = proto.prototype[j];\n }\n }\n proto = proto.prototype.__proto__;\n }\n else {\n proto = null;\n }\n }\n };\n for (i = 0; i < parent.length; i++) {\n for (var j in parent[i].prototype) {\n if (parent[i].prototype.hasOwnProperty(j) && !child.prototype.hasOwnProperty(j)) {\n child.prototype[j] = parent[i].prototype[j];\n }\n }\n _copyProtoChain(parent[i]);\n }\n var _makeFn = function (name, protoFn) {\n return function () {\n for (i = 0; i < parent.length; i++) {\n if (parent[i].prototype[name]) {\n parent[i].prototype[name].apply(this, arguments);\n }\n }\n return protoFn.apply(this, arguments);\n };\n };\n var _oneSet = function (fns) {\n for (var k in fns) {\n child.prototype[k] = _makeFn(k, fns[k]);\n }\n };\n if (arguments.length > 2) {\n for (i = 2; i < arguments.length; i++) {\n _oneSet(arguments[i]);\n }\n }\n return child;\n }", "function inheritPrototype(subType, superType) {\t // 0\n\t \t\t\t\tvar prototype = object(superType.prototype); // 1 \n\t \t\t\t\tprototype.constructor = subType; \t\t\t\t // 2\n\t \t\t\t\tsubType.prototype = prototype;\t\t\t\t\t // 3\n\t \t\t\t}", "function peg$subclass(child,parent){function ctor(){this.constructor=child;}ctor.prototype=parent.prototype;child.prototype=new ctor();}", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function baseCreate(prototype) {\n if (!isObject(prototype)) return {};\n if (nativeCreate) return nativeCreate(prototype);\n var Ctor = ctor();\n Ctor.prototype = prototype;\n var result = new Ctor;\n Ctor.prototype = null;\n return result;\n }", "function extend2(Child, Parent) {\n var p = Parent.prototype;\n var c = Child.prototype;\n for (var i in p) {\n c[i] = p[i]; }\n }", "function make (proto) {\n var o = Object.create(proto);\n var args = [].slice.call(arguments, 1);\n args.unshift(o);\n extend.apply(null, args);\n return o;\n }", "function inherit(childClass, parentClass) {\r\n childClass.prototype = Object.create(parentClass.prototype);\r\n childClass.prototype.constructor = childClass;\r\n}", "function createObject(proto) {\n\t\tvar f = function() {};\n\t\tf.prototype = proto;\n\t\treturn new f();\n\t}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function createObject(proto) {\n\tvar f = function() {};\n\tf.prototype = proto;\n\treturn new f();\n}", "function inherit(Child, Parent) {\n\t\tvar Inheritance = function () { };\n\t\tInheritance.prototype = Parent.prototype;\n\t Child.prototype = new Inheritance();\n\t Child.prototype.constructor = Child;\n\t Child.superClass = Parent.prototype;\n\t}", "function extend(protoProps) {\n var parent = this;\n var child;\n var args = [].slice.call(arguments);\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n child = function () {\n return parent.apply(this, arguments);\n };\n }\n\n // Add static properties to the constructor function from parent\n assign(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n var Surrogate = function () { this.constructor = child; };\n Surrogate.prototype = parent.prototype;\n child.prototype = new Surrogate();\n\n // set prototype level objects\n child.prototype._derived = assign({}, parent.prototype._derived);\n child.prototype._deps = assign({}, parent.prototype._deps);\n child.prototype._definition = assign({}, parent.prototype._definition);\n child.prototype._collections = assign({}, parent.prototype._collections);\n child.prototype._children = assign({}, parent.prototype._children);\n child.prototype._dataTypes = assign({}, parent.prototype._dataTypes || dataTypes);\n\n // Mix in all prototype properties to the subclass if supplied.\n if (protoProps) {\n var omitFromExtend = [\n 'dataTypes', 'props', 'session', 'derived', 'collections', 'children'\n ];\n args.forEach(function processArg(def) {\n if (def.dataTypes) {\n forEach(def.dataTypes, function (def, name) {\n child.prototype._dataTypes[name] = def;\n });\n }\n if (def.props) {\n forEach(def.props, function (def, name) {\n createPropertyDefinition(child.prototype, name, def);\n });\n }\n if (def.session) {\n forEach(def.session, function (def, name) {\n createPropertyDefinition(child.prototype, name, def, true);\n });\n }\n if (def.derived) {\n forEach(def.derived, function (def, name) {\n createDerivedProperty(child.prototype, name, def);\n });\n }\n if (def.collections) {\n forEach(def.collections, function (constructor, name) {\n child.prototype._collections[name] = constructor;\n });\n }\n if (def.children) {\n forEach(def.children, function (constructor, name) {\n child.prototype._children[name] = constructor;\n });\n }\n assign(child.prototype, omit(def, omitFromExtend));\n });\n }\n\n // Set a convenience property in case the parent's prototype is needed\n // later.\n child.__super__ = parent.prototype;\n\n return child;\n}", "constructor() {\n super(...arguments);\n var prototype = Object.getPrototypeOf(this);\n }", "constructor() {\n super(...arguments);\n var prototype = Object.getPrototypeOf(this);\n }", "function ParentConstructor() {\n}", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function create(prototype, props) {\n var result = baseCreate(prototype);\n if (props) extendOwn(result, props);\n return result;\n }", "function ctor() {\n this.constructor = child;\n }", "function inherit(p) {\n if (p == null) throw TypeError();\n if (Object.create) {\n return Object.create(p);\n }\n let t = typeof p;\n if (t!== \"object\" && t !== \"function\") throw TypeError();\n function f() {};\n f.prototype = p;\n return new f();\n}", "function inherits(childConstructor, parentConstructor) {\n\t var F = function() {}\n\t F.prototype = parentConstructor.prototype\n\t childConstructor.prototype = new F()\n\t childConstructor.prototype.constructor = childConstructor\n\t return childConstructor\n\t}", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "constructor() {\n var prototype = Object.getPrototypeOf(this);\n }", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() {\n this.constructor = child;\n }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "static inherit(p) {\n if (p == null) throw TypeError('p must be a non-null object'); // p must be a non-null object\n if (Object.create) // If Object.create() is defined...\n return Object.create(p); // then just use it.\n let t = typeof p; // Otherwise do some more type checking\n if (t !== \"object\" && t !== \"function\") throw TypeError('p must be object or function');\n function f() {}; // Define a dummy constructor function.\n f.prototype = p; // Set its prototype property to p.\n return new f(); // Use f() to create an \"heir\" of p.\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n}", "function getPrototypeOf(prototype) {\n return prototype.__proto__;\n }", "function getPrototypeOf(prototype) {\n return prototype.__proto__;\n }", "function getPrototypeOf(prototype) {\n return prototype.__proto__;\n }", "function getPrototypeOf(prototype) {\n return prototype.__proto__;\n }", "function getPrototypeOf(prototype) {\n return prototype.__proto__;\n }", "function extend(protoProps) {\n /*jshint validthis:true*/\n var parent = this;\n var child;\n\n // The constructor function for the new subclass is either defined by you\n // (the \"constructor\" property in your `extend` definition), or defaulted\n // by us to simply call the parent's constructor.\n if (protoProps && protoProps.hasOwnProperty('constructor')) {\n child = protoProps.constructor;\n } else {\n child = function () {\n return parent.apply(this, arguments);\n };\n }\n\n // Add static properties to the constructor function from parent\n assign(child, parent);\n\n // Set the prototype chain to inherit from `parent`, without calling\n // `parent`'s constructor function.\n var Surrogate = function () { this.constructor = child; };\n Surrogate.prototype = parent.prototype;\n child.prototype = new Surrogate();\n\n // set prototype level objects\n child.prototype._derived = assign({}, parent.prototype._derived);\n child.prototype._deps = assign({}, parent.prototype._deps);\n child.prototype._definition = assign({}, parent.prototype._definition);\n child.prototype._collections = assign({}, parent.prototype._collections);\n child.prototype._children = assign({}, parent.prototype._children);\n child.prototype._dataTypes = assign({}, parent.prototype._dataTypes || dataTypes);\n\n // Mix in all prototype properties to the subclass if supplied.\n if (protoProps) {\n var omitFromExtend = [\n 'dataTypes', 'props', 'session', 'derived', 'collections', 'children'\n ];\n for(var i = 0; i < arguments.length; i++) {\n var def = arguments[i];\n if (def.dataTypes) {\n forOwn(def.dataTypes, function (def, name) {\n child.prototype._dataTypes[name] = def;\n });\n }\n if (def.props) {\n forOwn(def.props, function (def, name) {\n createPropertyDefinition(child.prototype, name, def);\n });\n }\n if (def.session) {\n forOwn(def.session, function (def, name) {\n createPropertyDefinition(child.prototype, name, def, true);\n });\n }\n if (def.derived) {\n forOwn(def.derived, function (def, name) {\n createDerivedProperty(child.prototype, name, def);\n });\n }\n if (def.collections) {\n forOwn(def.collections, function (constructor, name) {\n child.prototype._collections[name] = constructor;\n });\n }\n if (def.children) {\n forOwn(def.children, function (constructor, name) {\n child.prototype._children[name] = constructor;\n });\n }\n assign(child.prototype, omit(def, omitFromExtend));\n }\n }\n\n // Set a convenience property in case the parent's prototype is needed\n // later.\n child.__super__ = parent.prototype;\n\n return child;\n}", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }", "function peg$subclass(child, parent) {\n function ctor() { this.constructor = child; }\n ctor.prototype = parent.prototype;\n child.prototype = new ctor();\n }" ]
[ "0.7548634", "0.7137564", "0.69749093", "0.6892633", "0.6832302", "0.67413795", "0.67216116", "0.66736656", "0.66182935", "0.66182935", "0.65928453", "0.65928453", "0.6586049", "0.6561189", "0.6554661", "0.6533801", "0.6530078", "0.65265024", "0.6518368", "0.6509167", "0.6498614", "0.64666015", "0.6424683", "0.6423758", "0.63913995", "0.63620275", "0.63501817", "0.63445693", "0.634313", "0.63125974", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.62895346", "0.6266541", "0.6209868", "0.6170354", "0.61664295", "0.61523736", "0.61523736", "0.61523736", "0.61523736", "0.61523736", "0.61523736", "0.61523736", "0.61523736", "0.6126319", "0.61063206", "0.6095016", "0.6095016", "0.6093544", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6062404", "0.6035928", "0.60243064", "0.5957981", "0.5949219", "0.5941029", "0.5941029", "0.5935106", "0.5935106", "0.5935106", "0.5929601", "0.59198725", "0.5910854", "0.5910854", "0.5908716", "0.5908096", "0.5903574", "0.5903574", "0.5903574", "0.5903574", "0.5903574", "0.5903574", "0.58942175", "0.58942175", "0.5888646", "0.5888646", "0.5888646", "0.5884577", "0.5871149", "0.5871149", "0.5871149", "0.5871149", "0.5871149", "0.5871149", "0.5871149", "0.5871149", "0.5871149" ]
0.0
-1
method to render the train schedule call
function renderTrains () { $('tbody').empty(); // looping through the array of trains for (var i=0; i < trainSchedule.length; i++) { // set the row in html var row = $("<tr>"); // set the first column to populate train name var td1 = $("<td>").text(trainSchedule[i].trainName); // set the second column to populate train destination var td2 = $("<td>").text(trainSchedule[i].destination); // set a start variable of the first train of the day var tStart = trainSchedule[i].firstTrainTime; // set the frequency for each train var tFrequency = trainSchedule[i].frequency // convert the start time to minutes and make it in the past so you can analyze it without errors var tStartConverted = moment(tStart, "HH:mm").subtract(1, 'years') // sets the current time var currentTime = moment() // calculates the difference in time from the start time to now var diffTime = moment().diff(moment(tStartConverted), "minutes") // calculates the remainder of the difference in time divided by the frequency of the trains var tRemainder = diffTime % tFrequency // calculates the time remaining until the next train var tMinutesTilTrain = tFrequency - tRemainder // sets the time the next train will arrive var nextTrain = moment().add(tMinutesTilTrain, "minutes").format('HH:mm') // populates the third column with frequency of train arrival var td3 = $('<td>').text(tFrequency) // populates the fourth column with the time the next train will arrive var td4 = $('<td>').text(nextTrain) // populates the fifth column with the time until the next train arrives var td5 = $('<td>').text(tMinutesTilTrain) //append all columns to the table row.append(td1).append(td2).append(td3).append(td4).append(td5); $("tbody").append(row); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function render() {\n\tconsole.log(\"Re-rendering\")\n\tif (selectedTopicID != \"\" && selectedTopicID != null) {\n\t\tdocument.title = \"Work Log - \" + topicsDictionary[selectedTopicID].name;\n\t\t$(\"#time-elapsed-header\").html(formatCounter(topicsDictionary[selectedTopicID].time));\n\t}\n\trenderTopics();\n\trenderEvents();\n}", "start() {\n this.model = DaySchedulerModel;\n this.view = DaySchedulerView;\n\n this.model.start();\n\n this.view.currentDayText.show(this.model.getTodayText());\n\n this.view.eventBlocks.setCallbacks(\n () => DaySchedulerController.updateSchedule(),\n (hourBlock, event) => DaySchedulerController.addEvent(hourBlock, event)\n );\n this.view.eventBlocks.show();\n }", "display(){\n this.htmlBuilder.build();\n this.displayCityName();\n this.displayTodayWeather();\n this.displayWeekWeather();\n this.displayTimeSlots();\n }", "function renderStart() {\n generateStart();\n }", "render() \n\t{\n\t\treturn (\n\t\t\t<div>\n\t\t\t{/* The Body Content of the MeetingTime, currently displays just as text */}\n\t\t\t\t{this.state.type + \" | \" +\n\t\t\t\tthis.state.dates + \" | \" +\n\t\t\t\tthis.state.instructor + \" | \" +\n\t\t\t\tthis.state.startTime + \" to \" + this.state.endTime}\n\t\t\t</div>\n\t\t);\n\t}", "function addTrainSched(train) {\n clearTable();\n console.log(train);\n\n for (var i = 0; i < train.length; i++) {\n var trainRow = $(\"<tr>\");\n var trainListName = $(\"<td>\");\n var trainListDest = $(\"<td>\");\n var trainListFreq = $(\"<td>\");\n var trainListNextArrival = $(\"<td>\");\n var trainListMinAway = $(\"<td>\");\n\n //calculate when the next run time will occur\n var diffTime = moment().diff(moment(train[i].initialTime),\"minutes\");\n var timesRun = Math.ceil(diffTime/train[i].frequency);\n var nextTime = moment(train[i].initialTime).add(timesRun*train[i].frequency,\"minutes\");\n var timeTillNext = moment(nextTime).diff(moment(), \"minutes\");\n\n //Get Train Information\n trainListName.text(train[i].trainName);\n trainListDest.text(train[i].destination);\n trainListFreq.text(train[i].frequency);\n trainListNextArrival.text(nextTime.format(\"HH:mm\"));\n trainListMinAway.text(timeTillNext);\n\n //Append Train Information to Table\n trainRow.append(trainListName);\n trainRow.append(trainListDest);\n trainRow.append(trainListFreq);\n trainRow.append(trainListNextArrival);\n trainRow.append(trainListMinAway);\n\n //Display Train Schedule\n $(\"#tableBody\").append(trainRow);\n\n }\n}", "schedule() {\n this.state = 'schedule'\n if (this.pause || !this.count) return\n this.downloadSchedule()\n }", "drawTask(){\n debugger;\n let template = \"\";\n this.tasks.forEach(Task => {template += Task.templateTask});\n return template\n }", "setupSchedule(){\n // setup the schedule\n\n SchedulerUtils.addInstructionsToSchedule(this);\n\n let n_trials = (this.practice)? constants.PRACTICE_LEN : 25;\n // added for feedback\n this.feedbacks = [];\n for(let i= 0;i<n_trials;i++)\n {\n this.add(this.loopHead);\n this.add(this.loopBodyEachFrame);\n this.add(this.loopEnd);\n\n // added for feedback\n if(this.practice){\n this.feedbacks.push(new Scheduler(this.psychojs));\n this.add(this.feedbacks[i]);\n }\n }\n this.add(this.saveData);\n }", "static scheduleRenderTask() {\n\t\tif (!renderTaskId) {\n\t\t\t// renderTaskId = window.setTimeout(RenderScheduler.renderWebComponents, 3000); // Task\n\t\t\t// renderTaskId = Promise.resolve().then(RenderScheduler.renderWebComponents); // Micro task\n\t\t\trenderTaskId = window.requestAnimationFrame(RenderScheduler.renderWebComponents); // AF\n\t\t}\n\t}", "function render() {\n renderLives();\n renderTimeRemaining();\n }", "render() {\n const tasksHtmlList = [];\n\n // Loops through tasks array objects to store in tasksHtmlList\n for (let i = 0; i < this.tasks.length; i++) {\n const task = this.tasks[i]; // initialize an array to store the tasks\n\n // Format the date\n const date = new Date(task.dueDate);\n const formattedDate =\n date.getDate() + \"/\" + (date.getMonth() + 1) + \"/\" + date.getFullYear();\n\n // Pass the task id as a parameter\n const taskHtml = createTaskHtml(\n // call the function expression creattaskHtml with parameters\n task.id,\n task.name,\n task.description,\n task.assignedTo,\n formattedDate,\n task.status\n );\n\n tasksHtmlList.push(taskHtml); // push the new task values to taskHtmlList\n }\n\n const tasksHtml = tasksHtmlList.join(\"\\n\");\n\n const tasksList = document.querySelector(\"#tasksList\");\n tasksList.innerHTML = tasksHtml;\n }", "function render() { \n\n $body.append(templates['container']({'id':_uid}))\n $j('#' + _uid).append(templates['heading-no-links']({'title':'Countdown Promotion'}));\n $j('#' + _uid).append(templates['countdown-promo']({'id':_uid}));\n \n chtLeaderboard = new CHART.CountdownLeaderboard(_uid + '-charts-promo-leaderboard', _models.promo.getData('all'), _models.promo.getTargetSeries(20000));\n tblLeaderboard = new TABLE.CountdownLeaderboard(_uid + '-tables-promo-leaderboard', _models.promo.groupByOwner('all', 20000), _models.promo.getTotal('all', 180000)); \n chtLastWeek = new CHART.CountdownLeaderboard(_uid + '-charts-promo-lastweek', _models.promo.getData('lastweek'), _models.promo.getTargetSeries(1540));\n tblLastWeek = new TABLE.CountdownLeaderboard(_uid + '-tables-promo-lastweek', _models.promo.groupByOwner('lastweek', 1540), _models.promo.getTotal('lastweek', 13860)); \n chtWeeklySales = new CHART.CountdownWeeklySales(_uid + '-charts-promo-weeklysales', _models.promo.getData('all'));\n\n }", "function renderSwitcher() {\n $('.schedule-page__switcher', scheduled.$el).html(scheduled.template.scheduledSwitcherTemplate({currentView: scheduled.currentView}));\n }", "function makeTimetable() {\n renderer.draw('.timetable'); // any css selector\n\n\n // Call database and get classes\n getData();\n}", "function render() {\n res.render('socList', {\n title: 'Sentinel Project: SOC Manager',\n socs: socs,\n datapoints: resultsDatapoints\n });\n }", "function displayPlanner() {\n for (var i = 9; i < 18; i++) {\n createTimeBlock(i);\n }\n displayActivities();\n}", "function displayFailureMessageSchedule1() {\n if (this.output_displayed) {\n document.getElementById(\"OUTPUT\").innerHTML = \"\";\n this.output_displayed = false;\n }\n var output = document.getElementById(\"OUTPUT\");\n var title = document.createElement(\"HEADER\");\n title.setAttribute(\"id\", \"output_header\"); \n var y = document.createElement(\"H2\");\n var t = document.createTextNode(\"Unfortunately, we couldn't find popular times data for the specified input(s). Please ensure all time frames are valid (>= 1 min durations).\");\n y.appendChild(t);\n title.appendChild(y);\n output.appendChild(title);\n this.output_displayed = true;\n}", "function displayTrains() {\r\n var trainList = $(\"#trainList\");\r\n trainList.empty();\r\n\r\n // Create column headers\r\n trainList.append(\r\n $(\"<tr>\").append(\r\n $(\"<th>\").text(\"Train Name\"),\r\n $(\"<th>\").text(\"Destination\"),\r\n $(\"<th>\").text(\"Frequency (min)\"),\r\n $(\"<th>\").text(\"Next Arrival\"),\r\n $(\"<th>\").text(\"Minutes Away\")\r\n )\r\n );\r\n\r\n // Add rows for each train\r\n for (var train in trains) {\r\n let trainData = trains[train];\r\n let currentTime = moment();\r\n let frequency = parseInt(trainData.frequency);\r\n let firstDeparture = moment(trainData.firstDeparture, \"HH:mm\").subtract(1, \"years\");\r\n\r\n // Calculate mintues away\r\n let minsUntil = frequency - (currentTime.diff(firstDeparture, \"minutes\") % frequency);\r\n // Calculate next arrival\r\n let nextArrival = currentTime.add(minsUntil, \"minutes\").format(\"hh:mm a\");\r\n\r\n // Creates row HTML and append it to the table\r\n trainList.append(\r\n $(\"<tr>\").append(\r\n $(\"<td>\").text(train),\r\n $(\"<td>\").text(trainData.destination),\r\n $(\"<td>\").text(trainData.frequency),\r\n $(\"<td>\").text(nextArrival),\r\n $(\"<td>\").text(minsUntil)\r\n )\r\n );\r\n }\r\n}", "function displayTime() {\n $(\"tbody\").empty();\n setInterval(displayTime, 10 * 1000);\n $(\"#currentTime\").html(\"<h2>\" + moment().format(\"hh:mm a\") + \"</h2>\");\n displayTrain();\n }", "function Schedule({ schedule }) {\n if (schedule) {\n return (\n <div className=\"Page\" data-testid=\"SchedulePage\">\n {schedule.map((event) => (\n <div key={event.id} className=\"schedule\">\n <b>{event.name}</b>\n {event.races.map((race) => (\n <div key={race.id}>\n {race.name}\n <br />\n {new Date(race.scheduled).toLocaleTimeString(\"en-us\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n })}\n </div>\n ))}\n </div>\n ))}\n </div>\n );\n }\n return (\n <div className=\"Page\">\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n <h1>Schedule</h1>\n this\n </div>\n );\n}", "render ()\n {\n return (\n <div>\n <Steps\n cicle={CICLE.map((x) => DISPLAY_NAMES.get(x))}\n step={this.state.step}\n />\n <Timer\n hours={this.state.hours}\n minutes={this.state.minutes}\n seconds={this.state.seconds}\n onStartClick={() => {this.onStartClick()}}\n onStopClick={() => {this.onStopClick()}}\n onResetClick={() => {this.onResetClick()}}\n />\n </div>\n );\n }", "function trainItem(train, inc) {\n\n\t\tvar output = \"\",\n\t\t\tnextStop = train.nextstop,\n\t\t\tlate = train.late;\n\n\t\toutput += \"<ul class='train'>\";\n\n\t\toutput += \"<li class='stop-info'><a target='_blank' href='\"+ getStationStopLink(nextStop) + \"'><h4>Next Stop <stromg>\" + reformatDestination(nextStop, 'pretty') + \"</h4></a></li>\";\n\n\t\tif(late === 0) {\n\t\t\toutput += \"<li class='status bg-success'>The train is not late.</li>\";\n\t\t} else if(late === 1) {\n\t\t\toutput += \"<li class='status bg-danger'>It's running \" + late + \" minute late.</li>\";\n\t\t} else {\n\t\t\toutput += \"<li class='status bg-danger'>It's running \" + late + \" minutes late.</li>\";\n\t\t}\n\n\t\toutput += \"<li><div id='map-canvas\" + inc +\"'></div></li>\";\n\n\t\toutput += \"</li></ul>\";\n\n\t\treturn output;\n\t}", "function render() {\n\n\t\t\t}", "function displayOutputSchedule(data, names) {\n if (this.output_displayed) {\n document.getElementById(\"OUTPUT\").innerHTML = \"\";\n this.output_displayed = false;\n }\n var output = document.getElementById(\"OUTPUT\");\n var title = document.createElement(\"HEADER\");\n title.setAttribute(\"id\", \"output_header\"); \n var y = document.createElement(\"H2\");\n var t = document.createTextNode(\"Scheduler Output\");\n y.appendChild(t);\n title.appendChild(y);\n output.appendChild(title);\n // var title = document.createElement(\"HEADER\");\n // title.innerHTML = type;\n var valid_array = data[0];\n var invalid_array = data[1];\n for (var i = 0; i < valid_array.length; i++) {\n let cur = valid_array[i];\n let name = names[cur[0]];\n let startTime = cur[1];\n let endTime = cur[2];\n\n var new_entry = document.createElement(\"div\");\n new_entry.class = \"relative\";\n var from_time;\n var min_from = startTime % 60;\n var hrs_from = Math.floor(startTime / 60);\n if (min_from < 10) {\n let new_min_from = \"0\" + min_from;\n min_from = new_min_from;\n }\n from_time = hrs_from + \":\" + min_from;\n\n var to_time;\n var min_to = endTime % 60;\n var hrs_to = Math.floor(endTime / 60);\n if (min_to < 10) {\n let new_min_to = \"0\" + min_to;\n min_to = new_min_to;\n }\n to_time = hrs_to + \":\" + min_to;\n\n var newContent1 = document.createTextNode(\"You should go to \");\n var newContent2 = document.createTextNode(\" between \");\n var newContent3 = document.createTextNode(\" and \");\n var container = document.createElement(\"span\");\n var contentName;\n if (cur[3] == 1 || cur[3] == 0) {\n contentName = document.createTextNode(name);\n }\n else {\n contentName = document.createTextNode(\"* \" + name);\n }\n container.appendChild(contentName);\n container.style.color = \"red\";\n new_entry.appendChild(newContent1);\n new_entry.appendChild(container);\n new_entry.appendChild(newContent2);\n var time_container1 = document.createElement(\"span\");\n var time_container2 = document.createElement(\"span\");\n var f_node = document.createTextNode(from_time);\n var t_node = document.createTextNode(to_time);\n time_container1.appendChild(f_node)\n time_container1.style.color = \"green\";\n new_entry.appendChild(time_container1);\n new_entry.appendChild(newContent3);\n time_container2.appendChild(t_node);\n time_container2.style.color = \"green\";\n new_entry.appendChild(time_container2);\n output.appendChild(new_entry);\n }\n if (invalid_array.length > 0) {\n var new_entry = document.createElement(\"div\");\n new_entry.class = \"relative\";\n var container = document.createElement(\"span\");\n var newContent = document.createTextNode(\"We were unable to schedule the following places: \");\n container.appendChild(newContent);\n container.style.color = \"red\";\n new_entry.appendChild(container);\n for (var i = 0; i < invalid_array.length; i++) {\n let cur = invalid_array[i];\n let name = names[cur];\n var new_name;\n if (i == invalid_array.length - 1) {\n new_name = document.createTextNode(name);\n\n\n }\n else {\n new_name = document.createTextNode(name + \", \");\n }\n new_entry.appendChild(new_name);\n }\n\n output.appendChild(new_entry);\n\n\n }\n this.output_displayed = true;\n document.getElementById(\"defaultOpen\").disabled = false;\n document.getElementById(\"bft_button\").disabled = false;\n\n}", "function renderSchedule() {\n for (var i = 0; i< 9; i++) {\n var newRow = $(\"<div>\",).addClass(\"schedulerow\").attr(\"id\", timeSlot[i])\n\n var timeDiv = $(\"<div>\").addClass(\"time\")\n timeDiv.text(timeSlot[i])\n newRow.append(timeDiv)\n\n var eventDiv = $(\"<textarea>\").addClass(\"event\").attr(\"id\", timeSlot[i] + \"event\")\n eventDiv.text(eventsArray[i])\n newRow.append(eventDiv)\n\n var saveButton = $(\"<button>\").addClass(\"waves-effect waves-light btn-large blue darken-4\").attr(\"id\", timeSlot[i] + \"waves-effect waves-light btn-large blue darken-4\")\n saveButton.text(\"Save\")\n newRow.append(saveButton)\n \n \n schedule.append(newRow)\n }\n}", "function render() {\n\t\treturn graphTpl;\n\t}", "render() {\n\t\t\t// check if temperature data is fetched, if so add the sign styling to the page\n\t\t\tconst tempStyles = this.state.temp ? `${style.temperature} ${style.filled}` : style.temperature;\n\n\t\t\t// display all weather data\n\t\t\treturn (\n\t\t\t\t<div class={ style.container }>\n\t\t\t\t\t<div class={ style.header }>\n\t\t\t\t\t\t<div class={ style.city }>{ this.state.locate }</div>\n <div class={ style.conditions }>{ this.state.cond }</div>\n\t\t\t\t\t\t<span class={ tempStyles }>{ this.state.temp }</span>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class={ style.details }></div>\n\n\t\t\t\t\t<div style=\"text-align:left; margin-left:30px; font-size:24px; margin-bottom:10px; font-family: OpenSans-Light;\"><br /> {this.state.schedules.getName()}'s Day </div>\n\t\t\t\t\t<div class={style.scheduling}> <Scheduling display = {this.state.displaySchedule} activity={this.state.schedules.getSchedule()[Object.keys(this.state.schedules.getSchedule())[0]]} time={Object.keys(this.state.schedules.getSchedule())[0]} temp = {this.state.forecast24[0]}/> </div>\n\t\t\t\t\t<div class={style.scheduling}> <Scheduling display = {this.state.displaySchedule} activity={this.state.schedules.getSchedule()[Object.keys(this.state.schedules.getSchedule())[1]]} time={Object.keys(this.state.schedules.getSchedule())[1]} temp = {this.state.forecast24[1]}/> </div>\n\t\t\t\t\t<div class={style.scheduling}> <Scheduling display = {this.state.displaySchedule} activity={this.state.schedules.getSchedule()[Object.keys(this.state.schedules.getSchedule())[2]]} time={Object.keys(this.state.schedules.getSchedule())[2]} temp = {this.state.forecast24[2]}/> </div>\n\t\t\t\t\t<div class={style.scheduling}> <Scheduling display = {this.state.displaySchedule} activity={this.state.schedules.getSchedule()[Object.keys(this.state.schedules.getSchedule())[3]]} time={Object.keys(this.state.schedules.getSchedule())[3]} temp = {this.state.forecast24[3]}/> </div>\n\t\t\t\t\t<div class={style.notes}> Notes</div>\n\t\t\t\t\t{this.state.showNewSchedule ? (\n\t\t\t\t\t\t<div class={style.overlay}>\n\n\t\t\t\t\t\t<form name=\"input-form\">\n\t\t\t\t\t\t\tName <input type=\"text\" name=\"name\" id=\"name\" size=\"10\" /> <br />\n\t\t\t\t\t\t\tTime <input type=\"text\" name=\"time1\" size=\"3\" id=\"time1\" /> Name of Activity <input type=\"text\" name=\"activity1\" id=\"activity1\" size = \"15\"/> <br />\n\t\t\t\t\t\t\tTime <input type=\"text\" name=\"time2\" id=\"time2\" size=\"3\"/> Name of Activity <input type=\"text\" name=\"activity2\" id=\"activity2\" size = \"15\"/> <br />\n\t\t\t\t\t\t\tTime <input type=\"text\" name=\"time3\" id=\"time3\" size=\"3\"/> Name of Activity <input type=\"text\" name=\"activity3\" id=\"activity3\" size = \"15\"/> <br />\n\t\t\t\t\t\t\tTime <input type=\"text\" name=\"time4\" id=\"time4\" size=\"3\"/> Name of Activity <input type=\"text\" name=\"activity4\" id=\"activity4\" size = \"15\"/> <br />\n\t\t\t\t\t\t</form>\n\n\t\t\t\t\t\t\t<div class={submit_style.overlay}>\n\t\t\t\t\t\t\t\t<SubmitButton class={submit_style.button} submitClick={this.submitSchedule}/>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t<div class={discard_style.overlay}>\n\t\t\t\t\t\t\t\t<DiscardButton class={discard_style.button} discardClick={this.discardOverlay}/>\n\t\t\t\t\t\t\t</div>\n\n\t\t\t\t\t\t</div>): null}\n\n\t\t\t\t\t<div class={style.suggestions}>\n\t\t\t\t\t\t<Suggestions display = {this.state.displaySuggestions}/></div>\n\n\t\t\t\t\t<div class={style.bottombar}>\n\t\t\t\t\t\t<div class={style_iphone.bottombar}>\n\t\t\t\t\t\t\t\t<Link to={{\n\t\t\t\t\t\t\t\t\t\t\t\tpathname: '/hourlyforecast',\n\t\t\t\t\t\t\t\t\t\t\t\tstate: {\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tforecast: this.state.forecast\n\t\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t}}>\n\t\t\t\t\t\t\t\t\t\t\t<HourlyForecastButton/>\n\t\t\t\t\t\t\t\t</Link>\n\t\t\t\t\t\t\t\t<PlusButton class={style_iphone.button} click ={this.newSchedule}/ >\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t);\n\t\t}\n\n\t\tparseForecastResponse = (parsed_forecast_json) => {\n\t\t\t\t// parse response for temperature, weather description of next 12 hours\n\t\t\t\tvar i;\n\t\t\t\tfor(i = 0; i < 10; i++) {\n\t\t\t\t\tthis.state.forecast.push(parsed_forecast_json['data'][i]['datetime']);\n\t\t\t\t\tthis.state.forecast.push(parsed_forecast_json['data'][i]['weather']['description']);\n\t\t\t\t\tthis.state.forecast.push(parsed_forecast_json['data'][i]['app_temp'])\n\t\t\t\t}\n\t\t}\n\n\t\tparseWeatherResponse = (parsed_json) => {\n\t\t\tvar location = parsed_json['name'];\n\t\t\tvar temp_c = parsed_json['main']['temp'];\n\t\t\tvar conditions = parsed_json['weather']['0']['description'];\n\n\t\t\t// set states for fields so they could be rendered later on\n\t\t\tthis.setState({\n\t\t\t\tlocate: location,\n\t\t\t\ttemp: temp_c,\n\t\t\t\tcond : conditions\n\t\t\t});\n\t\t}\n\n\t\tparseForecast24Response = (parsed_forecast24_json) => {\n\t\t// taking the user-inputted times to find the temperature at that given time\n\t\tvar time1 = this.state.times[0];\n\t\tvar time2 = this.state.times[1];\n\t\tvar time3 = this.state.times[2];\n\t\tvar time4 = this.state.times[3];\n\t\tif (time1.length == 1) {time1 = '0'+time1;}\n\t\tif (time2.length == 1) {time1 = '0'+time2;}\n\t\tif (time3.length == 1) {time1 = '0'+time3;}\n\t\tif (time4.length == 1) {time1 = '0'+time4;}\n\n\t\tvar i;\n\t\tfor (i = 0; i < 24; i++) {\n\t\t\tvar input = parsed_forecast24_json['data'][i]['datetime'];\n\t\t\tvar fields = input.split(':');\n\t\t\tvar back = fields[1];\n\t\t\t// populating array with the temperatures at user-inputted times\n\t\t\tif (time1 == back) { this.state.forecast24.push(parsed_forecast24_json['data'][i]['app_temp']); }\n\t\t\tif (time2 == back) { this.state.forecast24.push(parsed_forecast24_json['data'][i]['app_temp']); }\n\t\t\tif (time3 == back) { this.state.forecast24.push(parsed_forecast24_json['data'][i]['app_temp']); }\n\t\t\tif (time4 == back) { this.state.forecast24.push(parsed_forecast24_json['data'][i]['app_temp']); }\n\n\t\t}\n\n\n\t}", "getListTrainingSchedule(qParams) {\n return this.request.get('/training-info', qParams);\n }", "render () {\n\t\tthis.renderBoard();\n\t\tthis.renderPieces();\n\t\t$writeInnerHTML( this.view.$maxVal, this.model.maxTimes );\n\t\t$writeInnerHTML( this.view.$minVal, this.model.minTimes );\n\t\tthis.view.alocatePieces( this.model.finalPositionsArr, this.model.baseNumber, this.model.getPieceSize(), this.model.gutterSize );\n\t\tthis.toggleBoardLock();\n\t}", "getGames () {\n let schedule = this.year + `${View.SPACE()}` + this.title + ` Draw ${View.NEWLINE()}`\n for (let aWeek of this.allGames) {\n schedule += 'Week:' + aWeek[0].week + `${View.NEWLINE()}`\n for (let aGame of aWeek) {\n// to get the date type, e.g. Mon, Jul 16 2018\n let newDate = new Date(aGame.dateTime).toDateString()\n// adding that date\n schedule += newDate + `${View.SPACE()}`\n// getting time like 7:35PM\n// was gonna use navigator.language instead of en-US but it comes up with korean\n// even thought default language is ENG\n let newTime = new Date(aGame.dateTime).toLocaleTimeString('en-US', {hour: 'numeric', minute: 'numeric'})\n schedule += newTime + `${View.SPACE()}`\n\n// getting name for home team from rank\n schedule += 'Team: ' + this.allTeams[aGame.homeTeamRank - 1].name + `${View.SPACE()}` + 'vs' + `${View.SPACE()}` + this.allTeams[aGame.awayTeamRank - 1].name + `${View.SPACE()}` + 'At: ' + this.allTeams[aGame.homeTeamRank - 1].venue + ', ' + this.allTeams[aGame.homeTeamRank - 1].city + `${View.NEWLINE()}`\n }\n }\n return schedule\n }", "function RenderViewActivities(view){\n\tvar data = CalendarDaterange(view);\n\tdata.csrfmiddlewaretoken = getCookie('csrftoken');\n\tLoading();\n\t $.ajax({\n\t\t type: \"post\",\n\t\t data: data,\n\t\t cache: false,\n\t\t url: BASE_URL + \"index/displayperiod/\",\n\t\t dataType: \"text\",\n\t\t error: function (xhr, status, error) {\n\t\t\t Done();\n\t\t\t alert('Internal Server Error. Page will be reloaded');\n\t\t\t window.location.reload();\n\t\t },\n\t\t success: function (responseString) {\n\t\t\t DrawGroupUngroupSortWithChart(responseString);\n\t\t\t Done();\n\t\t }\n\t });\n}", "function RenderRxs() {\n return <section className=\"medicines__timestamp\">\n <div className=\"Rx__name timestamp__size\">{Rx.name}: Last taken on {new Date(Rx.timestamp).toLocaleDateString('en-US')} at {new Date(Rx.timestamp).toLocaleTimeString('en-US')}</div>\n \n </section>\n }", "function renderTime(){\n let times = [];\n for (let i = timeStart; i <= timeEnd; i+=1){\n times.push(`${i}:00`)\n times.push(`${i}:30`)\n }\n const markup = timesMarkup(times)\n return markup\n }", "function renderCall() {\n // Repaint?\n if (needs_repaint === true) {\n needs_repaint = false;\n\n ctx.clearRect(0, 0, canvas_el.width, canvas_el.height);\n\n renderTimeXAxis();\n renderElementsMargin();\n\n renderRows();\n\n renderCurrentTimePoint();\n\n }\n }", "render() {\n // background box.\n this.renderBackground();\n this.renderName();\n this.renderTimeLine();\n this.renderWave();\n }", "draw() {\r\n // IDs Template: _box, _title, _refresh, _popup, _body, _loading\r\n // IDs Widget: _calendar\r\n var body = \"#\"+this.id+\"_body\"\r\n\t\t// add the calendar\r\n\t\t$(body).html('<div class=\"'+this.id+'_calendar\" style=\"width:100%; height:950px;\"></div>')\r\n // TODO: how to display with the configured timezone regardless of the browser's time\r\n\t\t$(\".\"+this.id+\"_calendar\").dhx_scheduler({\r\n\t\t\txml_date: \"%Y-%m-%d %H:%i\",\r\n\t\t\tmode: \"week\",\r\n\t\t\tdetails_on_create: true,\r\n\t\t\tdetails_on_dblclick: true,\r\n\t\t\toccurrence_timestamp_in_utc: false,\r\n\t\t\tinclude_end_by: true,\r\n\t\t\trepeat_precise: true,\r\n\t\t\ttouch: \"force\",\r\n\t\t\ttime_step: 15,\r\n\t\t\tmark_now: true,\r\n\t\t\twide_form: false,\r\n\t\t\thour_size_px: 35,\r\n\t\t\tscroll_hour: 6,\r\n\t\t});\r\n\t\t// clear previously attached events\r\n // TODO: multiple calendars on the same page\r\n\t\tscheduler.clearAll();\r\n\t\tif (gui.scheduler_events.length > 0) {\r\n\t\t\tfor (var i = 0; i < gui.scheduler_events.length; i++) {\r\n\t\t\t\tscheduler.detachEvent(gui.scheduler_events[i]);\r\n\t\t\t}\r\n\t\t\tgui.scheduler_events = [];\r\n\t\t}\r\n \t\t// init responsive\r\n\t\tinitResponsive(scheduler);\r\n\t\t// configure the time step\r\n\t\tif (\"time_step\" in this.widget) scheduler.config.time_step = this.widget[\"time_step\"];\r\n\t\t// configure the mini-calendars\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onLightbox\", function(){\r\n\t\t\tvar lightbox_form = scheduler.getLightbox();\r\n\t\t\tvar inputs = lightbox_form.getElementsByTagName('input');\r\n\t\t\tvar date_of_end = null;\r\n\t\t\tfor (var i=0; i<inputs.length; i++) {\r\n\t\t\t\tif (inputs[i].name == \"date_of_end\") {\r\n\t\t\t\t\tdate_of_end = inputs[i];\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tvar repeat_end_date_format = scheduler.date.date_to_str(scheduler.config.repeat_date);\r\n\t\t\tvar show_minical = function(){\r\n\t\t\t\tif (scheduler.isCalendarVisible()) scheduler.destroyCalendar();\r\n\t\t\t\telse {\r\n\t\t\t\t\tscheduler.renderCalendar({\r\n\t\t\t\t\t\tposition:date_of_end,\r\n\t\t\t\t\t\tdate: scheduler.getState().date,\r\n\t\t\t\t\t\tnavigation:true,\r\n\t\t\t\t\t\thandler:function(date,calendar) {\r\n\t\t\t\t\t\t\tdate_of_end.value = repeat_end_date_format(date);\r\n\t\t\t\t\t\t\tscheduler.destroyCalendar()\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t\tdate_of_end.onclick = show_minical;\r\n\t\t})); \r\n \t\t// configure event details sections\r\n\t\tscheduler.config.lightbox.sections = [\r\n\t\t\t{ name:\"description\", height:30, map_to:\"text\", type:\"textarea\" , focus:true, },\r\n\t\t\t{ name:\"recurring\", type:\"recurring\", map_to:\"rec_type\", button:\"recurring\" },\r\n\t\t\t{ name:\"time\", height:72, type:\"calendar_time\", map_to:\"auto\" }\r\n\t\t];\r\n var this_class = this\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onBeforeLightbox\", function (id){\r\n\t\t\tscheduler.resetLightbox();\r\n\t\t\tvar event = scheduler.getEvent(id);\r\n\t\t\tif (event.text == \"New event\") {\r\n\t\t\t\t// newly created event, default to empty string\r\n\t\t\t\tevent.text = \"\"\r\n\t\t\t\tif (\"default_value\" in this_class.widget) {\r\n event.text = \"\"+this_class.widget[\"default_value\"]\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn true;\r\n\t\t})); \r\n\t\t// configure the event template\r\n\t\tif (\"event_template\" in this.widget) {\r\n\t\t\tscheduler.templates.event_text=function(start, end, event){\r\n\t\t\t\tvar text = this_class.widget[\"event_template\"].replace(\"%value%\", event.text);\r\n\t\t\t\treturn text;\r\n\t\t\t}\r\n\t\t}\r\n\t\t// load the events\r\n var sensor_id = this.widget[\"sensor\"]\r\n this.add_configuration_listener(\"sensors/\"+sensor_id, gui.supported_sensors_config_schema)\r\n var message = new Message(gui)\r\n message.recipient = \"controller/db\"\r\n message.command = \"GET\"\r\n message.args = sensor_id\r\n gui.sessions.register(message, {\r\n \"sensor_id\": sensor_id\r\n })\r\n this.send(message)\r\n\t\t// listen for changes\r\n\t\tvar onChange = function(id,e){\r\n\t\t\t// on change save the events\r\n\t\t\tvar now = new Date()\r\n\t\t\tvar start = new Date(now.setDate(now.getDate() - 2))\r\n\t\t\tvar now = new Date()\r\n\t\t\tvar end = new Date(now.setMonth(now.getMonth() + 2))\r\n\t\t\tvar events = scheduler.getEvents(start, end)\r\n // save both the events for being displaying and for the analysis\r\n var value = JSON.stringify([scheduler.toJSON(), JSON.stringify(events)])\r\n // ask controller to save the value\r\n gui.log_debug(\"saving calendar data: \"+value)\r\n var message = new Message(gui)\r\n message.recipient = \"controller/hub\"\r\n message.command = \"SET\"\r\n message.args = sensor_id\r\n message.set(\"value\", value)\r\n gui.send(message)\r\n\t\t};\r\n\t\t// on any change, save the calendar\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onEventAdded\",onChange));\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onEventChanged\",onChange));\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onEventCopied\",onChange));\r\n\t\tgui.scheduler_events.push(scheduler.attachEvent(\"onEventDeleted\",onChange));\r\n }", "function render() {\n\t\t\t}", "constructor(schedule) {\n\n }", "render() {\n return (\n <div>\n <h1>\n {this.getTimeSpan(this.state.total)}\n </h1>\n <button\n onClick={ () => this.startStop() }\n style={ style.button_start }\n >\n { this.state.isStart? \"Pause\" : \"Start\" }\n </button>\n <button\n onClick={ () => this.reset() }\n style={style.button_reset}\n >\n Reset!\n </button>\n </div>\n )\n }", "render() {\n return (\n <div className='border red'>\n <div>{this.renderContent()}</div>\n <div>time is : {this.state.time}</div>\n </div>\n );\n }", "render() {\n const me = this,\n {\n scheduler\n } = me;\n\n if (me.isScheduler) {\n // if any sum config has a label, init tooltip\n if (me.summaries && me.summaries.some(config => config.label) && me.showTooltip && !me._tip) {\n me._labels = me.summaries.map(config => config.label || '');\n me._tip = new Tooltip({\n id: `${scheduler.id}-groupsummary-tip`,\n cls: 'b-timeaxis-summary-tip',\n hoverDelay: 0,\n hideDelay: 0,\n forElement: scheduler.timeAxisSubGridElement,\n anchorToTarget: true,\n forSelector: '.b-timeaxis-group-summary .b-timeaxis-tick',\n clippedBy: [scheduler.timeAxisSubGridElement, scheduler.bodyContainer],\n getHtml: me.getTipHtml.bind(me)\n });\n }\n }\n }", "drawStopwatch() {\n const stopwatch = document.createElement('div');\n stopwatch.setAttribute('id', this.id);\n stopwatch.setAttribute('class', 'stopwatch');\n document.getElementById('stopwatch-container').appendChild(stopwatch);\n }", "showEvents() {\n this.showEventTimespans();\n this.showRaterTimelines();\n }", "function displayDynamicSchedule() {\n //get the active schedule item\n var activeEvent = findActiveEvent();\n\n //create some variables for manipulated dom elements.\n var displayNameNode = document.getElementById('schedName');\n var displayTimeNode = document.getElementById('schedTime');\n var displayLocationNode = document.getElementById('schedLocation');\n\n //reset some text\n displayNameNode.innerHTML = activeEvent.event.name;\n displayTimeNode.innerHTML = activeEvent.event.time;\n displayLocationNode.innerHTML = activeEvent.event.location;\n\n //change the timeline navigation buttons (the arrows)\n var nextKey = scheduleData[activeEvent.key * 1 + 1]\n ? activeEvent.key * 1 + 1\n : 'null';\n var prevKey = scheduleData[activeEvent.key * 1 - 1]\n ? activeEvent.key * 1 - 1\n : 'null';\n $('#schedIncrease').attr('data-linkTo', nextKey);\n $('#schedDecrease').attr('data-linkTo', prevKey);\n\n //change the day displayed\n var formattedDay = moment(eventDay + ' 2019', 'MMMM DD YYYY').format(\n 'dddd'\n );\n $('#schedDay').text(formattedDay);\n\n //display the new timeline.\n //first find the active event in the currently displayed timeline.\n var displayedEventsKey = null;\n for (var key in timeline_displayedEvents) {\n if (timeline_displayedEvents[key] == activeEvent.key) {\n displayedEventsKey = key;\n break;\n }\n }\n\n //if the element exists in the timeline list, don't recreate it. If not, create a new timeline.\n if (!displayedEventsKey) {\n timeline_displayedEvents = [];\n line.innerHTML = '';\n for (var i = activeEvent.key; i < activeEvent.key * 1 + 4; i++) {\n timeline_displayedEvents.push(i);\n var time = scheduleData[i] ? scheduleData[i].time : '...';\n var elem =\n '<div id=\"timelineItem' +\n i +\n '\" data-linkTo=\"' +\n (scheduleData[i] ? i : null) +\n '\" class=\"scheduleLink\">' +\n time +\n '</div>';\n line.insertAdjacentHTML('beforeend', elem);\n }\n }\n\n //bold the item in the schedule list.\n $('.scheduleLink.active').removeClass('active');\n $('#listItem' + activeEvent.key).addClass('active');\n $('#timelineItem' + activeEvent.key).addClass('active');\n}", "render() {\n const me = this,\n { scheduler } = me;\n\n if (me.isScheduler) {\n // if any sum config has a label, init tooltip\n if (me.summaries && me.summaries.some((config) => config.label) && me.showTooltip && !me._tip) {\n me._labels = me.summaries.map((config) => config.label || '');\n\n me._tip = new Tooltip({\n id: `${scheduler.id}-groupsummary-tip`,\n cls: 'b-timeaxis-summary-tip',\n hoverDelay: 0,\n hideDelay: 0,\n forElement: scheduler.timeAxisSubGridElement,\n anchorToTarget: true,\n forSelector: '.b-timeaxis-group-summary .b-timeaxis-tick',\n clippedBy: [scheduler.timeAxisSubGridElement, scheduler.bodyContainer],\n getHtml: me.getTipHtml.bind(me)\n });\n }\n }\n }", "function ScheduleTaskShow(by,callDisplaySchedule) {\n\tconsole.warn('ScheduleTaskShow[by='+by+', callDisplaySchedule='+callDisplaySchedule+']');\n\tif ( document.getElementById('schedulecontainer') ) {\n\t\t//document.getElementById('schedulecontainer').style.display = 'block'; // Show the main schedulecontainer.\n\t\tdocument.getElementById('div_CalendarKey').style.display = 'block'; // Show the calendar key.\n\t\tvar scheduleClasses = document.getElementsByClassName('calendar_class');\n\t\tfor ( var i=0; i<scheduleClasses.length; i++ ) {\n\t\t\tscheduleClasses[i].style.display = 'block'; // Show each schedule class.\n\t\t}\n\t\tdocument.getElementById('div_ScheduleFunctionsContainer').style.display = 'none'; // Hide the div_ScheduleFunctionsContainer.\n\t}\n\t//if ( typeof callDisplaySchedule === 'undefined' || !callDisplaySchedule ) { DisplaySchedule('1613 '+by); } // Re-display the schedule.\n\tDisplaySchedule('ScheduleTaskShow 1622 '+by);\n\treturn false;\n} // END ScheduleTaskShow.", "function formatresults(){\nif (this.timesup==false){//if target date/time not yet met\nvar displaystring=\"<span style='background-color: #CFEAFE'>\"+arguments[1]+\" hours \"+arguments[2]+\" minutes \"+arguments[3]+\" seconds</span> left until launch time\"\n}\nelse{ //else if target date/time met\nvar displaystring=\"Launch time!\"\n}\nreturn displaystring\n}", "render() {\n const tasksHtmlList = [];\n const tasksList = document.querySelector('#taskOutput');\n const imgTag = document.querySelector('#relax');\n if (this.tasks.length === 0) {\n tasksList.innerHTML = '';\n document.querySelector('#taskLabel').innerHTML = 'No Outstanding Tasks';\n const randomPicture = `TaskPlannerBg${Math.floor(Math.random() * 6)}.jpg`;\n imgTag.src = `./Images/${randomPicture}`;\n imgTag.classList.add('d-block');\n imgTag.classList.remove('d-none');\n } else {\n imgTag.classList.add('d-none');\n imgTag.classList.remove('d-block');\n document.querySelector('#taskLabel').innerHTML = 'Outstanding Tasks';\n this.tasks.forEach((item) => {\n const formattedCreatedDate = item.createdDay.split('-').reverse().join('-');\n const formattedDueDate = item.dueDate.split('-').reverse().join('-');\n const taskHtml = createTaskHtml(item.Id, item.name, item.description, item.assignedTo, formattedDueDate, formattedCreatedDate, item.status, item.rating);\n tasksHtmlList.push(taskHtml);\n });\n const tasksHtml = tasksHtmlList.join('\\n');\n tasksList.innerHTML = tasksHtml;\n }\n }", "render() {\n let seconds = (this.state.elapsed / 100).toFixed(1);\n\n return (\n <div className=\"app container\">\n <div className=\"row\">\n <div className=\"col s12\">\n <div className=\"card purple z-depth-5\">\n <div className=\"card-content white-text\">\n <span className=\"card-title\">{this.props.yourName}'s Stop Watch</span>\n <div className=\"counter\">\n <h2>Seconds</h2>\n\n {/* STEP 04 -- Display running time */}\n {/* what do we need here */}\n\n </div>\n </div>\n <div className=\"card-action\">\n <div className=\"buttons\">\n\n {/* Step 05 add onClick events for our buttons THEN go back above and create the handlers in steps 6,7, & 8 */}\n\n <button className=\"waves-effect waves-light btn\" type=\"text\" name=\"starttime\" >Start</button>\n <button className=\"waves-effect waves-light btn\" type=\"text\" name=\"stoptime\" >Stop</button>\n <button className=\"waves-effect waves-light btn\" type=\"text\" name=\"resettime\" >Reset</button>\n\n </div>\n </div>\n </div>\n </div>\n </div>\n </div>\n );\n }", "function printSchedule() {\n var win=window.open();\n win.document.write(\"<head><title>My Class Schedule</title>\");\n win.document.write(\"<style> img { border: 2.5px solid gray; } h1 { font-family: 'Arial'; }</style></head>\");\n win.document.write(\"<body><h1 style='text-align: center; width: 1080;'>\"+_schedule+\"</h1>\");\n win.document.write(\"<img src='\"+_canvas.toDataURL()+\"'></body>\");\n win.print();\n win.close();\n }", "render() {\n const me = this;\n me.resize && me.resize.destroy();\n me.resize = me.createResizeHelper();\n\n if (me.showTooltip) {\n me.clockTemplate = new ClockTemplate({\n scheduler: me.client\n });\n }\n }", "static renderStateMachines() {\n let contenu = `\n <div id=\"return\" style=\"display: flex; flex-direction:row; height: 25px; align-items: center; margin-right: 5px;\">\n <button type=\"text\" class=\"btn btn-outline-secondary\" style=\"border-radius: 100%;\">⬅</button>\n <h5><em>State of Machines</em></h5>\n </div>\n <div id=\"dash\">\n </div>\n </div>`;\n document.querySelector(\"#dashboard\").innerHTML = contenu;\n\n $(\"#return\").click(event => {\n event.preventDefault();\n Dashboard.renderGlobalView();\n });\n }", "function render() {\n timer.innerHTML = (clock / 1000).toFixed(3);\n }", "renderScreenContent(){}", "function renderCalendar() {\n\n function renderCalendarViewRender(view, element) {\n scheduled.currentViewType = view.type;\n // this event fires once the calendar has completed loading and when the date is changed - thus calling the new events\n var start = moment(view.start).format('DD-MM-YYYY');\n var end = moment(view.end).format('DD-MM-YYYY');\n if(scheduled.currentViewType == 'month') {\n // if the current 'start' date of the selected month is not the same as the actual month then set the scheduled.calendarDate to the first of the proper month\n var currentStartMonth = moment(start, 'DD-MM-YYYY').format('MM-YYYY');\n var currentMonth = moment(view.title, 'MMMM YYYY').format('MM-YYYY');\n if(currentStartMonth != currentMonth) {\n scheduled.calendarDate = moment(view.title, 'MMMM YYYY').startOf('month').format('DD-MM-YYYY');\n }\n else {\n scheduled.calendarDate = start;\n }\n } else {\n scheduled.calendarDate = start;\n }\n updateCalendar(start, end);\n }\n\n\n $('#schedule-calendar').fullCalendar({\n header: {\n left: 'prev,next today',\n center: 'title',\n right: 'month,agendaWeek,agendaDay',\n },\n eventRender: function (event, element) {\n //Show tooltip when hovering over an event title\n var toolTipContent = '<strong>' + event.title + '</strong><br/>' + moment(event.start).format('MMMM D, YYYY') + ' ' + moment(event.start).format('h:mma');\n /*element.qtip({\n content: toolTipContent,\n hide: {fixed: true, delay: 200},\n style: 'qtip-light',\n position: {\n my: 'bottom center',\n at: 'top center',\n target: 'mouse',\n viewport: $('#fullcalendar'),\n adjust: {\n x: 0,\n y: -10,\n mouse: false,\n scroll: false,\n },\n },\n });*/\n },\n\n viewRender: renderCalendarViewRender,\n\n timeFormat: 'h:mma',\n firstDay: 1,\n aspectRatio: 2,\n defaultView: scheduled.currentViewType,\n fixedWeekCount: false,\n editable: false,\n lazyFetch: false,\n defaultDate: moment(scheduled.calendarDate, 'DD-MM-YYYY')\n });\n\n log.info('calendar start date ' + moment(scheduled.calendarDate, 'DD-MM-YYYY').format('DD-MM-YYYY'))\n }", "function schedulePlan()\r\n{\r\n\tvar url = \"scheduled\";\r\n\tvar htmlAreaObj = _getWorkAreaDefaultObj();\r\n\tvar objAjax = htmlAreaObj.getHTMLAjax();\r\n\tvar objHTMLData = htmlAreaObj.getHTMLDataObj();\r\n\r\n\tsectionName = objAjax.getDivSectionId();\r\n\t//alert(\"sectionName \" + sectionName);\r\n\tif(objAjax && objHTMLData)\r\n\t{\r\n\t\tif(!isValidRecord(true))\r\n\t\t{\r\n\t\t\treturn;\r\n\t\t}\r\n\t\tbShowMsg = true;\r\n\t Main.loadWorkArea(\"techspecevents.do\", url);\t \r\n\t}\r\n}", "renderStartEndTime() {\n\t\treturn (<StartEndTime\n\t\t\tstartTime={this.state.startTime}\n\t\t\tendTime={this.state.endTime}\n\t\t\tcolor={colorsProvider.routinesMainColor}\n\t\t\tsetStartTime={item => {\n\t\t\t\tthis.props.start_time(item);\n\t\t\t\tthis.setState({ startTime: item });\n\t\t\t}}\n\t\t\tsetEndTime={item => {\n\t\t\t\tthis.props.end_time(item);\n\t\t\t\tthis.setState({ endTime: item });\n\t\t\t}}\n\t\t/>)\n\n\t}", "function doRender() {\n\n var acm_times = [];\n \n // parses date format for timeline vis\n function getTime(time) {\n time = time.toString().split(' ');\n var month = new Date(Date.parse(time[1] +\" 1, 2000\")).getMonth()+1\n var hms = time[4].split(':');\n var new_time = time[3] + '-' + (\"00\" + month).slice(-2) + '-' + time[2] + 'T' + hms[0] + ':' + hms[1] + ':' + hms[2] + '.000Z';\n return new_time;\n }\n\n // retrieves relevant times for timeline vis\n function acmTimes(in_arr, res_arr) {\n for (var i = 0; i < in_arr.length; ++i) {\n var start1, start2, start3;\n \n if (in_arr[i][\"atime\"])\n start1 = getTime(in_arr[i][\"atime\"]);\n else\n start1 = \"error\";\n res_arr.push({group: 1, content: in_arr[i][\"filename\"], start: start1 });\n\n if (in_arr[i][\"ctime\"])\n start2 = getTime(in_arr[i][\"ctime\"]);\n else\n start2 = \"error\";\n res_arr.push({group: 2, content: in_arr[i][\"filename\"], start: start2 });\n\n if (in_arr[i][\"mtime\"])\n start3 = getTime(in_arr[i][\"mtime\"]);\n else\n start4 = \"error\";\n res_arr.push({group: 3, content: in_arr[i][\"filename\"], start: start3 });\n }\n }\n \n if (!(clam_detections.length + vtotal_detections.length > 50)) {\n acmTimes(clam_detections, acm_times);\n acmTimes(vtotal_detections, acm_times);\n }\n\n // used to sort the results list\n function compare(a, b) {\n if (a.index < b.index)\n return -1;\n else (a.index > b.index)\n return 1;\n }\n\n // prepares statistics\n results.sort(compare);\n var left = results[4].result + results[14].result + results[6].result - results[13].result + results[7].result;\n var tot = results[13].result + results[14].result + results[15].result + results[6].result;\n var percent = Math.floor(((tot - left)/tot)*100);\n\n if (percent > 100)\n percent = 100;\n\n var status;\n var progress;\n if (results[5].result == 0 && results[6].result == 0) {\n progress = \"progress-bar-striped progress-bar-warning active\";\n status = \"HASHING IN PROGRESS\";\n percent = 100;\n }\n else if (percent == 100) {\n progress = \"progress-bar-success\";\n status = \"COMPLETE\";\n }\n else {\n var stage;\n if (stage_results[\"wildfire\"])\n stage = \"% (STAGE: ClamAV)\";\n else if (stage_results[\"virustotal\"])\n stage = \"% (STAGE: WildFire)\";\n // removed for now for compatibility\n //else if (stage_results[\"chromehistory\"])\n //stage = \"% (STAGE: VirusTotal)\";\n else if (stage_results[\"nsrl\"])\n stage = \"% (STAGE: VirusTotal)\";\n //stage = \"% (STAGE: Chrome History)\";\n else if (stage_results[\"fingerprinting\"])\n stage = \"% (STAGE: NSRL)\";\n else\n stage = \"% COMPLETE\";\n\n progress = \"progress-bar-striped active\";\n status = percent.toString() + stage;\n }\n\n res.render(\"/home/jdonas/web-interface/components/scan-interface/views/disk-results\", \n { percent: percent, progress: progress, tot_files: results[13].result, case_name: case_name, status: status, clam_detections: clam_detections, vtotal_detections: vtotal_detections, acm_times: acm_times,\n vtotal_null: results[0].result, vtotal_0: results[1].result, vtotal_gt5: results[2].result, vtotal_gt10: results[3].result,\n nsrl_null: results[4].result, nsrl_true: results[5].result, nsrl_false: results[6].result,\n clamav_null: results[7].result, clamav_true: results[8].result, clamav_false: results[9].result,\n wfire_null: results[10].result, wfire_true: results[11].result, wfire_false: results[12].result,\n vtotal_pending: results[14].result, vtotal_ne_null: results[15].result,\n vtotal_known: results[16].result, vtotal_neutral: results[17].result});\n }", "function renderAll() {\n\t\tchart.each(render);\n\t\ttimeline1.updateData(bornDate.top(99999));\n\t}", "function DisplaySchedule()\n{\nHTMLCode = \"<table cellspacing=0 cellpadding=3 border=3 bgcolor=purple bordercolor=#000033>\";\nQueryDay = DefDateDay(QueryYear,QueryMonth,QueryDate);\nWeekRef = DefWeekNum(QueryDate);\nWeekOne = DefWeekNum(1);\nHTMLCode += \"<tr align=center><td colspan=8 class=Titre><b>\" + MonthsList[QueryMonth] + \" \" + QueryYear + \"</b></td></tr><tr align=center>\";\n\nfor (s=1; s<8; s++)\n{\nif (QueryDay == s) { HTMLCode += \"<td><b><font color=#ff0000>\" + DaysList[s] + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><b>\" + DaysList[s] + \"</b></td>\"; }\n}\n\nHTMLCode += \"<td><b><font color=#888888>Sem</font></b></td></tr>\";\na = 0;\n\nfor (i=(1-DefDateDay(QueryYear,QueryMonth,1)); i<MonthLength[QueryMonth]; i++)\n{\nHTMLCode += \"<tr align=center>\";\nfor (j=1; j<8; j++)\n{\nif ((i+j) <= 0) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse if ((i+j) == QueryDate) { HTMLCode += \"<td><b><font color=#ff0000>\" + (i+j) + \"</font></b></td>\"; }\nelse if ((i+j) > MonthLength[QueryMonth]) { HTMLCode += \"<td>&nbsp;</td>\"; }\nelse { HTMLCode += \"<td>\" + (i+j) + \"</td>\"; }\n}\n\nif ((WeekOne+a) == WeekRef) { HTMLCode += \"<td><b><font color=#00aa00>\" + WeekRef + \"</font></b></td>\"; }\nelse { HTMLCode += \"<td><font color=#888888>\" + (WeekOne+a) + \"</font></td>\"; }\nHTMLCode += \"</tr>\";\na++;\ni = i + 6;\n}\n\nCalendrier.innerHTML = HTMLCode + \"</table>\";\n}", "show() {\n stroke(0);\n strokeWeight(this.stroke);\n noFill();\n rect(this.x, this.y, this.w, this.h);\n\n strokeWeight(1);\n textSize(12);\n text(`Lane: ${this.ID}`, this.x + (.06 * this.w), this.y + (.5 * this.h) + 3);\n\n // if no jobs are in the lane it displays the full length of the lane \n // otherwise each new job added updates the display to show the \n // amount of space remaining \n if (this.jobs.length == 0) {\n textSize(12);\n text(`Lane Length: ${lane_lens}`, this.x + (.75 * this.w), this.y + (.5 * this.h) + 3);\n }\n }", "function showRuns(){\n //get runs object\n \n var runs = getRunsObject();\n \n //Check if empty\n if(runs != '' && runs !=null){\n for(var i=0; i<runs.length;i++){\n $('#stats').append('<li class=\"ui-body-inherit ui-li-static\"><strong>Date: </strong> '+runs[i].date+'<br/><strong>Distance: </strong>'+runs[i].miles+'m<div class=\"controls\"><a href=\"#edit\" id=\"editLink\" data-miles=\"'+runs[i].miles+'\" data-date=\"'+runs[i].date+'\">Edit</a> | <a href=\"#delete\">Delete</a> </div> </li>');\n \n }\n \n $('#home').bind('pageinit',function(){\n $('#stats').listview('refresh');\n \n });\n \n }\n \n }", "function render() {\n\t\t\n\t}", "render(){\n const tasksHtmlList = [];\n for (let i=0; i<this.tasks.length; i++){\n const task = this.tasks[i];\n\n const due = new Date(task.dueDate);\n //format date dd/mm/yy \n const formattedDate = due.getDate() + '/' + (due.getMonth()+1) + '/' \n + (due.getFullYear());\n\n const taskHtml = createTaskHtml(task.id, task.name,task.description,task.assignedTo,formattedDate,task.staTus);\n tasksHtmlList.push(taskHtml);\n }//closed render for loop\n const tasksHtml = tasksHtmlList.join('\\n');\n \n const tasksList = document.querySelector('#taskCard');\n tasksList.innerHTML = tasksHtml;\n \n}", "function displayTask() {\n if (tasks.length != 0) { \n panel.refreshTask(tasks[0]);\n } else {\n panel.allTasksDone();\n }\n }", "getListCustomTrainingSchedule(qParams) {\n return this.request.get('/training-dates', qParams);\n }", "function loadTask(){\n\n document.getElementById('title').value = task.title;\n document.getElementById('description').value = task.description;\n document.getElementById('triggersCard').innerHTML = operationRenderer(task.triggers.trigger, \"trigger\");\n document.getElementById('cards_targets_container').innerHTML = targetRenderer();\n\n loadApiTime();\n}", "function render() {\n if (window._env === 'development') console.debug('RENDER');\n initDynamicSentence();\n initMapChart();\n initHighcharts();\n initBubbleChart();\n initSankeyChart();\n initBubbleChart();\n initTableBody();\n }", "function renderActions() {\n $('.schedule-page__actions', scheduled.$el).html(scheduled.template.scheduledActionsTemplate());\n }", "function displayNextLaunch(nextLaunch) {\n const container = document.querySelector(\".launches-container\");\n let html = \"\";\n\n const flightNo = nextLaunch.flight_number;\n const date = new Date(nextLaunch.date_utc).toDateString();\n const launchName = nextLaunch.name;\n let description = nextLaunch.details;\n let redditLink = nextLaunch.links.reddit.campaign;\n\n function checkLink(link) {\n if (link) {\n return `<a href=\"${redditLink}\" class=\"launch__link\">Reddit thread</a>`;\n } else {\n return \"\";\n }\n }\n\n function checkDescription(link) {\n if (link) {\n return description;\n } else {\n return \"Details to be announced at a later date.\";\n }\n }\n\n html += `\n <div class=\"feature__launch\">\n <p class=\"feature__launch__details\">#${flightNo} | ${date}</p>\n <h3 class=\"feature__launch__name\">${launchName}</h3>\n <p class=\"feature__launch__description\">${checkDescription(\n description\n )}</p>\n \n ${checkLink(redditLink)}\n <a href=\"launches.html\" class=\"btn btn--primary\">\n See all launches\n </a>\n </div>\n `;\n\n // Remove the loader\n const loader = document.querySelector(\".loader\");\n loader.style.display = \"none\";\n\n container.innerHTML = html;\n}", "function schedule() {\n\n\n\t$(\"#sections\").change(function () {\n\t\t$.ajax({\n\t\t\turl: base_url + \"Welcome/fetchSchedule\",\n\t\t\ttype: 'post',\n\t\t\tdataType: 'json',\n\t\t\tdata: { id: $(this).val() },\n\t\t\tsuccess: function (data) {\n\t\t\t\tif (data == false) {\n\t\t\t\t\t$(\"#schedule_section\").html(\"<div class='col s4'></div><div class='col s4'><h4>No Attendance Encoded Yet</h4></div><div class='col s4'></div>\");\n\t\t\t\t} else {\n\t\t\t\t\tvar calendar = new Timetable();\n\t\t\t\t\tcalendar.setScope(7, 21);\n\t\t\t\t\tcalendar.addLocations(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']);\n\t\t\t\t\tfor (var i = 0; i < data.length; i++) {\n\n\t\t\t\t\t\t// console.log(data[i]);\t\n\t\t\t\t\t\tcalendar.addEvent(data[i].schedule_venue, data[i].day, new Date(2015, 7, data[i].s_d, data[i].s_h, data[i].s_min), new Date(2015, 7, data[i].e_d, data[i].e_h, data[i].e_min));\n\t\t\t\t\t\tvar renderer = new Timetable.Renderer(calendar);\n\t\t\t\t\t\trenderer.draw('.timetable');\n\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t});\n\n\n\t});\n}", "function start() {\n var timelineHolder = document.getElementById(\"schedule-graph\");\n var timeline = new google.visualization.Timeline(timelineHolder);\n var dataTable = prepareDataTable();\n\n timeline.draw(dataTable);\n}", "render() {}", "render() {}", "render() {}", "startDatePanelClick() {\n // change time type to start time mode\n dispatch(modifyInnerState_timeType(1))\n // route to time selector page\n dispatch(modifyInnerState_route(3))\n }", "function render() {\n\t\t//Drawing background\n drawBackground();\n\t\t//Drawing player paddles\n\t\tdrawPaddles();\n\t\t//Drawing ball\n\t\tdrawBall();\n\n\t\t//If the game is running\n\t\tif(!started)\n\t\t{\n\t\t\tdrawInfo(); //Drawing information (Move your paddle...)\n\t\t\tdocument.getElementById('lifeActivity').style.opacity = 0;\n\t\t\tdocument.getElementById('universityActivity').style.opacity = 0;\n\t\t\tif(result != \"\")\n\t\t\t{\n\t\t\t\tfor(i = 0; i < universityHidden.length; i++) universityHidden[i] = false;\n\t\t\t\tfor(i = 0; i < lifeHidden.length; i++) lifeHidden[i] = false;\n\t\t\t\tdrawResult(); //Drawing result , who won\n\t\t\t}\n\t\t}\n}", "static rendered () {}", "static rendered () {}", "render() {\n\n\t}", "render() {\n\n\t}", "renderTable(schedule) {\n\n let table = [];\n let body = [];\n\n // display table in desktop or mobile layout depending on screen width\n if (this.state.desktopLayout) {\n let header = (\n <div key={'header'} className=\"Shuttle-table-row\">\n {schedule.stops.map((stop) => <div key={stop} className=\"Shuttle-table-heading\">{stop}</div>)}\n </div>\n );\n table.push(header);\n schedule.times.forEach((timeRow, i) => {\n let r = (\n <div key={i} className=\"Shuttle-table-row\">\n {timeRow.map((time, j) => <div key={i + '-' + j} className=\"Shuttle-table-time\">{time}</div>)}\n </div>\n );\n body.push(r);\n });\n } else {\n schedule.times.forEach((timeRow, i) => {\n let r = (\n <div key={i} className=\"Shuttle-table-col\">\n {timeRow.map((time, j) => {\n if (time !== '') {\n return <div key={i + '-' + j} className=\"Shuttle-table-time\">{schedule.stops[j] + \": \" + time}</div>;\n } else {\n return null;\n }\n })}\n </div>\n );\n body.push(r);\n });\n }\n\n table.push(body);\n return <div className=\"Shuttle-table\">{table}</div>;\n }", "function renderTimeLabel() {\n renderText(\"TIME\", \"end\", \"#FF0\", Frogger.drawingSurfaceWidth, Frogger.drawingSurfaceHeight);\n }", "displayTimer(){\n this.final_timer = `${this.year}-${this.month}-${this.date} Time : ${this.hours}:${this.mins}:${this.seconds}`;\n }", "function renderJourney(){\n\ttripTime = JSON.parse(sessionStorage.tripTime);\n\tdelayTime = JSON.parse(sessionStorage.delayTime);\n\tfromStation = JSON.parse(sessionStorage.fromStation);\n\ttoStation = JSON.parse(sessionStorage.toStation);\n\tvar mood = JSON.parse(sessionStorage.mood);\n\n\t$(\".js-journey-description\").text(`A ${mood} Journey from ${fromStation} to ${toStation}`);\n\t$(\".js-trip-time\").text(`Travel Time: ${tripTime}`);\n\t$(\".js-delay-time\").text(`Delay Time: ${delayTime}`);\n}", "function displaySchedule(schedule) {\n\tif (displayScheduleTimeout != null) {\n\t\tclearTimeout(displayScheduleTimeout);\n\t}\n\tvar now = new Date(Date.now() + tzOffsetDif); // will show device time\n\tvar nowMark = now.getHours()*60 + now.getMinutes();\n\tvar isToday = toXSDate(displayScheduleDate) == toXSDate(now);\n\tvar programClassesUsed = new Object();\n\tjQuery(\".stationSchedule .scheduleTick\").each(function() {\n\t\tjQuery(this).empty();\n\t\tvar sid = jQuery(this).parent().attr(\"data\");\n\t\tvar slice = parseInt(jQuery(this).attr(\"data\"))*60;\n\t\tvar boxes = jQuery(\"<div class='scheduleMarkerContainer'></div>\");\n\t\tfor (var s in schedule) {\n\t\t\tif (schedule[s].station == sid) {\n\t\t\t\tif (!(isToday && schedule[s].date == undefined && schedule[s].start + schedule[s].duration/60 < nowMark)) {\n\t\t\t\t\tvar relativeStart = schedule[s].start - slice;\n\t\t\t\t\tvar relativeEnd = schedule[s].start + schedule[s].duration/60 - slice;\n\t\t\t\t\tif (0 <= relativeStart && relativeStart < 60 ||\n\t\t\t\t\t\t0.05 < relativeEnd && relativeEnd <= 60 ||\n\t\t\t\t\t\trelativeStart < 0 && relativeEnd >= 60) {\n\t\t\t\t\t\tvar barStart = Math.max(0,relativeStart)/60;\n\t\t\t\t\t\tvar barWidth = Math.max(0.05,Math.min(relativeEnd, 60)/60 - barStart);\n\t\t\t\t\t\tvar programClass;\n\t\t\t\t\t\tvar idx;\t\t\t\t\t\t\n\t\t\t\t\t\tif (schedule[s].program == \"Manual\" || schedule[s].program == \"Run-once\") {\n\t\t\t\t\t\t\tprogramClass = \"programManual\";\t\t\t\t\t\t\n\t\t\t\t\t\t} else if(isNaN(schedule[s].program)) {\n\t\t\t\t\t\t\tidx = progNames.indexOf(schedule[s].program);\n\t\t\t\t\t\t\tprogramClass = \"program\" + (idx + 1)%10;\t\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tprogramClass = \"program\" + (parseInt(schedule[s].program))%10;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tprogramClassesUsed[schedule[s].program] = programClass;\n\t\t\t\t\t\tvar markerClass = (schedule[s].date == undefined ? \"schedule\" : \"history\");\n\t\t\t\t\t\tboxes.append(\"<div class='scheduleMarker \" + programClass + \" \" + markerClass + \"' style='left:\" + barStart*100 + \"%;width:\" + barWidth*100 + \"%' data='\" + programName(schedule[s].program) + \": \" + schedule[s].label + \"'></div>\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (isToday && slice <= nowMark && nowMark < slice+60) {\n\t\t\tvar stationOn = jQuery(this).parent().children(\".stationStatus\").hasClass(\"station_on\");\n\t\t\tboxes.append(\"<div class='nowMarker\" + (stationOn?\" on\":\"\")+ \"' style='width:2px;left:\"+ (nowMark-slice)/60*100 + \"%;'>\");\n\t\t}\n\t\tif (boxes.children().length > 0) {\n\t\t\tjQuery(this).append(boxes);\n\t\t}\n\t});\n\tjQuery(\"#legend\").empty();\n\tfor (var p in programClassesUsed) {\n\t\tjQuery(\"#legend\").append(\"<span class='\" + programClassesUsed[p] + \"'>\" + programName(p) + \"</span>\");\n\t}\n\tjQuery(\".scheduleMarker\").mouseover(scheduleMarkerMouseover);\n\tjQuery(\".scheduleMarker\").mouseout(scheduleMarkerMouseout);\n\t\n\tjQuery(\"#displayScheduleDate\").text(dateString(displayScheduleDate) + (displayScheduleDate.getFullYear() == now.getFullYear() ? \"\" : \", \" + displayScheduleDate.getFullYear()));\n\tif (isToday) {\n\t\tdisplayScheduleTimeout = setTimeout(displayProgram, 1*60*1000); // every minute\n\t}\n}", "function render() {\n\t}", "returnRenderText() {\n /*-- add heading part of seating chart --*/\n let layout = /*html*/`\n <div class=\"seating-container\">\n <div class=\"buffer\"></div>\n <div class=\"movie-details-row\">\n <em>${bookingTempStore.showingDetails.film}: ${bookingTempStore.showingDetails.date} (${bookingTempStore.showingDetails.time})</em>\n </div>\n <div class=\"screen-row\">\n <div></div>\n <h1>BIODUK</h1>\n <div></div>\n </div>\n <div class=\"seating-rows-container\">\n `\n /*-- add seating/checkboxes part of seating chart --*/\n layout += this.seatingChart();\n /*-- closing tags and footer part of seating chart --*/\n layout += /*html*/`\n </div>\n <div class=\"text-row\">\n <em>Välj din plats</em>\n </div>\n <div class=\"age-btn-row\">\n `\n layout += this.ageButtons();\n layout += /*html*/`\n </div>\n <div class=\"button-row\">\n ${BookingUtilityFunctions.bookingPriceButton()}\n </div>\n <div class=\"buffer\"></div>\n </div>\n `\n return layout;\n }", "render() {\n return (\n <div className=\"px-3\">\n <hr />\n Visualization method{this.createVisualizationSelector()}\n <hr />\n </div>\n );\n }", "displaySchedule(schedule) {\n // helper-function: add leading Zero to Numbers < 10\n function addZero(i) {\n if (i < 10) {\n i = \"0\" + i;\n }\n return i;\n }\n\n let today = new Date();\n let target = document.querySelector(\"#wrapper\");\n let dayNames = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"];\n\n let tempDay = -1;\n // for each entry\n for (let i in schedule) {\n // get start & end Date\n let start = new Date(parseInt(schedule[i].start) * 1000);\n let end = new Date(parseInt(schedule[i].end) * 1000);\n\n // if course is in the past -> skip\n if (\n start.getDate() < today.getDate() &&\n start.getMonth() < today.getMonth() &&\n start.getFullYear() <= today.getFullYear()\n ) {\n console.log(\n start.getDate(),\n today.getDate(),\n start.getMonth(),\n today.getMonth()\n );\n console.log(\"skip\");\n continue;\n }\n\n let dayforAriaLabel = \"\";\n // insert once per Day\n if (tempDay == -1 || tempDay != start.getDate()) {\n if (\n start.getDate() == today.getDate() &&\n start.getMonth() == today.getMonth() &&\n start.getFullYear() == today.getFullYear()\n ) {\n target.innerHTML += `\n <div class=\"schedule_day\">TODAY!</div>\n `;\n dayforAriaLabel = \"Today\";\n } else {\n target.innerHTML += `\n <div class=\"schedule_day\">${start.getDate()}.${start.getMonth() + 1} - ${dayNames[start.getDay()]}</div>\n `;\n\n dayforAriaLabel = `${dayNames[start.getDay()]} the ${start.getDate()}.${start.getMonth() + 1}`;\n }\n\n tempDay = start.getDate();\n }\n\n // Template\n target.innerHTML += `<div class=\"entry\" tabindex=\"0\" aria-label=\"${dayforAriaLabel}, ${schedule[i].title} in Room ${schedule[i].location} with ${schedule[i].lecturer} from ${addZero(start.getHours())}:${addZero(start.getMinutes())} to ${addZero(end.getHours())}:${addZero(end.getMinutes())}\">\n <div class=\"time\">\n ${addZero(start.getHours())}:${addZero(start.getMinutes())} - ${addZero(end.getHours())}:${addZero(end.getMinutes())}\n </div>\n <div class=\"detail\">\n ${schedule[i].title} / ${schedule[i].type} / ${schedule[i].lecturer} / ${schedule[i].location}\n </div>\n </div>\n `;\n }\n }", "function updateView(result) {\n showScheduleButton();\n showResultMessage(result.message);\n loadTasks();\n}", "renderStartAndDuration() {\n $(this._startElemjQuery).text(this._start.toLocaleTimeString());\n $(this._timerElemjQuery).text(Utility.getHHMMSS(this.duration));\n }", "render() {\n let alarmsHtmlList = [];\n for(let i = 0; i < this.alarms.length; i++) {\n const currentAlarm = this.alarms[i];\n const alarmHtml = createAlarmHtml(currentAlarm.id, currentAlarm.alarmTime);\n alarmsHtmlList.push(alarmHtml);\n };\n const alarmsHtml = alarmsHtmlList.join(\"\\n\");\n const alarmList = document.querySelector(\"#alarmList\");\n alarmList.innerHTML = alarmsHtml;\n return true;\n }", "function render() {\n let bigString;\n console.log('render fxn ran')\n if (store.view === 'landing') {\n bigString = generateTitleTemplate(store);\n\n }\n else if (store.view === 'question') {\n bigString = generateQuestionTemplate(store);\n\n }\n else if (store.view === 'feedback') {\n bigString = generateFeedbackTemplate(store)\n\n }\n else if (store.view === 'results') {\n bigString = generateResultsTemplate(store);\n\n }\n $('main').html(bigString);\n\n //attach event listeners\n\n\n}", "getSchedule(){\n // return CRON schedule format\n // this sample job runs every 15 seconds\n return '*/15 * * * * *';\n }", "function showRuns(){\n\t\t//get runs object\n\t\tvar runs2 = getRunsObject();\n\n\t\t//check if not empty\n\t\tif(runs2 != '' && runs2 != null){\n\t\t\tfor(var i = 0; i < runs2.length; i++){\n\t\t\t\t$('#stats').append('<li class=\"ui-body-inherit ui-li-static\"><strong>Date: </strong>'+runs2[i][\"date\"]+\n\t\t\t\t\t'<br><strong>Distance: </strong>'+runs2[i][\"miles\"]+'m<div class=\"controls\">'+\n\t\t\t\t\t'<a href=\"#edit\" id=\"editLink\" data-miles=\"'+runs2[i][\"miles\"]+'\" data-date=\"'+runs2[i][\"date\"]+'\">Edit</a> | <a href=\"#delete\" id=\"deleteLink\" data-miles=\"'+runs2[i][\"miles\"]+'\" data-date=\"'+runs2[i][\"date\"]+'\" onclick=\"return deleteRun()\">Delete</a></div</li>');\n\t\t\t}\n\t\t\t$('#home').bind('pageinit', function(){\n\t\t\t\t$('#stats').listview('refresh');\n\t\t\t});\n\t\t}else{\n\t\t\t$('#stats').html('<p>You have no logged run </p>');\n\t\t}\n\t}", "create() {\n if (this.cellmonitor.view !== 'tasks') {\n throw new Error('SparkMonitor: Drawing tasks graph when view is not tasks');\n }\n this.clearRefresher();\n const container = this.cellmonitor.displayElement.find('.taskcontainer').empty()[0];\n const tasktrace = {\n x: this.taskChartDataX,\n y: this.taskChartDataY,\n fill: 'tozeroy',\n type: 'scatter',\n mode: 'none',\n fillcolor: '#00aedb',\n name: 'Active Tasks',\n };\n const executortrace = {\n x: this.executorDataX,\n y: this.executorDataY,\n fill: 'tozeroy',\n type: 'scatter',\n mode: 'none',\n fillcolor: '#F5C936',\n name: 'Executor Cores',\n };\n const jobtrace = {\n x: this.jobDataX,\n y: this.jobDataY,\n text: this.jobDataText,\n type: 'scatter',\n mode: 'markers',\n fillcolor: '#F5C936',\n // name: 'Jobs',\n showlegend: false,\n marker: {\n symbol: 23,\n color: '#4CB5AE',\n size: 1,\n },\n };\n const data = [executortrace, tasktrace, jobtrace];\n const layout = {\n // title: 'Active Tasks and Executors Cores',\n // showlegend: false,\n margin: {\n t: 30, // top margin\n l: 30, // left margin\n r: 30, // right margin\n b: 60, // bottom margin\n },\n xaxis: {\n type: 'date',\n // title: 'Time',\n },\n yaxis: {\n fixedrange: true,\n },\n dragmode: 'pan',\n shapes: this.shapes,\n legend: {\n orientation: 'h',\n x: 0,\n y: 5,\n // traceorder: 'normal',\n font: {\n family: 'sans-serif',\n size: 12,\n color: '#000',\n },\n // bgcolor: '#E2E2E2',\n // bordercolor: '#FFFFFF',\n // borderwidth: 2\n },\n };\n this.taskChartDataBufferX = [];\n this.taskChartDataBufferY = [];\n this.executorDataBufferX = [];\n this.executorDataBufferY = [];\n this.jobDataBufferX = [];\n this.jobDataBufferY = [];\n this.jobDataBufferText = [];\n const options = { displaylogo: false, scrollZoom: true };\n Plotly.newPlot(container, data, layout, options);\n this.taskChart = container;\n if (!this.cellmonitor.allcompleted) this.registerRefresher();\n }", "render(){\n\n // draw one horizontal line at a time\n for (let y = 0; y < this.boardHeight; y++){\n\n let line = '';\n\n for (let x = 0; x < this.boardWidth; x++){\n\n line += this.board[x][y] === ALIVE ? 'o' : '_';\n }\n\n process.stdout.write(line + '\\n');\n }\n\n process.stdout.write('Generation: ' + this.generation + '\\n');\n\n }", "render() {\n if (!this.state.loaded1 || !this.state.loaded2) {\n return (\n <div className=\"center-align\">\n <div className=\"progress\">\n <div className=\"indeterminate\"></div>\n </div>\n </div>\n );\n }\n\n return (\n <div>\n <Navbar/>\n <div className=\"calender\">\n <ScheduleComponent\n height=\"650px\"\n readonly={true}\n currentView=\"Month\"\n eventSettings={{ dataSource: this.state.localData }}\n >\n <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />\n </ScheduleComponent>\n </div>\n </div>\n \n );\n }" ]
[ "0.59909433", "0.58976144", "0.5891908", "0.5891722", "0.5852336", "0.5830973", "0.57998675", "0.57507503", "0.5747022", "0.5734968", "0.5723215", "0.56842685", "0.5664556", "0.5657985", "0.56468445", "0.56430423", "0.560802", "0.558859", "0.5573398", "0.55627066", "0.5533108", "0.5525781", "0.55184823", "0.5516977", "0.5510406", "0.5507847", "0.55063444", "0.54917175", "0.5481585", "0.54692954", "0.54569334", "0.54419136", "0.54385996", "0.54368526", "0.5436835", "0.5420016", "0.54183936", "0.5398754", "0.5393019", "0.5375748", "0.5375196", "0.53695244", "0.5363752", "0.5363108", "0.5356725", "0.5354963", "0.5343605", "0.5340956", "0.5340601", "0.5338679", "0.5335356", "0.53327256", "0.5327939", "0.53194124", "0.53190273", "0.5314199", "0.5313008", "0.5312015", "0.5311161", "0.53100985", "0.5295679", "0.5278372", "0.52766865", "0.5275677", "0.5274324", "0.52692693", "0.52649456", "0.5257966", "0.52551204", "0.5243573", "0.5243489", "0.52411014", "0.52398646", "0.52360463", "0.52360463", "0.52360463", "0.5235629", "0.5234068", "0.52272046", "0.52272046", "0.5223288", "0.5223288", "0.5220831", "0.5218416", "0.5217369", "0.52161384", "0.52146274", "0.52132326", "0.52122736", "0.5211948", "0.5206847", "0.5202019", "0.52006483", "0.51917326", "0.5189558", "0.51821", "0.5171727", "0.5169228", "0.51676345", "0.51637954" ]
0.6137099
0
Function for displaying animal data
function renderButtons() { // preventing repeat $("#animals-button").empty(); for (var i = 0; i < animals.length; i++) { var a = $("<button>"); a.addClass("animal"); a.attr("data-name", animals[i]); a.text(animals[i]); $("#animals-button").append(a); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function displayAnimalInfo() {\n\n\t\tvar animal = $(this).attr(\"data-name\");\n\t\tconsole.log(\"animal= \" + animal);\n\t\tvar queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=dc6zaTOxFJmzC&limit=10\";\n\t\tconsole.log(\"queryURL= \" + queryURL);\n\t\t\t//creating AJAX call for specific animal button being called\n\t\t\t$.ajax({ url: queryURL, method: \"GET\" }).done(function(response) {\n\t\t\tconsole.log(response);\n\t\t\t\t//creating a div to hold the gifs (I already have a div created in html file #gifs-view)\n\t\t\t\t//var gifDiv = $(\"<div class='gif'>\");\n\n\t\t\t\tfor (var index = 0; index < response.data.length; index++) {\n\t\t\t\t\t//storing the rating data\n\t\t\t\t\tvar rating = response.data[index].rating; \n\t\t\t\t\tconsole.log(rating);\n\n\t\t\t\t\tvar image = response.data[index].images.downsized.url;\n\t\t\t\t\tconsole.log(image);\n\n\t\t\t\t\t//add rating to page \n\t\t\t\t\t$(\"#gifs-view\").append(\"Rating: \" + rating);\n\n\t\t\t\t\t//add gifs to page \n\t\t\t\t\t$(\"#gifs-view\").append(\"<img src='\" + image + \"'>\");\n\t\t\t\t\tconsole.log(image);\n\t\t\t\t}\n\n\t\t\t});\n\n\t}", "function showData(petfood){\n\tconsole.log(\"petfood\", petfood);\n\n\tfor (var i = 0; i < petfood.length; i++){\n\t\tpetFoodDiv.innerHTML += `<div><h2>${petfood[i].name}</h2></div>`;\n\t\tfor (var j = 0; j < petfood[i].types.length; j++){\n\t\t\tpetFoodDiv.innerHTML += `<div><h3>${petfood[i].types[j].type}</h3></div>`;\n\t\t\tfor (var k = 0; k < petfood[i].types[j].volumes.length; k++){\n\t\t\t\tpetFoodDiv.innerHTML += `<div>${petfood[i].types[j].volumes[k].name}</div>\n\t\t\t\t\t\t\t\t\t\t<div>${petfood[i].types[j].volumes[k].price}</div>`;\n\t\t\t}\n\t\t}\n\t}\n}", "function getAnimals() {\n console.log('getting animals');\n $.ajax({\n type: 'GET',\n url: '/poprandomizer',\n success: function (animals) {\n animals.forEach(function (animal) {\n var $el = $('<p>Type: ' + animal.type + ', Population: ' + animal.population + '</p>');\n $('#containerTitle').append($el);\n });\n },\n });\n}", "function getDogTemplate(dog) {\n /* This gets the information but does not work for nulls, would have to implement loops and format correctly\n console.log(dog.shows[0].location);\n console.log(dog.shows[0].medals[0].title);\n return `<li>${dog.name} - ${dog.description} - ${dog.breed} - ${dog.shows[0].location}</li>`;\n */\n return `<li>${dog.name} - ${dog.description} - ${dog.breed} </li>`;\n}", "function allDogs() {\n\t// Displays the dogs name on the left in a 'jumbotron'\n\tdocument.getElementById('dogsContainer').innerHTML += '<h3 class=\"jumbotron col-md-4 bg-dark text-center\">' + dogs[i].name + '</h3>';\n\t// Displays an image of the dog itself\n\tdocument.getElementById('dogsContainer').innerHTML += '<img id=\"d' + id.toString() + '\" class=\"img-thumbnail col-md-4 my-dogs\" src=\"' + dogs[i].photo + '\"alt=\"Dog\">'; // ID is incremented automatically\n\t// Displays the remaining information about the dog taken from the array function\n\tdocument.getElementById('dogsContainer').innerHTML += '<ul class=\"jumbotron col-md-4 bg-custom\">' +\n\t'<li><b>ID#:</b> D' + id++ + '</li>' + \n\t'<li><b>Breed:</b> ' + dogs[i].breed + '</li>' + \n\t'<li><b>Colour:</b> ' + dogs[i].color + '</li>' + \n\t'<li><b>Height (cm):</b> ' + dogs[i].height + '</li>' +\n\t'<li><b>Age(Years): </b>' + dogs[i].age + '</li>' + \n\t'<li><b>Job: </b>' + dogs[i].job + '</li>' +\n\t'</ul>';\n}", "function displayanimalInfo() {\n\n var animal = $(this).attr(\"data-name\");\n \n // var queryURL = \"http://api.giphy.com/v1/gifs/random?api_key=dc6zaTOxFJmzC&limit=10&search?q=\"+ animal;\n \n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=dc6zaTOxFJmzC&limit=10\";\n\n \n \n // Creating an AJAX call for the specific animal button being clicked\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).done(function(response) {\n\n //removes previously populated divs of animal gifs to prep for load on page\n $( \"div\" ).remove( \".imgState\" );\n // loads new pics into the page\n var results = response.data;\n console.log(\"number of records = \" + results.length);\n // loops through the API data pulled in \n\n for (var i = 0; i < results.length; i++) {\n\n // Creating and storing a div tag\n var animalDiv = $(\"<div class='imgState'>\");\n // Creating a paragraph tag with the result item's rating\n var p = $(\"<p>\").text(\"Rating: \" + results[i].rating);\n\n // Creating and storing still and animated images\n var animalImage = $(\"<img>\");\n animalImage.attr(\"src\", results[i].images.fixed_height_still.url);\n animalImage.attr(\"data-still\", results[i].images.fixed_height_still.url);\n animalImage.attr(\"data-animate\", results[i].images.fixed_height.url)\n \n // Appending the paragraph and image tag to the animalDiv\n \n animalDiv.append(animalImage);\n animalDiv.append(p);\n \n $(\"#animals-view\").append(animalDiv);\n } \n\n });\n\n }", "function displayAnimalInfo() {\n\n var animal = $(this).attr(\"data-name\");\n var queryURL = \"https://api.giphy.com/v1/gifs/search?api_key=x8yAyu1xp1MRX1C3aQjtJahAr5047i7j&q=\"+animal;\n \n\n // Creating an AJAX call for the specific animal button being clicked\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function(response) {\n console.log(response);\n for (var k = 0; k < amount.length; k++) { //forloop to make 10 appear\n // Creating a div to hold the animal\n var animalDiv = $(\"<div class='animal'>\");\n\n // Storing the rating data\n var rating = response.data[k].rating;\n\n // Creating an element to have the rating displayed\n var pOne = $(\"<p>\").text(\"Rating: \" + rating);\n\n // Displaying the rating\n animalDiv.append(pOne);\n\n\n // Retrieving the URL for the image\n var imgURL = response.data[k].images.fixed_height.url;\n\n // Creating an element to hold the image\n var image = $(\"<img>\").attr(\"src\", imgURL);\n\n // Appending the image\n animalDiv.append(image);\n \n // Putting the entire animal above the previous animals\n $(\"#giphy-view\").prepend(animalDiv);\n }//forloop end\n });\n\n}", "function renderHTML(data) {\n var htmlString = \"\";\n //for loop to concatinate each object info into a sentence\n for (var i = 0; i < data.length; i++) {\n htmlString += \"<p>\" + data[i].name + \" is a \" + data[i].species + \" that likes to eat \";\n\n for (var ii = 0; ii < data[i].foods.likes.length; ii++) {\n if (ii == 0) {\n htmlString += data[i].foods.likes[ii]\n\n }\n else {\n htmlString += \" and \" + data[i].foods.likes[ii]\n }\n }\n\n htmlString += \" and dislikes \";\n\n for (var ii = 0; ii < data[i].foods.dislikes.length; ii++) {\n if (ii == 0) {\n htmlString += data[i].foods.dislikes[ii]\n\n }\n else {\n htmlString += \" and \" + data[i].foods.dislikes[ii]\n }\n }\n\n htmlString += \".</p>\"\n }\n animals.insertAdjacentHTML('beforeend', htmlString);\n}", "showDetailsAnimal(id) {\n this.apiAnimal.get(id);\n }", "function displayAnimalInfo() {\n\n var animal = $(this).attr(\"data-name\");\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" +\n animal + \"&api_key=dc6zaTOxFJmzC&limit=10\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).done(function(response) {\n \n for (var i = 0; i < response.data.length; i++) {\n console.log(response);\n //This section creates a section of HMTL to repeatably print gifs to the screen\n var animalDiv = $('<div>');\n var p = $('<p>');\n p.text(\"Rating: \" + response.data[i].rating);\n var animalImage = $('<img>');\n animalImage.addClass(\"gif\");\n animalImage.attr('data-animate',response.data[i].images.fixed_height.url);\n animalImage.attr('data-still',response.data[i].images.fixed_height_still.url);\n animalImage.attr('data-state',\"still\");\n animalImage.attr(\"src\", response.data[i].images.fixed_height_still.url); //This line ensures the gifs prints when a button is clicked\n $(animalDiv).append(p);\n $(animalDiv).append(animalImage);\n $('#gif-view').prepend(animalDiv);\n }\n $('#gif-view').prepend(\"<br><hr>\");\n renderButtons();\n });\n }", "function showData(item) {\nvar string='';\nvar group = item;\n //Every object is an array\n for (i=0; i < group.length; i++) {\n string = string + 'Name: ' +group[i].name + ' ' + 'Noisy: ' + group[i].noisy + ' ' + 'FightsWith: ' +group[i].fights_with + '<br>'\n }\n //Every array can be accessed by name?\n return string;\n}", "function demographic_info(index){\n let info_opt=d3.select(\".panel-body\");\n info_opt.html(\"\")\n d3.json(\"samples.json\").then(function(data){\n //getting the values from the data\n var metadata=Object.values(data.metadata);\n Object.entries(metadata[index]).forEach(([keys,values])=>{\n let new_opt=info_opt.append(\"p\")\n var item=`${keys} : ${values}`\n new_opt.text(item)\n })\n }) \n}", "function listAnimals() {\n showAnimals.innerHTML =\n `<div>\n <div class=\"animalThumbnail\" onclick=\"displayAnimal('lion')\"> <img src=\"images/lion.png\"> </img></div>\n <div class=\"animalThumbnail\" onclick=\"displayAnimal('llama')\"> <img src=\"images/llama.png\"/> </div>\n <div class=\"animalThumbnail\" onclick=\"displayAnimal('owl')\"> <img src=\"images/owl.png\"/> </div>\n <div class=\"animalThumbnail\"onclick=\"displayAnimal('turtle')\"> <img src=\"images/turtle.png\"/> </div>\n </div>`\n}", "function displayDoctors() {\n\n // Reading Doctors file.\n var d = readFromJson('doc');\n\n // For loop to run till all the doctor's are printed.\n for (var i = 0; i < d.doctors.length; i++) {\n\n // Printing doctor's id, name & speciality.\n console.log(d.doctors[i].id + \". \" + d.doctors[i].name + \" (\" + d.doctors[i].special + \")\");\n }\n}", "function demographics(selector) {\n var filter1 = data.metadata.filter(value => value.id == selector);\n var div = d3.select(\".panel-body\")\n div.html(\"\");\n div.append(\"p\").text(`ID: ${filter1[0].id}`)\n div.append(\"p\").text(`ETHNICITY: ${filter1[0].ethnicity}`)\n div.append(\"p\").text(`GENDER: ${filter1[0].gender}`)\n div.append(\"p\").text(`AGE: ${filter1[0].age}`)\n div.append(\"p\").text(`LOCATION: ${filter1[0].location}`)\n div.append(\"p\").text(`BELLY BUTTON TYPE: ${filter1[0].bbtype}`)\n div.append(\"p\").text(`WASHING FREQUENCY: ${filter1[0].wfreq}`)\n \n}", "function displayShows() {\n var results = arguments;\n\n //Iterates through arguments by 2 as two consecutive elements in the array\n //belong to one show (first is show information, second is cast information)\n for (var i = 0; i < results.length; i+=2) {\n var show = results[i][0];\n var cast = results[i+1][0];\n\n var castText = '';\n\n //Iterates through cast\n for (var j = 0; j < cast.length; j++) {\n castText += (cast[j].person.name + '; ');\n }\n\n var table = $('table');\n table.append('<tr>' +\n '<td>' + show.name + '</td>' +\n '<td><a href=\"' + show.url + '\">'+ show.url +'</a></td>' +\n '<td>' + show.summary + '</td>' +\n '<td>' + castText + '</td>' +\n '<td>' + randomizeShowClip(show.name) + '</td>' +\n '</tr>'\n );\n }\n}", "function renderHTML(data) {\n\tvar htmlString = \"\";\n\n\tfor (i = 0; i < data.length; i ++) {\n\t\thtmpString += \"<p>\" + data[i].name + \" is a \" + data[i].species + \".</p>\";\n\t}\n\n\tanimalContainer.insertAdjacentHTML('beforeend', htmlString);\n}", "function renderHTML(data){ //Sikter til funksjon som tidelere er blitt tildelt ourdata, parameter kan være samme\r\n var htmlString = \"\"; // tom string som vi skal fylle\r\n\r\n for(i = 0; i < data.length; i++){ // kjører gjennom listen\r\n htmlString += \"<p>\" + data[i].name + \" is a \" + data[i].species + \" that likes to eat \" // bruker dot notation for å få tilgang til elementer\r\n\r\n for (ii = 0; ii < data[i].foods.likes.length; ii++){ //sikter oss dypere inn i underliggende arrays, så for loops inne i en for loop\r\n if (ii <= 0){\r\n htmlString += data[i].foods.likes[ii];\r\n } else{\r\n htmlString += \" and \" + data[i].foods.likes[ii];\r\n }\r\n }\r\n\r\n htmlString += \" and dislikes \";\r\n\r\n for(iii = 0; iii < data[i].foods.dislikes.length; iii++){\r\n if(iii <= 0){\r\n htmlString += data[i].foods.dislikes[iii];\r\n } else {\r\n htmlString += \" and \" + data[i].foods.dislikes[iii];\r\n }\r\n }\r\n\r\nhtmlString += \". </p>\"\r\n\r\n }\r\n\r\n animalContainer.insertAdjacentHTML('beforeend', htmlString);\r\n}", "function renderHTML(data) {\r\n\t// create empty string\r\n\tvar htmlString = \"\";\r\n\r\n\t// loop through array\r\n\tfor (i = 0; i < data.length; i++){\r\n\t\thtmlString += \"<p>\" + data[i].name + \" is a \" + data[i].species + \" that likes to eat \"\r\n\t\tfor (ii = 0; ii < data[i].foods.likes.length; ii++){\r\n\t\t\tif (ii == 0){\r\n\t\t\t\thtmlString += data[i].foods.likes[ii];\r\n\t\t\t}\r\n\r\n\t\t\telse {\r\n\t\t\t\thtmlString += \" and \" + data[i].foods.likes[ii];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\r\n\t\thtmlString += \" and dislikes \";\r\n\r\n\t\tfor (ii = 0; ii < data[i].foods.likes.length; ii++){\r\n\t\t\tif (ii == 0){\r\n\t\t\t\thtmlString += data[i].foods.likes[ii];\r\n\t\t\t}\r\n\r\n\t\t\telse {\r\n\t\t\t\thtmlString += \" and \" + data[i].foods.likes[ii];\r\n\t\t\t}\r\n\t\t}\r\n\r\n\r\n\t\thtmlString += '.</p>'\r\n\t}\r\n\r\n\tanimalContainer.insertAdjacentHTML('beforeend', htmlString)\r\n}", "function showStats() {\n var infoName = '\\n' + pet.name.toUpperCase() + \"'s life: \";\n var infoParameters = \"Happiness: \" + pet.happiness + \", Food: \" + pet.food + \", Energy: \" + pet.energy;\n var stats = infoName + infoParameters;\n return stats;\n }", "function demographicstuff(personId) {\n //I will need a variable and go through my jsondata and grab the metadata--ID is at [0]\n var metaData = jsonData.metadata.filter((x) => x.id === parseInt(personId))[0];\n //make sure it is grabbing what I need\n //console.log(metaData)\n //Worked with a teammate on this demo HTML part\n var demoHTML = d3.select(\"#sample-metadata\");\n demoHTML.html(\"\");\n //this is similar to the unpacking done on Day 2 of Week 15\n Object.entries(metaData).forEach(([key, value]) =>\n demoHTML.append(\"h6\").text(`${key}: ${value}`));\n}", "function displayData() {\n displayUserInfo();\n displayRecipes();\n console.log(\"before\", chosenPantry)\n}", "function populatePokemanInfo(data){\n let html = \"<h2>\" + data.name + \"</h2><img src=http://pokeapi.co/media/img/\" + data.national_id + \".png><h4>Types</h4><ul>\"; //breaking to iterate through types\n for (let i = 0; i < data.types.length; i++){\n html += \"<li>\" + data.types[i].name + \"</li>\";\n }\n html += \"</ul><h4>Height</h4><p>\" + data.height + \"</p><h4>Weight</h4><p>\" + data.weight +\"</p>\";\n $(\".pokeman_info\").html(html);\n }", "function display(id){\n\tif (id == \"Tomato\"){\n\t\tdocument.getElementById('desc').innerHTML = descriptions[0] + images[0] + care[0];\n\t}\n\tif (id == \"Apple\"){\n\t\tdocument.getElementById('desc').innerHTML = descriptions[1] + images[1] + care[1];\n\t}\n if (id == \"Carrot\"){\n document.getElementById('desc').innerHTML = descriptions[2] + images[2] + care[2];\n }\n if (id == \"Onion\"){\n document.getElementById('desc').innerHTML = descriptions[3] + images[3] + care[3];\n }\n if (id == \"Eggplant\"){\n document.getElementById('desc').innerHTML = descriptions[4] + images[4] + care[4];\n }\n if (id == \"Brocolli\"){\n document.getElementById('desc').innerHTML = descriptions[5] + images[5] + care[5];\n }\n if (id == \"Potato\"){\n document.getElementById('desc').innerHTML = descriptions[6] + images[6] + care[6];\n }\n if (id == \"Peas\"){\n document.getElementById('desc').innerHTML = descriptions[7] + images[7] + care[7];\n }\n if (id == \"Corn\"){\n document.getElementById('desc').innerHTML = descriptions[8] + images[8] + care[8];\n }\n if (id == \"Pumpkin\"){\n document.getElementById('desc').innerHTML = descriptions[9] + images[9] + care[9];\n }\n}", "function renderFunction(animal){\n\t// here we assemble our giphy API URL\n\tvar queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&limit=10&api_key=dc6zaTOxFJmzC&\";\n\n\t// perfoming an AJAX GET request for the queryURL\n\t$.ajax({\n\t\turl: queryURL,\n\t\tmethod: \"GET\"\n\t})\n\n\t// after the data from the AJAX request comes back\n\t.done(function(response) {\n\t\tconsole.log(response);\n\n\t\t// appending the animalImage to the images div\n\t\tfor (var i = 0; i < response.data.length; i++) {\n\t\t\tvar container = $(\"<div>\").addClass(\"gifParent col-sm-6\");\n\t\t\t\n\t\t\t// creating and storing an img tag\n\t\t\tvar animalImage = $(\"<img>\").addClass(\"img-rounded img-responsive\");\n\t\t\tvar rating = $(\"<p>\").text(\"rating: \" + response.data[i].rating);\n\n\t\t\tconfigImg(response.data[i], animalImage);\n\n \t\tcontainer.append(rating);\n \t\tcontainer.append(animalImage);\n \t\t$(\"#images\").append(container);\n\t\t};\n\t});\n}", "function change(d) { \n var str = \"\"; //appends to string above \n for (i = 0; i < d.length; i++) { \n str += \"<p>\" + d[i].name + \" is a \" + d[i].species + \".</p>\"; \n } \n //inserts into empty div \n getAnimal.insertAdjacentHTML('beforeend', str); \n}", "function Animal(name,age,latinName,legsNo){\n this.name=name;\n this.age=age;\n this.latinName=latinName;\n this.legsNo=legsNo;\n this.printAnimal=function(){\n console.log(`${this.name} or also known as ${this.latinName}, in latin, is ${this.age} years old and has ${this.legsNo} legs!`)\n }\n}", "function displayAnimalInfo() {\n \n var animal = $(this).attr(\"data-name\");\n console.log(\"animal ==> \", animal);\n var queryURL = \"https://api.giphy.com/v1/gifs/search?api_key=ZGFCXW4DL8GQr4WH9ycZuksvEfPaRaHm&q=\" + animal +\n \"&limit=10\";\n \n console.log(\"queryURL string ==>\", queryURL);\n \n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function (response) {\n console.log(\"response ==> \", response);\n console.log(\"response.data.length ==>\", response.data.length);\n var results = response.data;\n for (var i = 0; i < response.data.length; i++) {\n if (results[i] !== \"r\" && results[i] !== \"pg-13\") {\n var animalDiv = $(\"<div>\");\n var p = $('<p>').text(\"Rating: \" + response.data[i].rating);\n \n console.log(\"Rating ==> \", response.data[i].rating);\n var animalImage = $(\"<img>\");\n animalImage.attr('src', response.data[i].images.fixed_height_still.url);\n animalImage.attr('data-still', response.data[i].images.fixed_height_still.url);\n animalImage.attr('data-animate', response.data[i].images.fixed_height.url);\n animalImage.attr('data-state', \"still\");\n animalImage.attr('rating', response.data[i].rating);\n // animalImage.attr('class', response.data[i].type);\n animalImage.attr('class', 'img-fluid gif');\n animalDiv.append(p);\n animalDiv.append(animalImage);\n \n $(\"#images\").prepend(animalDiv);\n \n \n } //end if\n } // for\n }\n \n );\n } // end function displayAnimal image and info", "displayInfo() {\n clear(dogInfo())\n\n let image = document.createElement('img')\n image.src = this.image\n\n let h2 = document.createElement('h2')\n h2.innerText = this.name\n\n let button = document.createElement('button')\n button.innerText = this.buttonText()\n button.id = `toggle${this.id}`\n \n dogInfo().appendChild(image)\n dogInfo().appendChild(h2)\n dogInfo().appendChild(button)\n }", "function displayPatients() {\n\n // Reading the Patients data.\n var p = readFromJson('pat');\n\n // For loop will run till the size of the patients.\n for (var i = 0; i < p.size - 1; i++) {\n\n // Printing the patients data.\n console.log(p.patients[i].id + \". \" + p.patients[i].name + \" \" + p.patients[i].age +\n \" \" + p.patients[i].doc);\n }\n\n // Return size of the patient's array.\n return p.size;\n}", "function renderDietInfo(diet) {\n var template = $('#dietInfoTemplate').html();\n var rendered = Mustache.render(template,\n diet\n );\n $('#dietInfo').html(rendered);\n\n //add images to each meal type\n for (var i = 0; i < types.length; i++) {\n var type = types[i];\n var id = type + 'Image';\n var image = diet[type+'image'];\n document.getElementById(id).style.backgroundImage = 'url('+image+')';\n }\n}", "function demoInfo(id) {\r\n d3.json(\"data/cardata.json\").then((data)=> {\r\n //call in metadata to demographic panel//\r\n var car_data = data.cars;\r\n var result = car_data.filter(car => car.index_col.toString() === id)[0]\r\n\r\n console.log(`test ${result}`)\r\n\r\n //select demographic panel from html//\r\n var features = d3.select(\"#cardata-cars\");\r\n //empty the demographic panel for new data//\r\n features.html(\"\");\r\n Object.entries(result).forEach((key) => {\r\n features.append(\"h5\").text(key[0]+ \": \" + key[1]);\r\n });\r\n });\r\n}", "function displayPeople(people){\n \n alert(people.map(function(person){\n return person.firstName + \" \" + person.lastName + \" \"+ person.gender + \" \" + ' ' + person.dob + ' ' + person.height +\"inches\" + \" \"+ person.weight +\" \" + person.eyeColor + \" \"+ person.occupation\n }).join(\"\\n\"));\n}", "function displayAnimal() {\n var animal = $(this).attr(\"data-name\");\n //call to giphy database\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=pKCHSjye8BR1VMWxmo4mxbHcwO58FBKt\";\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n\n })\n\n .done(function (response) {\n var { data, meta } = response\n console.log(response);\n\n // Loop through each result item \n for (var i = 0; i < response.data.length; i++) {\n // put gifs in a div\n var animalDiv = $(\"<div class='animal'>\");\n\n // Show results of gifs\n var results = response.data;\n var rating = response.Rated;\n\n // pull rating of gif\n var p = $(\"<p>\").text(\"Rating: \" + results[i].rating);\n\n // pull gif\n var animalImage = $(\"<img class='image'>\");\n animalImage.attr(\"src\", results[i].images.fixed_height_still.url);\n //paused images\n animalImage.attr(\"data-still\", results[i].images.fixed_height_still.url);\n //animated images\n animalImage.attr(\"data-animate\", results[i].images.fixed_height.url);\n //how images come in, already paused\n animalImage.attr(\"data-state\", \"still\");\n animalImage.addClass(\"gif\");\n animalDiv.append(p);\n animalDiv.append(animalImage);\n // add new div to existing divs\n $(\"#animal-view\").prepend(animalDiv);\n }\n });\n}", "function displayData(data){\n\tlet display_with_poster = `\n\t\t\t<a href=\"${data.id}\" class=\"moreInfo\">\n\t\t\t<img class=\"poster\" src=\"http://image.tmdb.org/t/p/w500/${data.poster_path}\">\n\t\t\t<h3 class=\"title\">${data.title}</h3>\n\t\t\t</a>\n\t\t\t<p class=\"year\">${data.release_date}</p>\n\t\t\t`\n\tlet display_no_poster = `\n\t\t\t<a href=\"${data.id}\" class=\"moreInfo\">\n\t\t\t<img class=\"poster\" src=\"img/no_poster.png\">\n\t\t\t<a href=\"${data.id}\">\n\t\t\t<h3 class=\"title\">${data.title}</h3>\n\t\t\t</a>\n\t\t\t<p class=\"year\">${data.release_date}</p>\n\t\t\t`\n\tif(data.poster_path === null){\n\t\t$(`.movie${data.id}`).html(display_no_poster);\n\t}\n\telse{\n\t\t$(`.movie${data.id}`).html(display_with_poster);\n\t}\n}", "function animal() {\n return {\n restrict: 'E',\n template: `\n <div class=\"animal\" ng-repeat=\"animal in animals | orderBy: sortBy | filter: search\">\n <div class=\"info-container\">\n <a href=\"{{animal.profileLink}}\"><img class=\"pic\" src=\"{{animal.pic}}\" /></a>\n <div class=\"info\">\n <h2 class=\"name\">{{animal.name}}</h2>\n <span class=\"breed\">{{animal.breed}} | </span>\n <span class=\"sex\">{{animal.sex}} | </span>\n <span class=\"age\">{{animal.age}}</span>\n <p class=\"description\">{{animal.description}}</p>\n <p class=\"location\">Location: {{animal.location}}</p>\n </div>\n </div>\n </div>\n `\n };\n}", "function fn_createDOMAnimalList(detailType) {\n const dataJSON_Object = fn_getDataJSON(dataJSONURL);\n animalDescription.innerHTML = `\n <h3 class=\"text-capitalize mt-3\">List of ${detailType}</h3>\n \n `;\n for (let _animal of dataJSON_Object[detailType]) {\n animalListDOM.innerHTML += `\n <div class=\"animalList-item col-12 col-sm-6 col-md-4 mt-3 mb-3 \" animalID=\"${_animal.id}\"> \n <a href=\"./animals.html?detailType=${detailType}&detailID=${_animal.id}\">\n <img\n class=\"img-fluid animalList-item-imgURL\"\n src=\"./images/${_animal.imgURL}\"\n alt=\"\"\n />\n <h4>${_animal.name}</h4> \n </a>\n <p>${_animal.description}</p> \n </div>\n `;\n }\n}", "function showCats(jsonObj) {\n // Save reference to cats\n let cats = jsonObj.cats;\n\n // for every cat in the array\n for (let i = 0; i < cats.length; i++) {\n\n // build the elements\n let thisCat = document.createElement('div');\n let name = document.createElement('h2');\n let blurb = document.createElement('p');\n\n // Fill the elements\n name.innerHTML = cats[i].name;\n // build a description\n let descript = cats[i].name + ' is a ' + cats[i].age + ' year old '\n + cats[i].species + ' that loves';\n\n // get the array of favourite foods\n let favFoods = cats[i].favFoods;\n // loop through to add all foods to the description\n for (let a = 0; a < favFoods.length; a++) {\n // Add food\n descript = descript + ' ' + favFoods[a];\n\n if (a == (favFoods.length - 1)) {\n // end with a period if it's the last food\n descript = descript + '.';\n } else {\n // end with a comma if it's not the last food\n descript = descript + ',';\n }\n }\n\n // add description to the element\n blurb.innerHTML = descript;\n\n // append all elements into the cat's div\n thisCat.appendChild(name);\n thisCat.appendChild(blurb);\n // append the cat's div to the parent div\n div.appendChild(thisCat);\n }\n}", "function detailView(character) {\n return `<div>\n <img src=\"${character.img}\" />\n <h2>${character.name}</h2>\n <h3>of ${character.location}</h3>\n </div>`;\n}", "function getDescription(dog) {\n console.log(dog.description);\n\n}", "function showMale() {\n let bigList = document.getElementById(\"bigList\");\n for (var i = 0; i < data.length; i++) {\n \n if (data[i].constructor.name == \"Male\") {\n bigList.innerHTML += data[i].render();\n }\n }\n}", "function listar(){ \n var dog = JSON.parse(tbDogs[tbDogs.length-1]);\n $(\"#vitrine\").append(\n '<div class=\"resultado-dog\">'+\n '<img class=\"img-dog\" src=\"'+dog.Foto+'\">'+\n '<div class=\"texto-foto '+dog.Cor+' '+dog.Font+'\">'+\n '<span>Raça:</span><span class=\"raca-resultado\">'+dog.Raca+'</span><br>'+\n '<span>Nome:</span><span class=\"nome-resultado\">'+dog.Nome+'</span>'+ \n '</div>'+ \n '</div>')\n \n }", "function printCats(catArray) { \n for (var i = 0; i < catArray.length; i++) {\n var ballOfString = \"\";\n ballOfString += `<cat>`;\n ballOfString += `<header><p>Name: ${catArray[i].name}</p><p>Title: ${catArray[i].title}</p></header>`;\n ballOfString += `<section><div class=\"image-wrapper\"><img src=${catArray[i].image}></div><p class=\"bio\">Bio: ${catArray[i].bio}</p></section>`;\n ballOfString += `<footer><p>Lifespan: ${catArray[i].lifespan.birth} - ${catArray[i].lifespan.death}</p></footer>`;\n ballOfString += `</cat>`;\n catBox.innerHTML += ballOfString;\n };\n }", "function displayData(pokeData) {\n const entry = document.createElement('h2')\n entry.innerHTML = 'Pokedex Entry:' + pokeData.id\n const pokeInfo = document.querySelector('.pokeInfo')\n pokeInfo.append(entry)\n\n const name = document.createElement('h2')\n name.innerHTML = 'Name:' + pokeData.name\n removeText()\n pokeInfo.append(name)\n\n const flavorText = document.createElement('h2')\n flavorText.innerHTML = pokeData.flavor_text_entries[0].flavor_text\n pokeInfo.append(flavorText)\n pokeData.style.display = 'none'\n}", "function showPerson(person){\n const items = review[person];\n\n img.src = items.img;\n author.textContent = items.name;\n job.textContent = items.job;\n info.textContent = items.text;\n console.log(items);\n}", "function displayPerson(person){\n let personInfo = \"First Name: \" + person.firstName + \"\\n\";\n personInfo += \"Last Name: \" + person.lastName + \"\\n\";\n personInfo += \"Weight: \" + person.weight + \"\\n\";\n personInfo += \"Height: \" + person.height + \"\\n\";\n personInfo += \"Eyecolor: \" + person.eyecolor + \"\\n\"; \n personInfo += \"Occupation: \" + person.occupation + \"\\n\";\n personInfo += \"DOB: \" + person.dob + \"\\n\"; \n personInfo += \"Gender: \" + person.gender + \"\\n\"; \n // personInfo += \"Age: \" + person.age(person.dob) + \"\\n\"; \n\n return personInfo;\n}", "function displayData(data) {\n \n container.innerHTML = '';\n\n data.forEach(function (fact) {\n container.innerHTML += `<div class=\"product\"><div class=\"row\"><div class=\"col-sm-8\"><h3>Title: ${fact.title}</h3>\n <img src=\"${fact.image_url}\" ><p>Price: ${fact.price}</p>\n </div></div>\n </div>`;\n });\n}", "function showCollection(array){\n // - Console.log the number of items in the array.\n console.log(array);\n // - Loop over the array and console.log each album's information formatted like: `TITLE by ARTIST, published in YEAR`.\n for (let i = 0; i < array.length; i++){\n console.log(`${array[i].title} by: ${array[i].artist}, Published: ${array[i].yearPublished}`);\n\n } // end of foor loop\n } // end of of showCollection", "function showStrawFact(data) { //data accepting what is happening up top. \n //debugger; //comment out after bc you dont need to see what you did wrong anymore\n //parse the DB info and put it where it neds to go\n const { city, state, fact } = data; //destructuring assignmnet => MDN JS destructuring \n\n\n //might change some of this stuff for infographic all this is AJAX\n //grab the elements we need, and populate them with data\n document.querySelector('.city1').textContent = city; //will have three of these lines except with the selector in the quotes\n document.querySelector('.state').textContent = state;\n document.querySelector('.facts').textContent = fact;\n }", "function displayResults(articles) {\n // First, empty the table\n $(\"tbody\").empty();\n\n // Then, for each entry of that json...\n Article.forEach(function(articles) {\n // Append each of the animal's properties to the table\n $(\"tbody\").append(\"<tr><td>\" + Article.headline + \"</td>\" +\n \"<td>\" + Article.summary + \"</td>\" +\n \"<td>\" + Article.url + \"</td></tr>\");\n });\n}", "function displayDogs(count) {\n $('#dogs').empty();\n for(var i=0; i<count; i++) {\n $('#dogs').append(\"<img src='\" + dog(i) + \"' />\");\n }\n}", "function displayData(data) {\n for(const organism of data) {\n const sightingsAsHTML = convertSightingsToHTML(organism.sightings, organism.name);\n\n const organismID = cuid();\n\n $(\".wildlife-results .results-list\").append(`\n <li class=\"wildlife-result\" data-organism-id=\"${organismID}\">\n <section class=\"sightings\">\n ${sightingsAsHTML}\n </section>\n\n <h3 class=\"organism-name\">${organism.name}</h3>\n <a href=\"${organism.wikiURL}\" target=\"_blank\">\n ${organism.wikiURL}${newWindowIconGreen}\n </a>\n </li>\n `);\n\n /**\n * Some organisms may not have their wikipedia intros if the\n * Wikipedia fetch couldn't find anything, or if some other error\n * occurred with the fetch\n */\n if (organism.wikiIntro != undefined) {\n $(`.wildlife-result[data-organism-id=\"${organismID}\"]`)\n .find(\".organism-name\")\n .after(`<p>${organism.wikiIntro}</p>`);\n }\n }\n\n /**\n * Set the width of each sighting (photo and caption) in each\n * organism's slideshow to the with of the photo\n */\n $('.organism-photo').each((i, elem) => {\n $(elem).on('load', (event) => {\n const img = event.currentTarget;\n const width = $(img).actual(\"width\");\n $(img).closest(\".sighting\").css('width', `${width}px`);\n });\n });\n }", "printMovieInfo(data) {\n const rottenTomatoes = this.rottenTomatoesRating(data);\n const output = [\n `Title: ${data.Title}`,\n `Year: ${data.Year}`,\n `Rating: IMDb ${data.imdbRating}`,\n ` Rotten Tomatoes ${rottenTomatoes}`,\n `Country: ${data.Country}`,\n `Language: ${data.Language}`,\n `Plot: ${data.Plot}`,\n `Actors: ${data.Actors}`\n ];\n\n console.log(output.join(\"\\n\"));\n }", "function show() {\n best.html(population.pop[0].genes);\n averageFitness.html(population.averageFitness);\n generationNum.html(gNum);\n phrases.html(\"\");\n\n var phrs = \"\";\n\n for (let i = 1; i < population.pop.length && i < nPhrases.val(); i++) {\n phrs += '<span>' + population.pop[i].genes.join(\"\") + '</span>';\n }\n\n phrases.html(phrs);\n }", "function\tgetData () {\n\tvar data = JSON.parse(event.target.responseText);\n\tvar currentBrand = \" \";\n\tvar brand;\n\tvar type;\n\tvar volume;\n\tvar price;\n// Loop through dog_brands\n\tfor (i = 0; i < data.dog_brands.length; i++) {\n\t\t// variable to hold obj prop\n\t\tbrand = data.dog_brands[i].name;\n\t\t// create div wih unique id\n\t\tcurrentBrand += `<div>`;\n\t\tcurrentBrand += `<h1 id=\"b${i + 1}\" class=\"brand\">`;\n\t\tcurrentBrand += `${brand}`;\n\t\tcurrentBrand += `</h1>`;\n\t\t// repeat till we get through object\n\t\tfor (j = 0; j < data.dog_brands.length; j++) {\n\t\t\ttype = data.dog_brands[i].types[j].type;\n\t\t\tcurrentBrand += `<div class=\"infoDiv\">`;\n\t\t\tcurrentBrand += `<h2>`;\n\t\t currentBrand += `${type} :`;\n\t\t currentBrand += `</h2>`;\n\t \t for (x = 0; x < data.dog_brands.length; x++) {\n\t\t\t\tvolume = data.dog_brands[i].types[j].volumes[x].name;\n\t\t\t\tprice = data.dog_brands[i].types[j].volumes[x].price;\n\t\t\t\tcurrentBrand += `<div>`;\n\t\t\t\tcurrentBrand += `<h2>`;\n\t\t \tcurrentBrand += `${volume} `;\n\t\t \tcurrentBrand += `$ ${price}`;\n\t \t \tcurrentBrand += `</h2>`;\n\t\t\t\tcurrentBrand += `</div>`;\n\t \t }\n\t\t\t\tcurrentBrand += `</div>`;\n\n\t\t}\t\n\t\t\t\tcurrentBrand += `</div>`;\n\t}\n\tdogContainer.innerHTML = currentBrand;\n}", "function showData(data){\n const main = document.getElementById('main');\n \n const author = document.createElement('h2');\n t = document.createTextNode(data.by);\n author.appendChild(t);\n\n const title = document.createElement('p');\n t = document.createTextNode(`Title = ${data.title}`);\n title.appendChild(t);\n\n const type = document.createElement('p');\n t = document.createTextNode(`Type = ${data.type}`);\n type.appendChild(t);\n\n const score = document.createElement('p');\n t = document.createTextNode(`${data.score} votes | ${data.descendants} comments`);\n score.appendChild(t);\n\n main.append(author);\n main.append(title);\n main.append(type);\n main.append(score);\n \n}", "function showCharacters(array) {\n let html = \"\"\n array.map(\n character => {\n html += `<article>`\n html += `<h2>${character.name}</h2>`\n html += `<img src=\"${character.image}\" />`\n html += `<div>\n <ul>\n <li>Status: ${character.status}</li>\n <li>Gender: ${character.gender}</li>\n <li>Species: ${character.species}</li>\n <li>Created: ${character.created}</li>\n </ul> \n </div>`\n html += `</article>`\n }\n )\n\n const main = document.querySelector(\"main\")\n main.innerHTML = html\n}", "function showFemale() {\n let bigList = document.getElementById(\"bigList\");\n for (var i = 0; i < data.length; i++) {\n \n if (data[i].constructor.name == \"Female\") {\n bigList.innerHTML += data[i].render();\n } \n }\n}", "function showPerson() {\n $('body').find('.name').text(\"Name: \" + muArray[number].name);\n $('body').find('.git').text(\"github: \" + muArray[number].git_username);\n $('body').find('.shoutout').text(\"Shoutout: \" + muArray[number].shoutout);\n }", "function displayInitialSample(){\n\t\t//probably call it when starwars is clicked\n\t\tclearInfo();\n\t\t$spanInfo.html(\"<h4><b>Sample piece of data from each class on the API</b></h4>\");\n\t\t// $spanInfo.append(\"<h4 class='label label-info lb-md'>Starships, Vehicles, Species, Films, Planets, People</h4>\");\n\t\t$spanInfo.append(\"<table class='table tableHeaderHome label-default lb-sm'><th>Starships</th><th>Vehicles</th><th>Species</th><th>Films</th><th>Planets</th><th>People</th></table>\");\n\t\t$table.show();\n\t\t//print out the sample 1 per each.\n\t\tgenerateStarships(2);//no values on 1\n\t\tgenerateVehicles(4);//no values on first 3\n\t\tgenerateSpecies(1);\n\t\tgenerateFilms(1);\n\t\tgeneratePlanets(1);\n\t\tgeneratePeople(1);\t\t\t\t\t\t\n\t}", "function displayPatient(pt) {\n document.getElementById('patient_name').innerHTML = getPatientName(pt);\n document.getElementById('gender').innerHTML = pt.gender;\n document.getElementById('dob').innerHTML = pt.birthDate;\n}", "function displayAnimal() {\n var animal = $(this).attr(\"data-name\");\n //constructing a URL to search Giphy for the animal\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal + \"&api_key=dc6zaTOxFJmzC&limit=10\";\n console.log(queryURL); // displays the constructed URL\n \n //performing our ajax GET request\n $.ajax ({\n url: queryURL,\n method: 'GET'\n })\n //After the data comes back from the API\n .done(function(response) {\n console.log(response); // console test to make sure something returns\n \n //Deleting the animals prior to adding new animals\n $(\"#animalView\").empty();\n var results = response.data;\n if ( results == \"\" ) {\n alert (\"There is no animal for this selected button !\");\n }\n //looping through the array of animals\n for (var i = 0; i < results.length; i++) {\n \n // div for the animalgifs to go inside\n var gifDiv = $(\"<div>\");\n gifDiv.addClass(\"gifDiv\");\n //getting rating of animalGifs\n var gifRating = $(\"<p>\").text(\"Rating: \" + results[i].rating);\n gifDiv.append(gifRating);\n \n //Creating an image tag\n var animalImage = $(\"<img>\");\n // still image stored into src of image\n animalImage.attr('src', results[i].images.fixed_height_small_still.url);\n // still image\n animalImage.attr (\"data-still\",results[i].images.fixed_height_small_still.url);\n //Animated image\n animalImage.attr (\"data-animate\",results[i].images.fixed_height_small.url);\n // Set the image state\n animalImage.attr (\"data-state\", \"still\");\n animalImage.addClass(\"image\");\n gifDiv.append(animalImage);\n // Pulling still image of gif \n // adding div of gifs to Buttons-View\n $(\"#animalView\").prepend(gifDiv);\n }\n });\n }", "function displayPatient(pt) {\n document.getElementById(\"patient_name\").innerHTML = getPatientName(pt);\n document.getElementById(\"gender\").innerHTML = pt.gender;\n document.getElementById(\"dob\").innerHTML = pt.birthDate;\n}", "function characterDisplay() {\n //display the first character on the page\n characterSelect(characters[0].name, 1, characters[0].class, characters[0].portrait, characters[0].colors.dark, characters[0].colors.light, characters[0].stats);\n //loop through array and append all of the sprite version\n for (var i = 0; i < characters.length; i++) {\n var chibiContainer = $(\"<div>\").addClass(\"character-container\").attr({\n \"data-class\": characters[i].class,\n \"data-key\": i + 1\n });\n var characterImage = $(\"<img>\").attr(\"src\", characters[i].chibi);\n chibiContainer.append(characterImage);\n $(\".character-list\").append(chibiContainer);\n }\n }", "function ShowMetadata(sampleId)\n{\n // name of function and parameter called\n console.log(`Calling ShowMetadata(${sampleId})`);\n\n // call data\n d3.json(\"samples.json\").then((data) => {\n\n\n var metadata = data.metadata;\n var resultArray = metadata.filter(md => md.id == sampleId);\n var result = resultArray[0];\n\n var PANEL = d3.select(\"#sample-metadata\");\n // clear old metadata\n PANEL.html(\"\");\n\n Object.entries(result).forEach(([key, value]) => {\n // flesh out with html f string\n var textToShow = `${key}: ${value}` ;\n\n PANEL.append(\"h6\").text(textToShow);\n });\n });\n}", "function displayDataList(data) {\n let htmlContent = ''\n data.forEach(function (item) {\n htmlContent += `\n <div class=\"col-sm-3\">\n <div class=\"card mb-2\">\n <img class=\"card-img-top \" src=\"${POSTER_URL}${item.image}\" alt=\"Card image cap\">\n <div class=\"card-body movie-item-body\">\n <h6 class=\"card-title\">${item.title}</h6>\n <div class=\"d-flex flex-row flex-wrap\">\n `\n for (let i = 0; i < item.genres.length; i++) {\n htmlContent += `<div class=\"genresIcon\">${genresTypes[item.genres[i]]}</div>`\n }\n htmlContent += `\n </div>\n </div >\n </div >\n </div >\n `\n })\n dataPanel.innerHTML = htmlContent\n }", "function fn_createDOMAnimalDetail(detailType, detailID) {\n const dataJSON_Object = fn_getDataJSON(dataJSONURL);\n\n for (let _animal of dataJSON_Object[detailType]) {\n if (_animal.id === detailID) {\n animalDetailDOM.innerHTML += `\n \n <div class=\"row justify-content-center\">\n <div class=\"col-12 col-md-9 bg-light pt-3 border\">\n <div class=\"row\">\n <div class=\"col-12 col-md-6\">\n <img class=\"img-fluid\" src=\"./images/${_animal.imgURL}\" alt=\"\" dataName=\"imgURL\"/>\n </div>\n <div class=\"col-12 col-md-6 pt-3 pt-md-0\">\n <h4 dataName=\"name\">${_animal.name}</h4>\n <span dataName=\"description\">\n ${_animal.description}\n </span>\n </div>\n </div>\n <div class=\"row mt-3\">\n <div class=\"col-12 col-sm-4\">\n <strong>Animal type</strong>\n <p dataname=\"animalType\">${_animal.animalType}</p>\n <strong>Diet</strong>\n <p dataName=\"diet\">${_animal.diet}</p>\n </div>\n <div class=\"col-12 col-sm-4\">\n <strong>Habitat</strong>\n <p dataName=\"habitat\">${_animal.habitat}</p>\n <strong>Range</strong>\n <p dataName=\"range\">${_animal.range}</p>\n </div>\n <div class=\"col-12 col-sm-4\">\n <strong>Size</strong>\n <p dataName=\"size\">${_animal.size}</p>\n <strong>Relatives</strong>\n <p dataName=\"relatives\">${_animal.relatives}</p>\n </div>\n </div>\n </div>\n </div>\n \n \n `;\n }\n }\n}", "function appendFreeAnimal() {\n\t\t\t\t$('#cAnimalTable').append(animalTableRow(animal, null));\n\t\t\t}", "function dyna_demos(id) {\n d3.json(\"data/samples.json\").then((demodata) => {\n var metadata = demodata.metadata;\n // Returns Object:Object when you use `${}`\n console.log(metadata);\n\n // Select sample-metadata section\n var demographicInfo = d3.select(\"#sample-metadata\");\n // Clear contents\n // demographicInfo.html(\"Test\");\n demographicInfo.html(\"\");\n\n var result = metadata.filter(meta => meta.id.toString() === id)[0];\n\n // 5. Display each key-value pair from the metadata JSON object somewhere on the page.\n Object.entries(result).forEach((key) => {\n demographicInfo.append(\"h6\").text(key[0] + \": \" + key[1]);\n });\n });\n}", "function randomPet(){\n\n // Array for choosing random animal for displaying random animal \n // from a random location within US\n var randomAnimalArray = [\"dog\",\"cat\",\"horse\",\"bird\",\"barnyard\"];\n\n // variable for storing the random randomly selected animal from the array\n randomSearch = randomAnimalArray[Math.floor(Math.random() * (5 - 0)) + 0]; \n\n // Passing the variables into the url for API call\n var url = \"https://api.petfinder.com/pet.getRandom?format=json&key=0dbe85d873e32df55a5a7be564ae63a6&callback=?&animal=\"+randomSearch+\"&output=basic\";\n \n // API call to get the data to show the random animal picture and information using \n //pet.getRandom method\n $.ajax({\n url: url,\n dataType: 'jsonp', \n method: 'pet.getRandom',\n }).done(function(result) {\n \n \n // Rendering the images of two randomly selected animals \n $(\".randomImage\").append('<tr><td>'+\"<img src=\"+result.petfinder.pet.media.photos.photo[1].$t+\"/>\"+'</td><td>'+result.petfinder.pet.name.$t+'</td><td> - from '+result.petfinder.pet.contact.city.$t+',</td><td>'+result.petfinder.pet.contact.state.$t+'</td></tr>');\n \n \n //<td>'+result.petfinder.pet.age.$t+\n //</td><td>'+result.petfinder.pet.animal.$t+\n \n \n\n});\n}", "function displayVerbs() {\n // Select all of them in the array\n for (let i = 0; i < images[currentImage].verbs.length; i++) {\n // Create divs for them\n let $verbContainer = $('<div class=\"verbs\"></div>');\n // Put them in the container\n $verbContainer.appendTo(\".verbPool\");\n // Apply the text\n $verbContainer.text(images[currentImage].verbs[i]);\n }\n}", "function displayMetadata(value) {\n d3.json(\"samples.json\").then((data) => {\n let metadataArray = data.metadata.filter(selected => selected.id == value);\n let metadata = metadataArray[0];\n\n let wordbox = d3.select(\"#sample-metadata\");\n wordbox.html(\"\") // resets html to be blank\n // this should work just like on the ufo assignment....\n Object.entries(metadata).forEach(([key,value]) => {\n wordbox.append(\"h6\").text(`${key} : ${value}`)\n })\n })\n}", "function rederHtml(data){\n\t\n\t// create a variable that will hold the html code\n\tvar htmlString = \"\";\n\t//loop though the data and show it using html\n\tfor(i=0; i< data.length; i++){\n\t\thtmlString += \"<p>\" + data[i].name + \" is a \" + data[i].species + \" that likes to eat \";\n\t\t\n\t\t// loop though the list favorites food likes\n\t\tfor(a =0; a< data[i].foods.likes.length; a++){\n\t\t\t// if it is the first element\n\t\t\tif(a == 0){\n\t\t\t\t\n\t\t\t\thtmlString +=\tdata[i].foods.likes[a];\n\t\t\t} else { // otherwise\n\t\t\t\thtmlString +=\t\" and \" + data[i].foods.likes[a];\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\thtmlString += ' and dislikes ';\n\t\t\t\n\t\t\t// loop though the list dislikes food\n\t\t\tfor(a =0; a< data[i].foods.dislikes.length; a++){\n\t\t\t\t// if it is the first element\n\t\t\t\tif(a == 0){\n\t\t\t\t\t\n\t\t\t\t\thtmlString +=\tdata[i].foods.dislikes[a];\n\t\t\t\t} else { // otherwise\n\t\t\t\t\thtmlString +=\t\" and \" + data[i].foods.dislikes[a];\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\n\t\t\t\n\t\t}\n\t\t}\n\t\thtmlString += \"</p> <hr />\";\n\t\t\n\t}\n\t\n\t// append html to the page\n\tanimalContainer.insertAdjacentHTML('beforeend', htmlString);\n}", "function renderInfo(data){\n\n console.log(data);\n\n //display title\n title.innerHTML = data.name;\n\n //display image\n image.src = data.image.url;\n image.alt=\"Image not found\";\n \n //display favourite\n if(favList!==null && favList.includes(id)){\n fav.innerHTML = '<i id=\"heart-icon\" class=\"fas fa-heart\"></i>';\n }\n else{\n fav.innerHTML = '<i id=\"heart-icon\" class=\"far fa-heart\"></i>';\n }\n\n //display powerstats\n for(var i in data.powerstats){\n document.getElementById(i).innerHTML = data.powerstats[i];\n }\n\n //display biography\n for(var i in data.biography){\n document.getElementById(i).innerHTML = data.biography[i];\n }\n\n //display appearance\n for(var i in data.appearance){\n document.getElementById(i).innerHTML = data.appearance[i];\n }\n\n //display work\n for(var i in data.work){\n document.getElementById(i).innerHTML = data.work[i];\n }\n\n //display connections\n for(var i in data.connections){\n document.getElementById(i).innerHTML = data.connections[i];\n }\n}", "function displayPatient(pt) {\n document.getElementById('patient_name').innerHTML = getPatientName(pt);\n document.getElementById('gender').innerHTML = pt.gender;\n document.getElementById('dob').innerHTML = pt.birthDate;\n}", "showDogsBreed(){\r\n const elem = document.querySelector(\".dogsBreed\");\r\n elem.innerHTML = '';\r\n for (let i = 0; i<this.dogsBreed.length; i++){\r\n let li = document.createElement('li');\r\n li.innerHTML = this.dogsBreed[i];\r\n elem.appendChild(li);\r\n }\r\n }", "function showDemographicInfo(selectedSampleID) {\n\n console.log(\"showDemographicInfo: sample =\", selectedSampleID);\n\n d3.json(\"samples.json\").then((data) => {\n\n var demographicInfo = data.metadata;\n\n var resultArray = demographicInfo.filter(sampleObj => sampleObj.id == selectedSampleID)\n var result = resultArray[0];\n console.log(result)\n\n var panel = d3.select(\"#sample-metadata\");\n // clear panel variable on every load\n panel.html(\"\");\n\n Object.entries(result).forEach(([key, value]) => {\n var labelsToShow = `${key}: ${value}`;\n panel.append(\"h6\").text(labelsToShow);\n });\n });\n\n}", "function displaydemodata(id) {\r\n\t\t\t\tvar demodata = d3.select(\".sample-metadata\");\r\n\t\t\t\tdemodata.html(\"\")\r\n\t\t\t\tdemodata.append(\"li\").text(`id: ${data.metadata[id_index].id}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`ethnicity: ${data.metadata[id_index].ethnicity}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`gender: ${data.metadata[id_index].gender}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`age: ${data.metadata[id_index].age}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`location: ${data.metadata[id_index].location}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`bbtype: ${data.metadata[id_index].bbtype}`);\r\n\t\t\t\tdemodata.append(\"li\").text(`wfreq: ${data.metadata[id_index].wfreq}`);\r\n\t\t\t}", "function showGoonies(){\n var result = \"\"; \n \n for(var i = 0; i < goonies.records.length; i++){\n \n result += \"<p><b>Name: </b>\" + goonies.records[i].firstName + \" \" + goonies.records[i].lastName + \", <b>Phone: </b>\" + goonies.records[i].cell + \"</p>\";\n }\n document.getElementById(\"div_goonies\").innerHTML = result;\n}", "function DisplayMetadata(sampleId) {\n console.log(`DisplayMetadata(${sampleId})`);\n\n // Clear demographic info \n document.getElementById(\"sample-metadata\").innerHTML = \"\";\n\n d3.json(\"data/samples.json\").then(data => {\n\n var metaData = data.metadata;\n var resultArray = metaData.filter(s => s.id == sampleId);\n var result = resultArray[0];\n\n // Assigning the information to extract from the dataset\n var id = result.id;\n var ethnicity = result.ethnicity;\n var gender = result.gender;\n var age = result.age;\n var location = result.location;\n var bbtype = result.bbtype;\n var wfreq = result.wfreq;\n var info = [id,ethnicity,gender,age,location,bbtype,wfreq];\n\n // Append new data to a list within the demographic box\n var ul = d3.select(\"#sample-metadata\").append(\"ul\");\n ul.append(\"li\").text(`id: ${id}`);\n ul.append(\"li\").text(`ethnicity: ${ethnicity}`);\n ul.append(\"li\").text(`gender: ${gender}`);\n ul.append(\"li\").text(`age: ${age}`);\n ul.append(\"li\").text(`location: ${location}`);\n ul.append(\"li\").text(`bbtype: ${bbtype}`);\n ul.append(\"li\").text(`wfreq: ${wfreq}`);\n\n })\n}", "function displayBreed(image) {\n \n $('#cargador').fadeOut('slow');\n $('#breed_image').attr('src', image.url);\n $(\"#breed_data_table tr\").remove();\n \n $('#breed_image').show();\n var breed_data = image.breeds[0]\n var annosVida = breed_data.life_span;\n var altura = breed_data.height.metric;\n var peso = breed_data.weight.metric;\n console.log(\"Años: \"+annosVida)\n console.log(\"Altura: \"+altura+\" cm\")\n console.log(\"Peso: \"+peso+ \"kg\")\n $(\"#breed_data_table\").append(\"<tr><td style='text-align: right'>Años de Vida: </td><td style='text-align: left'>\" + annosVida + \"</td></tr>\");\n $(\"#breed_data_table\").append(\"<tr><td style='text-align: right'>Altura: </td><td style='text-align: left'>\" + altura+\" cm</td></tr>\");\n $(\"#breed_data_table\").append(\"<tr><td style='text-align: right'>Peso: </td><td style='text-align: left'>\" + peso+ \" kg</td></tr>\");\n \n}", "displayAllThings (allThings) {\n\n let outputAll = '<h3> Available Things: </h3>';\n for (let i = 0; i< allThings.length; i++) {\n\n _name = allThings[i].Thing_name\n _uid = allThings[i].Thing_UID\n _status = allThings[i].Thing_status\n\n outputAll +=\n ` <ul>\n <li> <b>---- Thing ${i+1} </b> </li>\n <li> <b> Thing- Name </b>: ${_name} </li>\n <li> <b>Thing- UID </b>: ${_uid} </li> \n <li> <b>Thing- Status </b>: ${_status} </li> \n </ul> \n `\n } \n document.getElementById ('outputAll').innerHTML = outputAll;\n }", "function renderDogsToPage(dogs){\n dogs.map(renderSingleDogToPage).join('')\n }", "function displayPetData(pets, parentDiv) {\n pets.forEach((item, index) => {\n var template = document.getElementById('template-pet');\n var templateNode = template.content.cloneNode(true);\n templateNode.querySelector('#txt-petname').textContent = item.Name;\n templateNode.querySelector('#txt-constraint').textContent = item.Consts;\n parentDiv.appendChild(templateNode);\n });\n }", "function displayInfo(code) {\n const dataName = nationsData.find(country => country.alpha3Code === code);\n document.querySelector(\"#flag img\").src = dataName.flag;\n document.querySelector(\"#flag img\").alt = `Flag of ${dataName.name}`;\n document.getElementById(\"capital\").innerHTML = dataName.capital;\n document.getElementById(\"population\").innerHTML = dataName.population.toLocaleString(\"en-US\");\n document.getElementById(\"languages\").innerHTML = dataName.languages.filter(c => c.name).map(c => `${c.name}`).join(\", \");\n document.getElementById(\"currencies\").innerHTML = dataName.currencies.filter(c => c.name).map(c => `${c.name} (${c.code})`).join(\", \");\n\n}", "function prettyArchiveVisualization(i) {\n console.log(archive[i].name\n +\" \"+archive[i].dateOfEvent\n +\" (Minors are \"+(archive[i].onlyAdults ? \"not allowed.)\" : \"allowed.)\"));\n}", "function dogPictureInfo(name, breed, fee) {\n alert(`Name: ${name}\\nBreed: ${breed}\\nAdoption Fees: $${fee}`);\n}", "function showData(data){\n\talert('what');\n\tfor(var i=0; i<data.length; i++){\n\t\tvar currItem = data[i];\n\t\tvar listItem = $('<li></li>');\n\t\tvar paragraph = $('<p></p>');\n\t\tvar image = $('<img src=\"'+currItem.url+'\">');\n\t\tlistItem.text(data[i].name);\n\t\tlistItem.append(image);\n\t\t$dataList.append(listItem);\n\t}\n}", "function showRickandmorty(rickandmorty) {\n for (let i = 0; i < rickandmorty.length; i++) {\n containerRoot.innerHTML += `\n <div>\n <div class=\"Cards\">\n <div class=\"Cards-header\">\n <div class=\"img\">\n <img src=\"${rickandmorty[i].image}\">\n </div>\n <div class=\"Cards-body\"\n <h1>${rickandmorty[i].name}</h1>\n </div>\n </div>\n </div>\n </div>\n `\n\n }\n\n}", "function Animal () {\n\tthis.name = \"animal\";\n\tthis.showName = function () {\n\t\tconsole.log(this.name);\n\t}\n}", "function displayTreasure(array, size) {\n for (var i=0;i<size;i++)\n array[i].display();\n }", "function populateDemoInfo(patientID) {\n var demographicInfoBox = d3.select(\"#sample-metadata\");\n d3.json(\"samples.json\").then(data => {\n // console.log(data)\n })\n d3.json(\"samples.json\").then((data) => {\n var metadata = data.metadata;\n var resultArray = metadata.filter(s => s.id == patientID);\n var result = resultArray[0];\n var demographicInfoBox = d3.select(\"#sample-metadata\");\n demographicInfoBox.html(\"\");\n Object.entries(result).forEach(([key, value]) => {\n demographicInfoBox.append(\"h6\").text(`${key.toUpperCase()}: ${value}`);\n });\n });\n}", "function showDetail(d) {\r\n // change outline to indicate hover state.\r\n d3.select(this).attr('stroke', 'black');\r\n\r\n var content = '<span class=\"name\">Title: </span><span class=\"value\">' +\r\n d.name +\r\n '</span><br/>' +\r\n '<span class=\"name\">Amount Awarded: </span><span class=\"value\">$' +\r\n addCommas(d.value) +\r\n '</span><br/>' +\r\n '<span class=\"name\">Funds Available: </span><span class=\"value\">$' +\r\n addCommas(d.balance) +\r\n '</span><br/>' +\r\n '<span class=\"name\">Number of Grants: </span><span class=\"value\">' +\r\n d.count +\r\n '</span><br/>' +\r\n '<span class=\"name\">Avg Life: </span><span class=\"value\">' +\r\n d.year +\r\n ' yrs</span><br/>';\r\n\r\n tooltip.showTooltip(content, d3.event);\r\n }", "function updateAnimals(){\n\tfor(let i=0; i<animals.length; i++){\n\t\tanimals[i].drawAnimal();\n\t}\n}", "function display(d) {\n // updateNodeInfo(d.properties.name, color(i));\n console.log(d.properties.name);\n updateNodeInfo(d);\n}", "function dogFunction() {\r\n document.getElementById(\"New_and_This\").innerHTML =\r\n \"Kira has a \" + Kira.Dog_Breed + \" named \" + Kira.Dog_Name;\r\n}", "function renderRandomDogs(data) {\n\n for (let image of data) {\n let imageDiv = document.createElement(\"div\");\n imageDiv.className = \"imageDiv\";\n let img = document.createElement(\"img\");\n img.src = image;\n imageContainer.appendChild(imageDiv);\n imageDiv.appendChild(img);\n }\n}", "function displayPerson(person){\n let personInfo = \"First Name: \" + person.firstName + \"\\n\";\n personInfo = \"Last Name: \" + person.lastName + \"\\n\";\n personInfo += \"Gender: \" + person.gender + \"\\n\";\n personInfo += \"Height: \" + person.height + \"\\n\";\n personInfo += \"Weight: \" + person.weight + \"\\n\";\n personInfo += \"Date of Birth: \" + person.dob + \"\\n\";\n personInfo += \"Occupation: \" + person.occupation + \"\\n\";\n personInfo += \"Eye Color: \" + person.eyeColor + \"\\n\";\n alert(personInfo);\n}", "function showallfilms(films) {\n items.innerHTML = \"\";\n for (var i=0;i<films.length;i++){\n items.innerHTML += defLa[0] + i + defLa[1] + i + defLa[2] + films[i].image + defLa[3] + \" Title: \" +films[i].title + \" <br>Genre: \" + films[i].genre + defLa[4] + films[i].rating + defLa[5];\n }\n}", "function getDemoInfo(id) {\n // read the json file to get data\n d3.json(\"names.json\").then((data)=> {\n // get the metadata info for the demographic panel\n const metadata = data.metadata;\n \n console.log(metadata)\n \n // filter metadata info by id\n const result = metadata.filter(meta => meta.id.toString() === id)[0];\n // select demographic panel to put data\n const demographicInfo = d3.select(\"#name-metadata\");\n \n // empty the demographic info panel each time before getting new id info\n demographicInfo.html(\"\");\n \n // grab the necessary demographic data data for the id and append the info to the panel\n Object.entries(result).forEach((key) => { \n demographicInfo.append(\"h5\").text(key[0].toUpperCase() + \": \" + key[1] + \"\\n\"); \n });\n });\n }", "function displayAnimalInfo(){\n \n // Set our animal variable equal to the text of the button. \n var animal = $(this).attr(\"data-name\");\n console.log(animal);\n\n // Grab our GIPHY API by making an Ajax request\n var queryURL = \"https://api.giphy.com/v1/gifs/search?q=\" + animal +\"&api_key=86gmopU2iKrSWy2FWvm1h5sM3An49fxH&limit=9\"\n\n $.ajax({\n url: queryURL,\n method: \"GET\"\n }).then(function(response) {\n console.log(response);\n \n var results = response.data;\n\n for (i = 0; i < results.length; i++){\n\n // Creating a div to hold the movie\n var gifDiv = $(\"<div class='col-md-4'>\");\n\n // Storing the rating data\n var rating = results[i].rating;\n\n // Creating an element to have the rating displayed\n var ratingParagraph = $(\"<span>\").text(\"Rating: \" + rating);\n var favoriteButton = $(\"<button>\").text(\"♥\")\n $(favoriteButton).addClass(\"favoriteButton\");\n\n // Displaying the rating and fav button\n gifDiv.prepend(favoriteButton);\n gifDiv.prepend(ratingParagraph);\n\n\n // Retrieving the URL for the image\n var gifURL = results[i].images.fixed_height_still.url;\n var stillGIF = results[i].images.fixed_height_still.url;\n var movingGIF = results[i].images.fixed_height.url;\n\n // Creating an element to hold the image, giving it data attributes\n var gif = $(\"<img>\").attr(\"src\", gifURL);\n gif.attr(\"data-still\", stillGIF);\n gif.attr(\"data-animate\", movingGIF);\n gif.attr(\"data-state\", \"still\");\n gif.addClass(\"gif\")\n \n\n // Appending the image\n gifDiv.append(gif);\n //This keeps the image divs from taking up an entire row\n $(gifDiv).css({\"float\":\"left\"});\n $(gifDiv).css({\"margin-top\":\"20px\"});\n\n\n // Putting the entire movie above the previous movies\n $(\"#gif-view\").prepend(gifDiv);\n\n }\n\n // GIF on click still and animate function. \n $(\".gif\").on(\"click\", function() {\n var state = $(this).attr(\"data-state\");\n\n if (state === \"still\"){\n $(this).attr(\"src\", $(this).attr(\"data-animate\"));\n $(this).attr(\"data-state\", \"animate\");\n console.log(state);\n }\n \n else {\n $(this).attr(\"src\", $(this).attr(\"data-still\"));\n $(this).attr(\"data-state\", \"still\");\n console.log(this);\n\n }\n });\n\n // on click function to move the gif to our favorites section. Figured it out using .parent()!\n $(document).on(\"click\", \".favoriteButton\", function(){\n\n var newFav = $(this).parent();\n $(\"#favorites-view\").append($(newFav)); \n $(this).addClass(\"unFavoriteButton\");\n $(this).removeClass(\"favoriteButton\");\n })\n\n //Allows the user to then remove the gif from our favorites. This is not working - it's not even registering the click.\n $(document).on(\"click\", \".unFavoriteButton\" , function() {\n var unFav = $(this).parent();\n console.log(unFav);\n unFav.remove(); \n });\n // $(\".unFavoriteButton\").on(\"click\", function(){\n // var unFav = $(this).parent();\n // console.log(unFav);\n // $(\"#favorites-view\").remove(unFav);\n // })\n \n }); \n }" ]
[ "0.7203563", "0.70514053", "0.67474014", "0.6629687", "0.6607811", "0.6543826", "0.64710593", "0.64496416", "0.6402128", "0.63760084", "0.6364072", "0.6310598", "0.63053083", "0.62978953", "0.628696", "0.6271424", "0.62701595", "0.62427247", "0.62411225", "0.62229145", "0.6215645", "0.6166831", "0.6163317", "0.61611366", "0.6151141", "0.6128831", "0.61092865", "0.60978615", "0.60898876", "0.6068376", "0.6062979", "0.6048273", "0.6044928", "0.603239", "0.60182387", "0.6014245", "0.6010292", "0.59902155", "0.5979136", "0.5969717", "0.5966558", "0.59657675", "0.5965483", "0.5957748", "0.59529793", "0.595076", "0.5949067", "0.59474087", "0.59371334", "0.59320587", "0.5931245", "0.5914565", "0.5914185", "0.59086627", "0.5904739", "0.59028155", "0.5901428", "0.5898969", "0.5886334", "0.5879282", "0.58742", "0.5874037", "0.58739567", "0.5873925", "0.5872191", "0.585585", "0.5851654", "0.58483964", "0.5834608", "0.5832229", "0.58306766", "0.5828137", "0.58255637", "0.58255094", "0.58205503", "0.58161396", "0.5812848", "0.580164", "0.57954305", "0.5795388", "0.5794827", "0.5788272", "0.5787186", "0.5778971", "0.57778007", "0.5772946", "0.57723266", "0.5771902", "0.5771367", "0.5769882", "0.57698613", "0.57651967", "0.5756903", "0.5751949", "0.57435566", "0.57434446", "0.57413304", "0.5734999", "0.57339877", "0.5732293", "0.5729533" ]
0.0
-1
TODO: Add sorting functionality
renderSorting() { return (<div className="search-bar__sort"> <span>Sort by: </span> <i className="search-bar__sort-icon"></i> <i className ="search-bar__arrow-down"></i> </div>); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Sort() {}", "sort() {\n\t}", "sort() {\n\t}", "function sortJson() {\r\n\t \r\n}", "function sortResults(){\n return sort.sortCustomerRecords(result);\n}", "sort(){\n\n }", "Sort() {\n\n }", "sortProducts() {}", "getOrderBy() {}", "sortedListings() {\n return this.state.data.sort((a, b) => {\n return b.id - a.id\n })\n }", "function sortByRating(list) {\n // your code here..\n \n}", "get sortingOrder() {}", "get overrideSorting() {}", "function sortData (data) {\n ...\n}", "sortedItems() {\n return this.childItems.slice().sort((i1, i2) => {\n return i1.index - i2.index;\n });\n }", "sortBy() {\n // YOUR CODE HERE\n }", "sortedTasks(state){\n //criar uma variavel para ordernar nossas tarefas sem alterar o estado original(state)\n let sorted = state.tasks\n return sorted.sort((a,b) => {\n //se o a for menor então ele retorna para corrigir a ordenação\n if(a.name.toLowerCase() < b.name.toLowerCase()) return -1\n //mesma inversa se for o inverso da primeira situação\n if(a.name.toLowerCase() > b.name.toLowerCase()) return 1\n\n return 0\n }) \n }", "sort () {\r\n this._data.sort((a, b) => a.sortOrder !== b.sortOrder ? b.sortOrder - a.sortOrder : a.value.localeCompare(b.value))\r\n }", "static DEFAULT_SORT_BY_FIELD(){ return \"description\"}", "repeaterOnSort() {\n }", "function sortListsByDate() {\r\n\t\treturn getItems().sort(function(a,b){\r\n \t\t\treturn new Date(`${a.date} ${a.time}`) - new Date(`${b.date} ${b.time}`);\r\n\t\t});\r\n\t}", "function sortForDisplay(targetArray) {\n var i;\n var tempArray = [];\n for (i in targetArray) {\n tempArray.push(targetArray[i]);\n tempArray[i].pKey = i;\n }\n tempArray.sort(compare);\n //for (i in tempArray) {\n //console.log(tempArray[i].name);\n //}\n return tempArray;\n}", "sortingFunction() {\n let records = this.get('content');\n if (isArray(records) && records.length > 1) {\n let sorting = this.get('sorting') || [];\n if (sorting.length === 0) {\n sorting = [{ propName: 'id', direction: 'asc' }];\n }\n\n for (let i = 0; i < sorting.length; i++) {\n let sort = sorting[i];\n if (i === 0) {\n records = this.sortRecords(records, sort, 0, records.length - 1);\n } else {\n let index = 0;\n for (let j = 1; j < records.length; j++) {\n for (let sortIndex = 0; sortIndex < i; sortIndex++) {\n if (records.objectAt(j).get(sorting[sortIndex].propName) !== records.objectAt(j - 1).get(sorting[sortIndex].propName)) {\n records = this.sortRecords(records, sort, index, j - 1);\n index = j;\n break;\n }\n }\n }\n\n records = this.sortRecords(records, sort, index, records.length - 1);\n }\n }\n\n this.set('content', records);\n }\n\n let componentName = this.get('componentName');\n this.get('_groupEditEventsService').geSortApplyTrigger(componentName, this.get('sorting'));\n }", "function sortByDate(a, b){\nvar aDate = a.date;\nvar bDate = b.date; \nreturn ((aDate > bDate) ? -1 : ((aDate < bDate) ? 1 : 0));\n}", "sortListItems() {\n let sortedItems = this.props.listItems.slice();\n return sortedItems.sort((a, b) => {\n if (a.value > b.value) {\n return -1;\n } else if (a.value < b.value) {\n return 1;\n }\n return 0;\n });\n }", "function sort(){\n var toSort = S('#sched-list').children;\n toSort = Array.prototype.slice.call(toSort, 0);\n\n toSort.sort(function(a, b) {\n var a_ord = +a.id.split('e')[1]; //id tags of the schedule items are timeINT the INT = the numeric time\n var b_ord = +b.id.split('e')[1]; //splitting at 'e' and getting the element at index 1 gives use the numeric time\n\n return (a_ord > b_ord) ? 1 : -1;\n });\n\n var parent = S('#sched-list');\n parent.innerHTML = \"\";\n\n for(var i = 0, l = toSort.length; i < l; i++) {\n parent.appendChild(toSort[i]);\n }\n }", "function sortingAscend() {\n setSearchData(null)\n let sorted = studentData.sort(function(a, b){\n return b.id - a.id;\n })\n\n setStudentData(sorted)\n console.log(sorted, typeof(sorted))\n }", "render(table) {\n console.log('Applying 3rd partys better sort.');\n }", "function sortNames() {\n /* Runs first function looking for content */\n sortUsingNestedName($('#projectIndexBig'), \"span\", $(\"button.btnSortName\").data(\"sortKey\"));\n /* Checks button classes and add and removes as necessasry */\n if ($(\"#date\").hasClass(\"underline\")) {\n $(\"#date\").removeClass(\"underline\");\n $(\"#name\").addClass(\"underline\");\n } else {\n $(\"#name\").addClass(\"underline\");\n }\n }", "function sortFruitMarketTableByFruitNameAndPrice() {\n\n}", "doSortSection() {\n this.sortedSections = [];\n\n for (let [sectionId, sectionObject] of Object.entries(this.formData.sections)) {\n this.sortedSections.push(sectionObject)\n }\n\n this.sortedSections.sort((a, b) => {\n return a.sortOrder - b.sortOrder;\n })\n }", "getSortedUsers() {\n //clone a new array for users\n let users = [...this.props.users]\n if (this.state.sortDirection === 'asc') {\n users.sort(this.genSortAscendingByField(this.state.sortField))\n } else {\n users.sort(this.genSortDescendingByField(this.state.sortField))\n }\n\n return users\n }", "function sortByMathAsc()\n{\n let tBody = document.getElementById(\"tBody\");\n tBody.innerHTML = \"\"\n sortBySubjectAsc(dataBase, \"maths\")\n // sortBySubjectDsc(dataBase, \"maths\")\n createTable(dataBase)\n}", "function sortRows(){\n sortRowsAlphabeticallyUpwards();\n}", "function sortNames() {\n /* Runs first function looking for content */\n sortUsingNestedName($('#projectIndex'), \"div\", $(\"button.btnSortName\").data(\"sortKey\"));\n /* Checks button classes and add and removes as necessasry */\n if ($(\"#date\").hasClass(\"underline\")) {\n $(\"#date\").removeClass(\"underline\");\n $(\"#name\").addClass(\"underline\");\n } else {\n $(\"#name\").addClass(\"underline\");\n }\n }", "sortAscending(index) {\n const temp = [...this.state.displayData];\n \n temp.sort((a, b) => {\n if(a.name < b.name) { return -1; }\n if(a.name > b.name) { return 1; }\n return 0;\n });\n \n return temp;\n }", "sortData() {\n this.data.sort(($val1, $val2 ) => {\n const a = JSON.stringify($val1[this.sortBy]);\n const b = JSON.stringify($val2[this.sortBy]);\n if ( a < b ){\n return -this.sortDir;\n }\n if ( a > b ){\n return this.sortDir;\n }\n return 0;\n });\n }", "function sort_li(a, b) {\n console.log('in');\n an = Date.parse($(a).find('.col1').text());\n bn = Date.parse($(b).find('.col1').text());\n\n return bn < an ? 1 : -1;\n }", "async function TopologicalSort(){}", "function sortingDscend() { \n setSearchData(null)\n let sorted = studentData.sort(function(a, b){\n return a.id - b.id;\n })\n\n setSearchData(sorted)\n // console.log(sorted, typeof(sorted))\n }", "sortGraphics(a, b) {\n if (a.z === b.z) {\n return a.id - b.id;\n }\n return a.z - b.z;\n }", "function sortBy(elem){\n\n var sort = elem.innerHTML.replace(/<.+?>/g,\"\")\n var sortDirection = elem.children[0].className\n \n if(sort == \"name\"){\n \n if(sortDirection.match(\"sortAscending\")){\n elem.children[0].className = elem.children[0].className.replace(\"glyphicon-arrow-down\", \"glyphicon-arrow-up\")\n elem.children[0].className = elem.children[0].className.replace(\"sortAscending\", \"sortDescending\")\n tableRef.fnSort([2, \"desc\"]) //sort by last name\n }else {\n elem.children[0].className = elem.children[0].className.replace(\"glyphicon-arrow-up\", \"glyphicon-arrow-down\")\n elem.children[0].className = elem.children[0].className.replace(\"sortDescending\", \"sortAscending\")\n tableRef.fnSort([2, \"asc\"]) //sort by last name\n }\n \n var $ProfileList = $(\"div.ProfileContainer\")\n \n var rows = tableRef._('tr', {\"filter\":\"applied\"}); \n var IndexArray = rows.map(function(value,index) { return value[0]; });\n \n var SortedProfiles = $ProfileList.sort(function (a, b) {\n var test1 = IndexArray.indexOf(a.id.match(/\\d+/)[0])\n var test2 = IndexArray.indexOf(b.id.match(/\\d+/)[0])\n\n return test1 < test2 ? -1 : test1 > test2 ? 1 : 0;\n });\n \n $(\"#ProfileResults\").html(SortedProfiles)\n\n }\n updateActiveContent()\n }", "function sortByCreationDate() {\n let nodes = document.querySelectorAll('.bookCard')\n nodes.forEach((node) => {\n node.style.order = 'initial'\n })\n}", "function sortName() {\n if (localStorage.AddressBookRecord) {\n addresBookArray = JSON.parse(localStorage.AddressBookRecord);\n\n for (var i = 0; i < addresBookArray.length; i++) {\n\n for (var j = i + 1; j < addresBookArray.length; j++) {\n var previous = addresBookArray[i].firstName;\n var next = addresBookArray[j].firstName;\n console.log(previous + \" \" + next);\n if (previous > next) {\n temp = addresBookArray[i];\n addresBookArray[i] = addresBookArray[j];\n addresBookArray[j] = temp;\n }\n }\n }\n\n\n\n }\n localStorage.AddressBookRecord = JSON.stringify(addresBookArray);\n init();\n\n displayRecord();\n\n}", "function reorderResults(){\n ids=[];\n $('.resultholder .starblock').each(function(){\n ids.push($(this).prop('id'));\n });\n ids.sort();\n $rh = $('.resultholder');\n ids.forEach(function(id){\n $('#'+id).appendTo($rh);\n });\n }", "function sortList(a,b) {\n if (a.total < b.total)\n return -1;\n if (a.total > b.total)\n return 1;\n return 0;\n }", "function sortList(a,b) {\n if (a.total < b.total)\n return -1;\n if (a.total > b.total)\n return 1;\n return 0;\n }", "nameSort() {\n orders.sort( \n function(a,b) {\n return (a[0] < b[0]) ? -1 : (a[0] > b[0]) ? 1 : 0; \n }\n ); \n }", "renderSortedListings() {\n const { sortedListings } = this.props;\n const listingsArr = [];\n each(sortedListings, (listing) => {\n listingsArr.push(<Listing {...listing} />);\n });\n return listingsArr;\n }", "function doSortObjHighestToLowest() {\n const mappedNames = people.results\n .map((person) => {\n return {\n name: person.name.first,\n };\n })\n .filter((person) => person.name.startsWith('A')) //filtrando todos que começa com A\n .sort((a, b) => {\n return a.name.length - b.name.length;\n }); //ordenando\n console.log('lista de obj ordenados do menor para o maior', mappedNames);\n}", "get orderList() {\n let orderList = this.env.pos.db.getQrCodeOrders()\n orderList = orderList.sort(this.env.pos.sort_by('created_time', true, function (a) {\n if (!a) {\n a = 'N/A';\n }\n return a.toUpperCase()\n }));\n return orderList\n }", "sortData(data) {\n return data.sort((a, b) => {\n let aa = typeof a.date === \"string\" ? Date.parse(a.date) : a.date,\n bb = typeof b.date === \"string\" ? Date.parse(b.date) : b.date;\n return this.latest ? bb - aa : aa - bb;\n });\n }", "sortByTag(){\n this.list.sort(function(a,b){\n return a.tag.localeCompare(b.tag);\n });\n $(\"#theTasks\").empty();\n this.list.forEach(function(item){\n item.addToDom();\n });\n }", "function sorte ( i ){\n return function(){\n if(scope.sorting.obj){\n //var index = _.findIndex(scope.viewer, scope.sorting.obj);\n }\n var key = scope.headers[i].field;\n if(scope.sorting.field === key){\n scope.sorting.direction = scope.sorting.direction * -1;\n }else{\n scope.sorting.field = key;\n scope.sorting.direction = 1;\n }\n sorter(key,scope.sorting.direction);\n scope.sorting.obj = scope.headers[i];\n scope.buildTable();\n\n };\n }", "function sorte ( i ){\n return function(){\n if(scope.sorting.obj){\n //var index = _.findIndex(scope.viewer, scope.sorting.obj);\n }\n var key = scope.headers[i].field;\n if(scope.sorting.field === key){\n scope.sorting.direction = scope.sorting.direction * -1;\n }else{\n scope.sorting.field = key;\n scope.sorting.direction = 1;\n }\n sorter(key,scope.sorting.direction);\n scope.sorting.obj = scope.headers[i];\n scope.buildTable();\n\n };\n }", "function testSorts()\n{\n\n\tconsole.log(\"============= original googleResults =============\");\n\tconsole.log(googleResults);\n\t\n\tconsole.log(\"==== before sort array element index name rating ====\");\n\t\n\tgoogleResults.forEach(function(element,index)\n\t{\n\t\t console.log(index + \": name: \" + element.name + \" rating: \" + element.rating);\n\n\t});\n\n\t\t// commented for testing\n\t\t//googleResults.sortByRatingAscending();\n\t\t\n\t\t// commented for testing\n\t\tgoogleResults.sortByRatingDescending();\n\t\t\n\t//===============================================================\t\n\n\tconsole.log(\"============= after sort =============\");\n\n\tgoogleResults.forEach(function(element,index)\n\t{\n\t\t console.log(index + \": name: \" + element.name + \" rating: \" + element.rating);\n\n\t});\n\t\n}//END test", "sort() {\n if(this.data.length >= 2){\n for (var i = 0; i < this.data.length - 1; i++){\n for (var j = i + 1; j < this.data.length; j++){\n if (this.data[i].users.length < this.data[j].users.length){\n let tmp = this.data[i];\n this.data[i] = this.data[j];\n this.data[j] = tmp;\n \n }\n }\n \n }\n }\n }", "function sortDate()\n{\n\tevents.sort( function(a,b) { if (a.startDate < b.startDate) return -1; else return 1; } );\n\tclearTable();\n\tfillEventsTable();\n}", "getTitles() {\n let titles = this.state.projects.map(proj => proj.title); \n titles.sort();\n titles.unshift('');\n this.setState({titles: titles}); \n }", "function sort_li(a, b) {\n an = Date.parse($(a).find('.col2').text());\n bn = Date.parse($(b).find('.col2').text());\n\n return bn < an ? 1 : -1;\n }", "function orderAlphabetically(array) {\nlet title = array.map( (elem) => {\n return array.titles < 20\n})\n\nlet orderedTitle = title.sort(first, second) => {\n if (first.title > second.title) {\n return 1\n }\n else if (first.title < second.title) {\n return 0\n }\n else {\n return 0\n }\n}\n\n return orderedTitle\n}", "function sortAssets2() {\r\n\t//}\r\n\tchangeList();\r\n\t}", "function sortData(searches){\r\n var sorters = document.getElementsByName(\"sorter\");\r\n var sorted = 0;\r\n for(var x=0; x<4;x++){\r\n if(sorters[x].checked){\r\n sorted=x; break;\r\n }\r\n }\r\n /*\r\n sorted : \r\n 0 -> id\r\n 1 -> Name\r\n 2 -> Height\r\n 3 -> Weight\r\n */\r\n searches.sort(function (a,b){\r\n switch(sorted){\r\n case 0:\r\n return a.id - b.id;\r\n\r\n case 1:\r\n return a.name.localeCompare(b.name);\r\n \r\n case 2:\r\n return a.height-b.height;\r\n\r\n case 3:\r\n return a.weight - b.weight;\r\n }\r\n });\r\n return searches;\r\n}", "function alphabetique(){\n entrepreneurs.sort.year\n }", "sort(key) {\n //used JavaScript sort method\n const sortedContacts = this.state.contacts.sort((contactA, contactB) => {\n return contactA[key] >= contactB[key] ? 1 : -1;\n });\n this.setState({ contacts: sortedContacts, reset: true })\n }", "sortRankStats(ranks){\n const sortedRanks = ranks.sort(this.pointsCompare);\n return sortedRanks;\n }", "function sortDates(){\n\n\n function swap(x,y){\n let tx=dates[x];\n dates[x]=dates[y];\n dates[y]=tx;\n }\n\n for (let i=0;i<dates.length;i++){\n let m1=parseInt(dates[i].date.slice(0,dates[i].date.indexOf('.')));\n let d1=parseInt(dates[i].date.slice(dates[i].date.indexOf('.')+1,dates[i].date.indexOf('.',dates[i].date.indexOf('.')+1)));\n for (let j=i;j<dates.length;j++){\n let m2=parseInt(dates[j].date.slice(0,dates[j].date.indexOf('.')));\n let d2=parseInt(dates[j].date.slice(dates[j].date.indexOf('.')+1,dates[j].date.indexOf('.',dates[j].date.indexOf('.')+1)));\n if ((m2<m1)||m1==m2&&d2<d1){\n swap(i,j);\n m1=parseInt(dates[i].date.slice(0,dates[i].date.indexOf('.')));\n d1=parseInt(dates[i].date.slice(dates[i].date.indexOf('.')+1,dates[i].date.indexOf('.',dates[i].date.indexOf('.')+1)));\n }\n }\n }\n injectData();\n\n }", "function sortByTitle() {\n let nodes = document.querySelectorAll('.bookCard')\n let titles = []\n nodes.forEach(node => titles.push(library[node.dataset.index].title))\n console.log(titles)\n titles.sort()\n console.log(titles)\n\n let order\n nodes.forEach((node) => {\n console.log(node)\n order = titles.findIndex(x => x === library[node.dataset.index].title)\n node.style.order = order\n }) \n}", "function sortByAuthor() {\n let nodes = document.querySelectorAll('.bookCard')\n let authors = []\n nodes.forEach(node => authors.push(library[node.dataset.index].author))\n authors.sort()\n\n let order\n nodes.forEach((node) => {\n console.log(node)\n order = authors.findIndex(x => x === library[node.dataset.index].author)\n node.style.order = order\n })\n}", "sortByDueDate(){\n this.list.sort(function(a,b){\n return a.duedate - b.duedate;\n });\n $(\"#theTasks\").empty();\n this.list.forEach(function(item){\n item.addToDom();\n });\n }", "function sortEntriesMRU(entries){\n\t// Comparison function for sort\n\tvar date_sort_desc = function (entry1, entry2) {\n\t\tvar date1 = Date.parse(entry1.dateAccessed);\n\t\tvar date2 = Date.parse(entry2.dateAccessed);\n\t\tif (date1 > date2) return -1;\n\t\tif (date1 < date2) return 1;\n\t\treturn 0;\n\t};\n console.log(\"sort mru\");\n\tentries.sort(date_sort_desc);\n}", "sortInitialResults() {\r\n var output = [];\r\n if (this.state.sortBy === \"Sort by Company Name\") {\r\n output = this.sortDataByName(this.state.output); \r\n }\r\n else if (this.state.sortBy === \"Sort by Views\") {\r\n output = this.sortDatabyViews(this.state.output);\r\n }\r\n else if (this.state.sortBy === \"Sort by Rating\") {\r\n output = this.sortDataByRating(this.state.output);\r\n }\r\n this.setState({output: output});\r\n }", "function sortPlaylist() {\n playlistArr = Object.entries(livePlaylist);\n\n if (playlistArr.length > 2) {\n var sorted = false;\n while (!sorted) {\n sorted = true;\n for (var i = 1; i < playlistArr.length - 1; i++) {\n if ((playlistArr[i][1].upvote < playlistArr[i + 1][1].upvote)) {\n sorted = false;\n var temp = playlistArr[i];\n playlistArr[i] = playlistArr[i + 1];\n playlistArr[i + 1] = temp;\n // })\n }\n // playlistArr[i][1].index = i;\n }\n }\n }\n return playlistArr;\n}", "sortedCategories() {\n return this.state.categories.sort((a, b) => {\n if (a.name === b.name) return 0\n return a.name < b.name ? -1 : 1\n })\n }", "function ascendingOrder(){\n let moviesCopy = movies\n moviesCopy.sort((a, b) => (a.duration>b.duration) ? 1 : -1)\n for (let i =0; i<moviesCopy.length;i+=1){\n console.log(moviesCopy[i].title, moviesCopy[i].duration )\n }\n}", "getSortedData(data) {\n if (!this.sort.active || this.sort.direction === '') {\n return data;\n }\n return data.sort((a, b) => {\n const isAsc = this.sort.direction === 'asc';\n switch (this.sort.active) {\n case 'name': return compare(a.name, b.name, isAsc);\n case 'id': return compare(+a.id, +b.id, isAsc);\n default: return 0;\n }\n });\n }", "getSortedData(data) {\n if (!this.sort.active || this.sort.direction === '') {\n return data;\n }\n return data.sort((a, b) => {\n const isAsc = this.sort.direction === 'asc';\n switch (this.sort.active) {\n case 'name': return compare(a.name, b.name, isAsc);\n case 'id': return compare(+a.id, +b.id, isAsc);\n default: return 0;\n }\n });\n }", "function sortByRichestAsc() {\n data.sort((a, b) => a.money - b.money);\n updateDOM();\n}", "function sortByDate() {\n return articles.sort(function(a, b) {\n let x = new Date(a.published_at).getTime();\n let y = new Date(b.published_at).getTime();\n if (x < y){\n return -1; \n } else if (y > x){\n return 1;\n } else {\n return 0\n }\n });\n}", "serialize() {\n //creates array with spread syntax, then sorts\n //not cross-compatible with some older versions of browsers like IE11\n const sorted = [...this.data];\n sorted.sort((a , b) => {\n return a.comparator - b.comparator;\n });\n return JSON.stringify(sorted);\n }", "serialize() {\n //creates array with spread syntax, then sorts\n //not cross-compatible with some older versions of browsers like IE11\n const sorted = [...this.data];\n sorted.sort((a , b) => {\n return a.comparator - b.comparator;\n });\n return JSON.stringify(sorted);\n }", "function sortBooks() {\n let sorted = extractBookElements();\n switch (getInputSortBy()) {\n case \"date\":\n sorted.sort( (a,b) => {\n return a.id < b.id ? -1 : 1;\n });\n break;\n case \"title\":\n sorted.sort( (a,b) => {\n return a.querySelector(\".title\").textContent < b.querySelector(\".title\").textContent ? -1 : 1;\n });\n break;\n case \"author\":\n sorted.sort( (a,b) => {\n return a.querySelector(\".author\").textContent.split(\" \").pop() < b.querySelector(\".author\").textContent.split(\" \").pop() ? -1 : 1;\n });\n break;\n case \"unread\":\n sorted.sort( (a,b) => {\n const unread = \"Not read\";\n const read = \"Already read\";\n if ( a.querySelector(\".status\").textContent === unread && b.querySelector(\".status\").textContent === read) {\n return -1;\n }\n if ( a.querySelector(\".status\").textContent === read && b.querySelector(\".status\").textContent === unread) {\n return 1;\n }\n return 0;\n });\n break;\n }\n attachBookElements(sorted);\n}", "function sortData(data)\n\t{\n\t\tfor (let i = 0; i < data.length; i++)\n \t{\n\t \tfor (let j = 0; j < data.length - i - 1; j++)\n\t \t{\n\t \t\tif (+data[j].subCount < +data[j + 1].subCount)\n\t \t\t{\n\t \t\t\tlet tmp = data[j];\n\t \t\t\tdata[j] = data[j + 1];\n\t \t\t\tdata[j + 1] = tmp;\n\t \t\t}\n\t \t}\n \t}\n \treturn data;\n\t}", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "function resort(){\n if(scope.sorting && scope.sorting.obj){\n var sortKey = scope.sorting.obj.field;\n sorter(sortKey,scope.sorting.direction);\n }\n }", "sortedRankings ({ rankings, sortBy }) {\n const { field, order } = sortBy\n const sortComparator = (a, b) => {\n if (order === 'asc') {\n return a.stats[field] - b.stats[field]\n }\n return b.stats[field] - a.stats[field]\n }\n return rankings.sort(sortComparator)\n }", "sortPosts() {\n const orderBy = this.state.postsOrder;\n this.props.posts.sort((post1, post2) => {\n switch (orderBy) {\n case 'timestamp' : return post1.timestamp - post2.timestamp;\n case 'voteScore' : return post2.voteScore - post1.voteScore;\n case 'category' : return post1.category.localeCompare(post2.category);\n default : return post2.voteScore - post1.voteScore;\n }\n });\n }", "inputSorted() {\n const text = document.querySelector('#sort').value\n document.querySelector(\"#dream-list\").innerHTML = \"\"\n if(text === \"all\" ) {\n const allDreams = Dream.all\n allDreams.forEach(dream => dream.addToDom())\n }\n else{\n const filtered = Dream.all.filter(dream => dream.achieved.includes(text))\n // debugger;\n filtered.forEach(dream => dream.addToDom())\n // this.sortRender(filtered)\n }\n }", "function orderAlphabetically (movies){\n\n const array = [...movies].map(function(movie){\n\n return movie.title;\n}) \n var finalArray = array.sort();\n var top = finalArray.slice(0,20) \n\n return top;\n}", "function sortOrder(a,b) {\n return b.size - a.size;\n }", "_sortBy(array, selectors) {\n return array.concat().sort((a, b) => {\n for (let selector of selectors) {\n let reverse = selector.order ? -1 : 1;\n\n a = selector.value ? JP.query(a, selector.value)[0] : JP.query(a,selector)[0];\n b = selector.value ? JP.query(b, selector.value)[0] : JP.query(b,selector)[0];\n\n if (a.toUpperCase() > b.toUpperCase()) {\n return reverse;\n }\n if (a.toUpperCase() < b.toUpperCase()) {\n return -1 * reverse;\n }\n }\n return 0;\n });\n }", "function sortRenderOrder() {\n \n var sortBy = function(field, reverse, primer){\n var key = primer ? function(x) {return primer(x[field])} : function(x) {return x[field]};\n reverse = [-1, 1][+!!reverse];\n return function (a, b) {\n\treturn a = key(a), b = key(b), reverse * ((a > b) - (b > a));\n } \n }\n \n gadgetRenderOrder.sort(sortBy(\"tabPos\", true, parseInt));\n gadgetRenderOrder.sort(sortBy(\"paneId\", true, parseInt));\n gadgetRenderOrder.sort(sortBy(\"parentColumnId\", true, parseInt));\n }", "sortByLastName(addressData)\n {\n let i,j,temp\n for(i=0;i<addressData.length;i++)\n {\n for(j=0;j<addressData.length-1;j++)\n {\n if(addressData[j+1].lastname < addressData[j].lastname)\n {\n temp=addressData[j+1]\n addressData[j+1]=addressData[j]\n addressData[j]=temp\n }\n }\n }\n for(i=0;i<addressData.length;i++)\n {\n console.log(addressData[i])\n }\n }", "sortAlbumsYear() {\n this.albumsList.sort((album1, album2)=>{\n if(album1.year < album2.year){\n return -1\n } else if (album1.year > album2.year) {\n return 1\n } else {\n return 0\n }\n })\n }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "get sort() { return this._sort; }", "static async getAllSeries(){\n const results = await axios.get('./sample.json')\n const all = results.data.entries;\n const series = all.filter(show=>(show.programType === \"series\"))\n const ordered = series.sort((a,b) => a.title > b.title ? 1 : -1);\n return ordered;\n }", "sortResults(event, index, value) {\r\n var output = [];\r\n this.setState({sortBy: value});\r\n if (value === \"Sort by Company Name\") {\r\n output = this.sortDataByName(this.state.output); \r\n }\r\n else if (value === \"Sort by Views\") {\r\n output = this.sortDatabyViews(this.state.output);\r\n }\r\n else if (value === \"Sort by Rating\") {\r\n output = this.sortDataByRating(this.state.output);\r\n }\r\n this.setState({output: output});\r\n }", "_sort (a, b) {\n return this.members.sort((a, b) => a.cost - b.cost);\n }", "function sortOrder(a, b) {\n\t return b.size - a.size;\n\t }" ]
[ "0.6634282", "0.66133404", "0.66133404", "0.6498647", "0.64679635", "0.64645666", "0.6387402", "0.63607615", "0.63265496", "0.6305758", "0.6275738", "0.6266211", "0.6252127", "0.622554", "0.620018", "0.6185742", "0.61510754", "0.6140837", "0.6131251", "0.6130222", "0.61281455", "0.6118069", "0.611039", "0.6069673", "0.6069671", "0.6045526", "0.60336137", "0.6003918", "0.5981601", "0.5979053", "0.5960085", "0.5959402", "0.5942386", "0.5937449", "0.5936955", "0.5896808", "0.5895503", "0.5895193", "0.58892816", "0.5886308", "0.58835727", "0.588031", "0.58645177", "0.586253", "0.586202", "0.58606726", "0.58606726", "0.5852407", "0.58471495", "0.5845387", "0.5844435", "0.58301723", "0.58151233", "0.58114135", "0.58114135", "0.57999974", "0.5796148", "0.57955486", "0.57952017", "0.5793732", "0.57926875", "0.579151", "0.57895154", "0.57892525", "0.57834285", "0.5772303", "0.577104", "0.5769597", "0.57694495", "0.5765722", "0.5760394", "0.57546276", "0.5752363", "0.57518315", "0.57493234", "0.5749309", "0.5749309", "0.5746657", "0.5741346", "0.57373714", "0.57373714", "0.5736246", "0.5734914", "0.57346845", "0.57346845", "0.57327145", "0.5732001", "0.5731473", "0.57305753", "0.57270885", "0.572685", "0.5726783", "0.5724797", "0.5719759", "0.5707963", "0.5707963", "0.5707963", "0.5703616", "0.5701714", "0.57015955", "0.5699912" ]
0.0
-1
Usa WebSocket per inviare il messaggio al server
function onSendMessage(){ var msg = document.getElementById("usermsg").value; if(msg == "") alert("assicurati di inserire il testo da inviare"); else { if(sex == "lui") msg = "newMsg " + name + ": <div style='background-color:lightblue;display:inline-block;box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);border-radius: 5px'>" + document.getElementById("usermsg").value + "</div>"; else msg = "newMsg " + name + ": <div style='background-color:pink;display:inline-block;box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);border-radius: 5px'>" + document.getElementById("usermsg").value + "</div>"; //alert(msg); connection.send(msg); document.getElementById("usermsg").value=""; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function sendMessage() {\r\n let content = document.getElementById(\"msg\").value;//recupere le message de l'input\r\n document.getElementById(\"msg\").value = \"\";//on vide l'élément\r\n websocket.send(\"[\"+login+\"] \"+content);//on envoie le msg au serveur + login de la personne\r\n}", "function broadcast(msg) {\n\twss.clients.forEach((client) => {\n\t\tif (client.readyState === WebSocket.OPEN) {\n\t\t\tclient.send(typeof msg === 'object' ? JSON.stringify(msg) : msg);\n\t\t}\n\t});\n}", "function messaggio_da_inviare(msg) {\n var msgjson = JSON.stringify(msg);\n ws.send(\"m:\"+ stanza + \":\" + chiamante + \":\" + msgjson);\n}", "function broadcast(message){\n // ここでチャンネルの全てのユーザ宛てにメッセージを送信している\n console.log(wss.clients);\n wss.clients.forEach(function(client){\n client.send(JSON.stringify({\n message: message\n }))\n })\n}", "function onSendClick() {\n if (webSocket.readyState !== WebSocket.OPEN) {\n console.error(\"webSocket is not open: \" + webSocket.readyState);\n webSocket.close();\n return;\n }\n var msg = document.getElementById(\"message\").value;\n webSocket.send(msg);\n}", "function broadcast(msg) {\n wss.clients.forEach(function each(client) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(JSON.stringify(msg));\n }\n });\n}", "function socket_send(msg) {\n if (websocket.readyState == 1) {\n websocket.send(msg);\n }\n}", "sendMessage(text) {\n const msg = {\n type: \"newMessage\",\n chatId: this.chatId(),\n user: this.state.user,\n text: text\n };\n this.ws.send(JSON.stringify(msg));\n }", "envoyerMessage(socket,channel){\n var localThis=this;\n var doc = document.getElementById(\"msgBox\");\n document.getElementById(\"envoyer\").onclick = function(){\n if(doc.value){\n var msg = new Message(\"onMessage\", localThis.currentChannel.id , doc.value , null, null);\n socket.send(JSON.stringify(msg));\n $(\"#msgBox\").val('');\n }\n else{\n alert(\"Saisir un message!\");\n }\n }\t\n }", "function wssBroadcastEx (data, ws){\n wss.clients.forEach(function each(client) {\n if (client !== ws && client.readyState === WebSocket.OPEN) {\n client.send(data);\n }\n });\n}", "handleWS(message){\n this.props.wsSend(message);\n }", "sendMessage(msg){\n this.socket.emit(\"client\", msg);\n }", "_broadcastMessage(message){\n //Publish messages to peer\n this._wire.extended('ut_live_chat', {...message,\n middleman : true\n })\n }", "function sendToServer(msg) {\n ws.send(msg);\n }", "function envoiMessage(mess) {\r\n // On recupere le message\r\n var message = document.getElementById('message').value;\r\n\r\n // On appelle l'evenement se trouvant sur le serveur pour qu'il enregistre le message et qu'il l'envoie a tous les autres clients connectes (sauf nous)\r\n socket.emit('nouveauMessage', { 'pseudo' : pseudo, 'message' : message });\r\n\r\n // On affiche directement notre message dans notre page\r\n document.getElementById('tchat').innerHTML += '<div class=\"line\"><b>'+pseudo+'</b> : '+message+'</div>';\r\n\r\n // On vide le formulaire\r\n document.getElementById('message').value = '';\r\n\r\n // On retourne false pour pas que le formulaire n'actualise pas la page\r\n return false;\r\n}", "function wsSend(msg) {\n ws.send(JSON.stringify(msg));\n}", "sendMessage(sender, msg) {\n const message = {\n sender: sender,\n content: msg\n };\n this._serverSideClient.publish(`/chat`, JSON.stringify(message));\n }", "function broadcastMessage(message) {\n for (let client of wss.clients) {\n if(client.readyState === ws.OPEN) {\n client.send(message);\n }\n }\n}", "function send(msg) { // send: msg\n if (socket.readyState === READY_STATE_OPEN) { socket.send(msg); }\n\n console.log('chatService(wsBaseUrl).send('+msg+')');\n }", "function sendMessage(event) {\n event.preventDefault();\n event.stopPropagation();\n\n ws.send(currX+\";\"+currY+\";\"+prevX+\";\"+prevY+\";\"+ishere);\n // if (sendInput.value !== '') {\n //Send data through the WebSocket\n//ws.send(sendInput.value);\n // sendInput.value = '';\n //}\n}", "function send(msg) {\n ws.send( msg );\n }", "broadcast(event, payload = {}) {\n this.server.clients.forEach(client => {\n // Check if the client is still active\n if (client.readyState === ws.OPEN) {\n client.send(\n JSON.stringify({\n event,\n payload\n })\n );\n }\n });\n }", "async function sendMessage(event) {\n var input = document.getElementById(\"messageText\");\n //#ws.send(JSON.stringify(mess))\n let mess = {\n type: \"text\",\n from: `${user}`,\n message: input.value,\n time: Date.now(),\n broadcast: false,\n course_name: eBookConfig.course,\n div_id: currentQuestion,\n };\n await publishMessage(mess);\n var messages = document.getElementById(\"messages\");\n var message = document.createElement(\"li\");\n message.classList.add(\"outgoing-mess\");\n var content = document.createTextNode(`${user}: ${input.value}`);\n message.appendChild(content);\n messages.appendChild(message);\n input.value = \"\";\n // not needed for onclick event.preventDefault()\n}", "createChat () {\n let messageDiv = elementCreate.create('div', { id: 'messages' })\n this.chatDiv.appendChild(messageDiv)\n\n this.chatSocket = new window.WebSocket('ws://vhost3.lnu.se:20080/socket/', 'chatchannel')\n\n let chatData = {\n 'type': 'message',\n 'data': '',\n 'username': this.nameStorage.getItem('userName'),\n 'channel': 'myOwnChannel',\n 'key': 'eDBE76deU7L0H9mEBgxUKVR0VCnq0XBd'\n }\n\n this.chatSocket.addEventListener('message', event => {\n let answer = JSON.parse(event.data)\n\n if (answer.type !== 'heartbeat') {\n let user = elementCreate.create('h3', { id: 'user' })\n user.innerText = answer.username\n this.chatDiv.querySelector('#messages').appendChild(user)\n\n let userMessage = document.createElement('p')\n userMessage.innerText = answer.data\n this.chatDiv.querySelector('#messages').appendChild(userMessage)\n }\n messageDiv.scrollTop = messageDiv.scrollHeight\n })\n\n let messageBox = elementCreate.create('textarea',\n { name: 'textbox', id: 'messagebox', cols: 30, rows: 5 })\n this.chatDiv.appendChild(messageBox)\n\n let textBox = this.chatDiv.querySelector('#messagebox')\n let chatSocket = this.chatSocket\n textBox.addEventListener('keydown', event =>\n sendMessage(event, chatSocket, textBox, chatData))\n\n /**\n * Sends messages to server via the web socket.\n *\n * @param {event} event\n * @param {WebSocket} chatSocket\n * @param {element} textBox\n * @param {object} chatData\n */\n function sendMessage (event, chatSocket, textBox, chatData) {\n if (event.key === 'Enter') {\n event.preventDefault()\n\n if (textBox.value !== '') {\n chatData.data = textBox.value\n chatSocket.send(JSON.stringify(chatData))\n textBox.value = ''\n }\n }\n }\n }", "function webSocketSend(msg) {\n var reqPayload = {\n \"clientMessageId\":1519890390169,\n \"message\":{\"body\":msg},\n \"resourceid\":\"/bot.message\",\n \"botInfo\":{\"chatBot\": botName,\"taskBotId\": streamId,\n \"client\":\"sdk\",\"meta\":{\"timezone\":\"Asia/Kolkata\",\"locale\":\"en-US\"},\n \"id\":1519890390169}};\n console.log(\"Request Payload: \"+JSON.stringify(reqPayload));\n return Promise.resolve(ws.send(JSON.stringify(reqPayload)));\n}", "constructor() {\n // call the socket init with the url of my test environment aka local host (WS server)\n socket.init('ws://localhost:3001'); \n //sending and echoing a message\n socket.registerOpenHandler(() => {\n let message = new ChatMessage({ message: 'pow!' });\n socket.sendMessage(message.serialize());\n });\n socket.registerMessageHandler((data) => {\n console.log(data);\n });\n }", "sendNewMessage(){\n\n if(this.state.messageInput.length > 0){\n\n const newMessage = {\n type: \"postMessage\",\n content: this.state.messageInput,\n username: this.state.currentUser.name\n };\n\n this.setState({messageInput: \"\"});\n\n this.sendWebSocket(newMessage);\n }\n }", "function MinimaWebSocketListener(){\n\tMinima.log(\"Starting WebSocket Listener @ \"+Minima.wshost);\n\t\n\t//Check connected\n\tif(MINIMA_WEBSOCKET !== null){\n\t\tMINIMA_WEBSOCKET.close();\n\t}\n\t\n\t//Open up a websocket to the main MINIMA proxy..\n\tMINIMA_WEBSOCKET = new WebSocket(Minima.wshost);\n\t\n\tMINIMA_WEBSOCKET.onopen = function() {\n\t\t//Connected\n\t\tMinima.log(\"Minima WS Listener Connection opened..\");\t\n\t\t\n\t\t//Now set the MiniDAPPID\n\t\tuid = { \"type\":\"uid\", \"uid\": window.location.href };\n\t\t\n\t\t//Send your name.. set automagically but can be hard set when debugging\n\t\tMINIMA_WEBSOCKET.send(JSON.stringify(uid));\n\t\t\t\n\t //Send a message\n\t MinimaPostMessage(\"connected\", \"success\");\n\t};\n\t\n\tMINIMA_WEBSOCKET.onmessage = function (evt) { \n\t\t//Convert to JSON\t\n\t\tvar jmsg = JSON.parse(evt.data);\n\t\t\n\t\tif(jmsg.event == \"newblock\"){\n\t\t\t//Set the new status\n\t\t\tMinima.block = parseInt(jmsg.txpow.header.block,10);\n\t\t\tMinima.txpow = jmsg.txpow;\n\t\t\t\n\t\t\t//What is the info message\n\t\t\tvar info = { \"txpow\" : jmsg.txpow };\n\t\t\t\n\t\t\t//Post it\n\t\t\tMinimaPostMessage(\"newblock\", info);\n\t\t\t\n\t\t}else if(jmsg.event == \"newtransaction\"){\n\t\t\t//What is the info message\n\t\t\tvar info = { \"txpow\" : jmsg.txpow, \"relevant\" : jmsg.relevant };\n\t\t\t\n\t\t\t//New Transaction\n\t\t\tMinimaPostMessage(\"newtransaction\", info);\n\t\t\n\t\t}else if(jmsg.event == \"newtxpow\"){\n\t\t\t//What is the info message\n\t\t\tvar info = { \"txpow\" : jmsg.txpow };\n\t\t\t\n\t\t\t//New TxPoW\n\t\t\tMinimaPostMessage(\"newtxpow\", info);\n\t\t\t\n\t\t}else if(jmsg.event == \"newbalance\"){\n\t\t\t//Set the New Balance\n\t\t\tMinima.balance = jmsg.balance;\n\t\t\t\n\t\t\t//What is the info message\n\t\t\tvar info = { \"balance\" : jmsg.balance };\n\t\t\t\n\t\t\t//Post it..\n\t\t\tMinimaPostMessage(\"newbalance\", info);\n\t\t\n\t\t}else if(jmsg.event == \"network\"){\n\t\t\t//What type of message is it..\n\t\t\tif( jmsg.details.action == \"server_start\" || \n\t\t\t\tjmsg.details.action == \"server_stop\" || \n\t\t\t\tjmsg.details.action == \"server_error\"){\n\t\t\t\t\t\n\t\t\t\tsendCallback(MINIMA_SERVER_LISTEN, jmsg.details.port, jmsg.details);\n\t\t\t\t\n\t\t\t}else if( jmsg.details.action == \"client_new\" || \n\t\t\t\t\t jmsg.details.action == \"client_shut\" || \n\t\t\t\t\t jmsg.details.action == \"message\"){\n\t\t\t\t\t\t\n\t\t\t\tif(!jmsg.details.outbound){\n\t\t\t\t\tsendCallback(MINIMA_SERVER_LISTEN, jmsg.details.port, jmsg.details);\n\t\t\t\t}else{\n\t\t\t\t\tsendCallback(MINIMA_USER_LISTEN, jmsg.details.hostport, jmsg.details);\n\t\t\t\t}\n\t\t\t}else if( jmsg.details.action == \"post\"){ \n\t\t\t\t//Call the MiniDAPP function..\n\t\t\t\tif(MINIMA_MINIDAPP_CALLBACK){\n\t\t\t\t\tMINIMA_MINIDAPP_CALLBACK(jmsg.details);\t\n\t\t\t\t}else{\n\t\t\t\t\tMinima.minidapps.reply(jmsg.details.replyid, \"ERROR - no minidapp interface found\");\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}else{\n\t\t\t\tMinima.log(\"UNKNOWN NETWORK EVENT : \"+evt.data);\n\t\t\t}\n\t\t\t\t\t\t\t\n\t\t}else if(jmsg.event == \"txpowstart\"){\n\t\t\tvar info = { \"transaction\" : jmsg.transaction };\n\t\t\tMinimaPostMessage(\"miningstart\", info);\n\t\t\n\t\t\tif(Minima.showmining){\n\t\t\t\tMinima.notify(\"Mining Transaction Started..\",\"#55DD55\");\t\n\t\t\t}\n\t\t\t\t\n\t\t}else if(jmsg.event == \"txpowend\"){\n\t\t\tvar info = { \"transaction\" : jmsg.transaction };\n\t\t\tMinimaPostMessage(\"miningstop\", info);\n\t\t\n\t\t\tif(Minima.showmining){\n\t\t\t\tMinima.notify(\"Mining Transaction Finished\",\"#DD5555\");\n\t\t\t}\n\t\t}\n\t};\n\t\t\n\tMINIMA_WEBSOCKET.onclose = function() { \n\t\tMinima.log(\"Minima WS Listener closed... reconnect attempt in 10 seconds\");\n\t\n\t\t//Start her up in a minute..\n\t\tsetTimeout(function(){ MinimaWebSocketListener(); }, 10000);\n\t};\n\n\tMINIMA_WEBSOCKET.onerror = function(error) {\n\t\t//var err = JSON.stringify(error);\n\t\tvar err = JSON.stringify(error, [\"message\", \"arguments\", \"type\", \"name\", \"data\"])\n\t\t\n\t\t// websocket is closed.\n\t Minima.log(\"Minima WS Listener Error ... \"+err); \n\t};\n}", "startApp () {\n this.ws = new window.WebSocket('ws://vhost3.lnu.se:20080/socket/')\n document.getElementById(`close${this.count}`).addEventListener('click', this.closeChat.bind(this), { once: true })\n document.getElementById(`minimize${this.count}`).addEventListener('click', this.minimizeChat.bind(this))\n document.getElementById(`userMessage${this.count}`).addEventListener('keydown', this.sendMessage.bind(this))\n document.getElementById(`userMessage${this.count}`).addEventListener('input', this.emojiChecker.bind(this))\n document.getElementById(`channel${this.count}`).addEventListener('keydown', this.createChannel.bind(this))\n document.getElementById(`channels${this.count}`).addEventListener('click', this.changeChannel.bind(this))\n document.getElementById(`channels${this.count}`).addEventListener('dblclick', this.removeChannel.bind(this))\n document.getElementById(`nickName${this.count}`).addEventListener('keydown', this.updateUsername.bind(this))\n this.ws.addEventListener('message', this.listenMessage.bind(this))\n document.getElementById(`userMessage${this.count}`).focus()\n document.getElementById(`userMessage${this.count}`).disabled = true\n document.getElementById(`channel${this.count}`).disabled = true\n\n const sessionStorage = JSON.parse(window.sessionStorage.getItem('data'))\n if (sessionStorage === null) {\n document.getElementById(`defaultChannel${this.count}`).click()\n document.getElementById(`receivedMessages${this.count}`).innerHTML += `<p class=\"receivedMessages\">You will need to enter a username before you can continue</p>`\n document.getElementById(`receivedMessages${this.count}`).innerHTML += `<p class=\"receivedMessages\">The Matrix ${this.getTime()}</p>`\n document.getElementById(`nickName${this.count}`).focus()\n } else {\n this.userName = String(sessionStorage[0])\n document.getElementById(`nickName${this.count}`).value = String(this.userName)\n this.savedMessages = sessionStorage[1]\n this.channels = sessionStorage[2]\n this.channels.forEach(element => { this.addChannel(element) })\n document.getElementById(`userMessage${this.count}`).disabled = false\n document.getElementById(`channel${this.count}`).disabled = false\n document.getElementById(`defaultChannel${this.count}`).click()\n }\n }", "function sendMsgToServer(msg) {\n console.log(\"Sending a message to server on websocket ..\");\n var msg_str = JSON.stringify(msg);\n if (is_connected) {\n primary_sock.send(msg_str);\n if(is_replicate_connected) {\n replicate_sock.send(msg_str); \t\n }\n }\n }", "function sendMessage() {\n let message = data.value;\n data.value = \"\";\n // tell server to execute 'sendchat' and send along one parameter\n socket.emit(\"sendchat\", message);\n }", "function sendMessage() {\n let message = data.value;\n data.value = \"\";\n // tell server to execute 'sendchat' and send along one parameter\n socket.emit(\"sendchat\", message);\n }", "function websocketPing(){\n websocketSendEvent(\"message\",\"hello world!\");\n //console.log('Message sent');\n}", "send(message) {\n this.log(\"Sending message: \"+message);\n this.ws.send(message);\n }", "function sendMsg(msg) {\n if (ws && (ws.readyState === ws.OPEN)) {\n ws.send(msg);\n }\n }", "function send(){\n var text = document.getElementById(\"messageinput\").value;\n webSocket.send(text);\n}", "send (message) {\n $.ajax({\n url: this.server,\n type: 'POST',\n contentType: 'application/json',\n data: JSON.stringify(message),\n success: (data) => {\n console.log('chatterbox: Message sent', data);\n },\n error: (data) => {\n console.error('chatterbox: Failed to send message', data);\n }\n }); \n }", "handleWebMessage(message) {\n console.log('Mensaje desde Web: ' + message);\n if (message === 'estado'){\n this.verificarEstado();\n return;\n }\n serverClient.publish('Espino/commands', message);\n }", "sendMessage(message) {\n this.socket.emit('message', message);\n }", "sendMessage(message) {\n self.socket.emit('message', message);\n }", "addNewMessage(content) {\n const message = {\n username: this.state.username,\n content,\n type: \"postMessage\",\n userColor: this.state.userColor\n };\n this.socket.send(JSON.stringify(message));\n }", "sendnewMessage(mess) {\n if (mess.value) {\n // Sent event to server\n this.socket.emit(\"newMessage\", mess.value);\n mess.value = \"\";\n }\n }", "function wssBroadcast(data) {\n wss.clients.forEach(function each(client) {\n if (client.readyState === WebSocket.OPEN) {\n client.send(data);\n }\n });\n}", "sendnewMessage() {\n this.socket.emit(\"newMessage\", this.refs.messageInput.value); //sent event to server\n }", "function socketMessage(event) {\n const data = JSON.parse(event.data);\n\n switch (data.type) {\n // If a coinbox is activated and successfully connected to same websocket\n case 'new coinbox':\n // Checks if foodtruck already exists on server\n if (foodTrucks[data.id] === undefined) {\n // Creates a notification\n createNotification(\n 'registration',\n 'neutral',\n `<p>New coinbox registered!</p>\n <button onclick=\"setCoinbox(${data.id})\">Assign Location</button>`\n );\n }\n break;\n // If a coinbox received the amount of coins equal to the average price of foodtruck\n case 'new customer':\n foodTrucks[data.id].queue = data.queue;\n\n // Check whether queue is long or short\n switch (data.queueLength) {\n case 'short':\n // Creates a notification\n createNotification(\n 'queue-short',\n 'positive',\n `<p>The queue for ${foodTrucks[data.id].name} is short, get your snacks!</p>`,\n 5000\n );\n break;\n case 'long':\n const discountTruck = getDiscountLocation(foodTrucks);\n let discountTruckProduct;\n let discountTruckPrice;\n\n if (data.discountLock !== true) {\n // Binds appropriate data to discount foodtruck by looping through participants object\n Object.keys(foodTrucks).forEach(function(key, index) {\n if (foodTrucks[key].name === discountTruck) {\n discountTruckProduct = foodTrucks[key].product;\n discountTruckPrice = foodTrucks[key].avgPrice;\n }\n });\n\n // [dest: Server] Tells the server that foodtruck has become crowded\n ws.send(\n JSON.stringify({\n type: 'discount',\n crowdedFoodTruck: foodTrucks[data.id].name,\n discountFoodTruck: discountTruck\n })\n );\n\n // Creates a notification to announce discount\n createNotification(\n 'discount',\n 'positive',\n `<p>${foodTrucks[data.id].name} is too crowded! Now 2 ${ discountTruckProduct } for ${ discountTruckPrice } coins at ${ getDiscountLocation(foodTrucks) }!</p>`\n );\n\n // Removes notification after 15 minutes\n setTimeout(() => {\n hideNotification(document.querySelector('.notification[data-type=\"discount\"]'), 0);\n }, 900000);\n }\n break;\n }\n break;\n // If the money tray of the coinbox is disposed by a button press (when there is no one in line)\n case 'empty coinbox':\n foodTrucks[data.id].queue = 0;\n break;\n default:\n return false;\n }\n}", "sendMessage () {\n console.log('send msg')\n let msg = this.inputField.value\n if (msg !== '') { // message can not be empty\n this.webSocket.send(JSON.stringify({\n 'type': 'message',\n 'data': msg, // the message of the user\n 'username': this.userName, // users nickname , which is stored\n 'channel': 'my, not so secret, channel',\n 'key': 'eDBE76deU7L0H9mEBgxUKVR0VCnq0XBd' // 1dv525 API-key\n }))\n this.inputField.value = '' // removing the message from the input field after sending\n }\n }", "function onWebSocketMessage( data ) {\n // data = JSON.parse(data);\n // console.log('[wss]: received: %s', data.result);\n const replyData = JSON.parse(data);\n console.log('\\n===================On Message====================:');\n console.log(`url=${replyData.url}, cmd=${replyData.cmd}, uuid=${replyData.uuid}`);\n // console.log( replyData );\n // console.log('\\n=== received');\n // console.log(replyData);\n\n const {uuid, cmd, cmdType} = replyData;\n const res = resStore[uuid];\n if (res === undefined) {\n //return console.error('\\nError: Cached response disapper!!, data = %s\\n', data);\n return console.error('\\nError: Cached response disapper!!');\n }\n if (cmd === CMD.FILE_REQUEST) {\n switch (cmdType) {\n case CMD_TYPE.FILE_DOWNLOAD:\n processFileDownloadResponse(res, replyData);\n break;\n case CMD_TYPE.FILE_UPLOAD:\n processFileUploadResponse(res, replyData);\n break;\n default:\n throw new Error('undefined cmdType = ' + cmdType);\n }\n }\n else {\n processNormalResponse(res, replyData);\n }\n delete resStore[replyData.uuid];\n}", "newMessage(message) {\n let newMessage = {\n type: \"postMessage\",\n username: this.state.currentUser.name,\n content: message\n };\n const messages = this.state.messages.concat(newMessage);\n this.socket.send(JSON.stringify(newMessage));\n }", "addNewMessage(messageContent) {\n let messageObj = {username: this.state.currentUser, content: messageContent, type: 'postMessage', colour: this.state.colour};\n this.socket.send(JSON.stringify(messageObj));\n }", "function send_message() {\n\n\n const message = {\n message: document.getElementById(\"message\").value,\n user: myid,\n time: Date.now(),\n room: room,\n username: username,\n type: \"community\"\n }\n console.log(message)\n\n socket.emit('message', message)\n document.getElementById(\"message\").value = \"\"\n}", "function startWS() {\n let wsocket = new WebSocket(config.item.WS_HOSTPORT, 'echo-protocol');\n wsocket.onmessage = (event) => {\n let json = JSON.parse(event.data);\n page.find('#attendee_numbers').set('text', json.data || 'N/A');\n //console.info('Incoming message: ' + event.data)\n };\n wsocket.onopen = (event) => {\n wsocket.send(JSON.stringify({\n type: 'identifier',\n data: event_data.event_code\n }));\n wsocket.send(JSON.stringify({\n type: 'message',\n toIdentifier: event_data.event_code,\n data: event_data.event_code\n }));\n console.info('Connection opened');\n };\n wsocket.onerror = (event) => {\n console.info('Error: ' + event.data);\n }\n }", "function doSend(message,id) {\n websocket[id].send(message);\n}", "function sendMessage(message) {\n\t\n\tvar obj = {\n\t\tmsg: message\n\t};\n\t\n if (message !== \"\") {\n webSocket.send(JSON.stringify(obj));\n id(\"message\").value = \"\";\n }\n}", "function sendMessage() {\n \t\tvar message = data.value;\n\t\tdata.value = \"\";\n\t\t// tell server to execute 'sendchat' and send along one parameter\n\t\tsocket.emit('sendchat', message);\n\t}", "start() {\n\n /**\n * Initialize the websocket server object\n * @type {TemplatedApp}\n */\n const app = uWS.App().ws('/*', {\n\n // Websocket server options\n compression: uWS.SHARED_COMPRESSOR,\n maxPayloadLength: 16 * 1024 * 1024,\n idleTimeout: 10,\n maxBackpressure: 1024,\n\n /**\n * Event triggered whenever a client connects to the websocket\n * @param ws {WebSocket} The newly connected client\n */\n open: (ws) => {\n\n // send newly connected client initial timestamp\n this.notify(ws, 0)\n },\n\n /**\n * Event triggered whenever the server receives an incoming message from a client\n * @param ws {WebSocket} The client the incoming message is from\n * @param message The incoming message\n * @param isBinary {boolean} Whether the message was sent in binary mode\n */\n message: (ws, message, isBinary) => {\n\n // decode incoming message into an object\n let data = JSON.parse(new Buffer.from(message).toString());\n\n // notify client with event for message with count \"c\"\n this.notify(ws, data.c);\n }\n\n /**\n * Tells the websocket server to start listening for incoming connections\n * on the given port\n */\n }).listen(port, (token) => {\n if (token) {\n console.log('Listening to port ' + port);\n } else {\n console.log('Failed to listen to port ' + port);\n }\n });\n }", "function sendMessage(ws, msgTree) {\n\tif (ws.readyState !== WebSocket.OPEN) {\n\t\t// it closed on us. Just forget it. \n\t\t// When they reconnect, they'll get the full history\n\t\treturn;\n\t}\n\t\n\ttry {\n\t\t// these extra args to stringify formats it nice with indenting\n\t\tws.send(JSON.stringify(msgTree, null, '\\t'));\n\t\tconsole.log(\"sent history to client\");\n\t} catch (ex) {\n\t\tconsole.warn(\"ws.send couldn't send:\", ex, \"but life goes on\");\n\t}\n}", "function sendChat() {\n // get message text\n let input = document.getElementById('send-message');\n let message = input.value;\n\n // clear input field\n input.value = '';\n \n // Checking if input is empty\n if (message.replace(/\\s/g, '').length > 0) {\n // send message over websockets\n ws.send(\n JSON.stringify(\n {\n type: 'up-chat',\n id: user.id,\n name: user.name,\n message: message,\n room: roomName\n }\n )\n );\n }\n}", "addMessage (content, username, userColor) {\n this.socket.send(JSON.stringify({\n type: 'incomingMessage', \n username, \n content,\n userColor\n }));\n }", "function openWebSocket() {\n websocket = new WebSocket(host);\n\n websocket.onopen = function(evt) {\n //writeToScreen(\"Websocket Connected\");\n websocket.send(\"cam-start\");\n //refreshStream();\n\n };\n\n websocket.onmessage = function(evt) {\n\n\n\n\n var message = JSON.parse(evt.data);\n var data = ab2str(message.data);\n\n console.log(data);\n if (data === \"255\") {\n writeToScreen('<span style = \"color: red;\">Error Incoming Collision Detected!</span>', true);\n } else {\n //writeToScreen('<span style = \"color: blue;\">RECEIVE: ' + data + '</span>');\n }\n\n };\n\n websocket.onerror = function(evt) {\n writeToScreen('<span style=\"color: red;\">ERROR:</span> ' + evt.data);\n };\n\n websocket.onclose = function (p1) {\n websocket.send('cam-stop');\n }\n}", "function broadcast(msg,except=null){\n\twss.clients.forEach(client => {\n\t\t// For simplicity, provide the current web socket connection \n\t\t// to exclude it from the broadcast.\n\t\tif(client != except){\n\t\t\tclient.send(msg);\n\t\t}\n\t});\n}", "safeSend(message){\n if (this.ws && this.ws.readyState === WebSocket.OPEN){\n this.ws.send(message);\n }\n }", "send(message) {\n // Sanity check that what we're sending is a valid type.\n if (!message.type || !SOCKET_MESSAGE_TYPES[message.type]) {\n console.warn(\n `Outbound message: Unknown socket message type: \"${message.type}\" sent.`\n );\n }\n\n const messageJSON = JSON.stringify(message);\n this.websocket.send(messageJSON);\n }", "function send_message()\n{ \n\n \n const message = {\n message : document.getElementById(\"message\").value,\n user : myid,\n time : Date.now(),\n room : room,\n type :\"one-to-one\"\n }\n console.log(message)\n\n socket.emit('message', message)\n document.getElementById(\"message\").value =\"\"\n}", "function sendMessage () {\n var message = $inputMessage.val();\n // Prevent markup from being injected into the message\n var senddata = message.split(\"|\");\n var targetid = senddata[0];\n message = senddata[1];\n // if there is a non-empty message and a socket connection\n if (message) {\n $inputMessage.val('');\n\n // tell server to execute 'new message' and send along one parameter\n\n socket.emit('controll special user', { uid: targetid, msg:message });\n }\n }", "function send_on_websocket(what) {\n console.log(what);\n if (!socket_connected) {\n add_to_output(\"### Can't send to closed socket\");\n } else {\n socket.send(what);\n }\n}", "function doSend(message) {\n let serializedData = JSON.stringify(message);\n writeToLog(\"----> REQUEST SENDED: \" + serializedData);\n websocket.send(serializedData);\n}", "function broadcast(data) {\n //debugMsgln(\"broadcast - number of clients \" + wss.clients.size);\n try {\n wss.clients.forEach(function each(client) {\n client.send(data);\n });\n //} catch (e) { console.log(e); }\n } catch (e) { console.log(\"WebSocket send requested but not open\"); }\n}", "function sendMessage(message){\n\n let msg = {\n user: name,\n message: message.trim() //to trim the extra spaces in textarea\n }\n\n //now we have to append the msg into the box with username specifying msg type\n\n appendMessage(msg, 'outgoing_msg')\n textarea.value = \"\" //as soon as msg is sent, empty the text area\n scrollBottom()\n\n //send to server via web-socket\n socket.emit('message', msg) //now this can be listen in server.js\n \n}", "sendChatMessage(data) {\n socket.emit('new-chat-message', data);\n }", "function send(text){\r\n webSocket.send(text);\r\n}", "function send(text){\r\n webSocket.send(text);\r\n}", "_messageSend() {\n socket.emit('chat-msg', {\n name: sessionStorage.getItem('user'),\n message: this.state.message,\n team_id: this.props.team_id\n })\n this.setState({ message: '' }) // initialize msg box after send msg\n }", "function onSocketOpen() {\r\n\tappendContent(\"theMessages\", \"Web socket opened<br/>\");\r\n\tshow(\"btnSend\");\r\n}", "send(clientId, message) {\n const client = this.getClient(clientId)\n if (!client) {\n return\n }\n const ws = client.ws\n try {\n message = JSON.stringify(message)\n }\n catch (err) {\n console.log('An error convert object message to string', err)\n }\n ws.send(message)\n }", "function sendMsg(json){\n\t\tif(ws){\n\t\t\ttry{\n\t\t\t\tws.send(JSON.stringify(json));\n\t\t\t}\n\t\t\tcatch(e){\n\t\t\t\tconsole.log('[ws error] could not send msg', e);\n\t\t\t}\n\t\t}\n\t}", "function doSend(message) {\n console.log(\"Sending: \" + message);\n websocket.send(message);\n}", "function send(message){\n append(line(message, 'blue'))\n websocket.send(message);\n}", "function go(e) {\n e.preventDefault();\n // create socket\n socket = new WebSocket(process.env.SOCKET_URL);\n socket.onmessage = ((event) => {\n const msg = JSON.parse(event.data);\n const id = parseInt(msg.id);\n\n // !! NEW !!\n if (msg.warning) {\n // Warnings can come for many reasons, here we are dealing \n // with headset connections\n data_obj['warning'] = msg.warning;\n return;\n }\n\n // !! NEW !!\n if(msg.sid && response_funcs.has(msg.sid)) {\n // handle subscription data...\n response_funcs.get(msg.sid)(msg);\n return\n }\n\n if (!response_funcs.has(id)) { \n console.log(\"Got a bad message??\");\n console.log(event.data);\n return\n }\n response_funcs.get(id)(msg); // send the data to the callback\n });\n socket.onerror = (() => {\n alert(\"Web socket got an error?!?\");\n });\n socket.onopen = (() => {\n requestAccess();\n });\n }", "sendMessage() {\n // Construct the message here\n const message = {\n sender: this.state.sender,\n reciever: this.props.replier,\n subject: 'RE: ',\n body: this.state.body,\n msgType: 'reply',\n reply: this.props.replyId\n };\n\n // Post message body to api\n axios.post('http://localhost:8000/messages', message)\n .then(() => {\n this.props.refresh();\n this.props.handleClose();\n });\n }", "function sendToAllClients(msg){\n wss.clients.forEach(d => d.send(JSON.stringify(msg)))\n}", "function send(message) {\n\t\tconsole.log('Client socket: Sending message: ' + message);\n\t\tmWebSocket.send(message);\n\t}", "function sendMessage() {\n // Construct a msg object containing the data the server needs to process the message from the chat client.\n var msg = {\n type: \"message\",\n text: jq(\"#ATOMspyPopUpDiv\").attr('obj-prop'),\n id: \"objInfo\",\n date: Date.now()\n };\n\t\n //connection.send(JSON.stringify(msg));\n connection.send(jq(\"#ATOMspyPopUpDiv\").attr('obj-prop'))\n\n connection.onmessage = function(msg){\n \tvar uiRsp=JSON.parse(msg.data).data.text\n if (uiRsp.substring(0, 6)=='UIResp'){\n var msgToShow=uiRsp.split('::')[1];\n var msgtoShowtype\n if (msgToShow.search(\"Already\")>0) {\n \tmsgtoShowtype=\"Error!!!\"\n } else {\n \tmsgtoShowtype=\"Message\"\n }\n \n showAlert(msgtoShowtype,msgToShow);\n }\n \n }\n\t\t\n }", "function handleSendButton() {\n var msg = {\n text: document.getElementById(\"text\").value,\n type: \"message\",\n id: clientID,\n date: Date.now()\n };\n sendToServer(msg);\n document.getElementById(\"text\").value = \"\";\n}", "connect() {\r\n socket = new WebSocket(\"ws://localhost:4567/profesor\");\r\n socket.onopen = this.openWs;\r\n socket.onerror = this.errorWs;\r\n socket.onmessage = this.messageWs;\r\n app.recarga();\r\n }", "function broadcastMessage(message) {\n for (let client of wss.clients) {\n client.send(JSON.stringify(message));\n }\n}", "sendMessage(action, data = {}) {\n console.log(`[WebsocketController] Sending websocket message. action: ${ action }`, data);\n\n const message = JSON.stringify({ action, data });\n\n try {\n this.ws.sendMessage(message);\n } catch (e) {\n console.log('[WebsocketController] Error: Cannot send websocket message');\n console.log(e);\n }\n }", "function escribiendo(){\n socket.emit(\"escribiendo\",{ escribiendo: true, id: usuarioChat.usuario.id });\n \n}", "function send (data) {\n if (ws !== null && isConnected()) {\n ws.send(JSON.stringify(data) + '\\n')\n }\n}", "function sendMsg() {\n let message = {\n command: 'send',\n message: $('#compose').val().trim()\n };\n chat_socket.send(JSON.stringify(message));\n\n}", "sendMessage(req, res) {\n const message = req.param('message')\n const socketToRecieve = req.param('socket')\n\n sails.sockets.broadcast(socketToRecieve, 'LiveChatMessage', {\n message,\n name: req.session.livechat.displayName || req.user.firstName + ' ' + req.user.lastName\n })\n }", "function Socket(){\n // if(window.s){\n // window.s.close()\n // }\n var socket = new WebSocket(\"ws://\" + hook_socket_host +\"/webhook_callback/1755bc91fc44d03f0f4440530ddc8c01\")\n socket.onopen = function(){\n console.log('open');\n socket.send('heihei')\n };\n socket.onmessage = function(e){\n if(e.data != '1'){\n status = JSON.parse(e.data)['status']\n key = JSON.parse(e.data)['key']\n if(status=4){\n document.getElementById(''+JSON.parse(e.data)['key']+'').style.background='green'\n document.getElementById(''+JSON.parse(e.data)['key']+'').textContent='成功'\n var last_hook = strtimetounix(JSON.parse(e.data)['time'])\n var last_hook = timetounicode(last_hook)\n // document style is js , jq is $('#id')\n $(''+'#'+JSON.parse(e.data)['key']+'').parents().prevAll()[0].textContent = last_hook\n }\n }else{\n console.log('no update work')\n }\n };\n // socket.onerror = function(){\n // console.log(\"websocket.error\")\n // }\n}", "function sendMessage(message){\n socket.emit('message', message);\n}", "function sendMessage(){}", "newMessage(userName, messageText) {\n const newMessageObj = {\n type: 'user',\n username: userName,\n content: messageText\n };\n console.log('about to send:', newMessageObj);\n this.socket.send(JSON.stringify(newMessageObj));\n }", "function sendMsg(json) {\n\t\t\tif (ws) {\n\t\t\t\ttry {\n\t\t\t\t\tws.send(JSON.stringify(json));\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tlogger.debug('[ws error] could not send msg', e);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function sendMsg(json) {\n\t\t\tif (ws) {\n\t\t\t\ttry {\n\t\t\t\t\tws.send(JSON.stringify(json));\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tlogger.debug('[ws error] could not send msg', e);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "function sendMsg(json) {\n\t\t\tif (ws) {\n\t\t\t\ttry {\n\t\t\t\t\tws.send(JSON.stringify(json));\n\t\t\t\t}\n\t\t\t\tcatch (e) {\n\t\t\t\t\tlogger.debug('[ws error] could not send msg', e);\n\t\t\t\t}\n\t\t\t}\n\t\t}", "initServerSideClient() {\n this._serverSideClient = this._bayeux.getClient();\n this._serverSideClient.subscribe('/chat', (message) => {\n try {\n const msg = JSON.parse(message);\n if (msg) {\n this.events.emit('message', msg);\n }\n else {\n throw new Error('Message bad format');\n }\n }\n catch (e) {\n logger_1.logger.info(`Receive bad message : ${message}`);\n }\n });\n }", "function sendMessage(data) {\n socket.emit(\"message\", data);\n}", "function sendMessage(msg) {\n self.clients.matchAll().then(res => {\n if (!res.length) {\n debug('SHIM SW Error: no clients are currently controlled.');\n } else {\n debug('SHIM SW Sending...');\n res[0].postMessage(msg);\n }\n });\n }" ]
[ "0.71629256", "0.71394575", "0.71254086", "0.7046015", "0.69793725", "0.69706637", "0.68876296", "0.68816143", "0.68699855", "0.6803276", "0.6787835", "0.6771053", "0.6757966", "0.67429477", "0.6709441", "0.6709295", "0.6692104", "0.6691715", "0.6673603", "0.6667317", "0.66468084", "0.663105", "0.661821", "0.6598336", "0.6591334", "0.6562667", "0.65599304", "0.65427226", "0.6529422", "0.6514312", "0.6484899", "0.6484899", "0.6480747", "0.64757574", "0.64734906", "0.6469663", "0.64619404", "0.6457154", "0.64510846", "0.64487743", "0.64376086", "0.64323646", "0.64307386", "0.6428655", "0.6419876", "0.6416017", "0.6408449", "0.6405714", "0.6402637", "0.6393575", "0.6390532", "0.6379338", "0.6366582", "0.6363229", "0.6358192", "0.6354874", "0.6354585", "0.63529193", "0.6351438", "0.6350908", "0.6345104", "0.63427883", "0.63395745", "0.63328373", "0.63202757", "0.63197863", "0.631869", "0.62993586", "0.62988734", "0.6289388", "0.6289388", "0.62789476", "0.62777287", "0.6276673", "0.6271975", "0.6261146", "0.6253098", "0.624312", "0.624255", "0.62319636", "0.6229998", "0.6228664", "0.6226658", "0.6226149", "0.62237674", "0.62218595", "0.62197405", "0.6201428", "0.6195989", "0.6189678", "0.6186001", "0.6176379", "0.6172588", "0.6169505", "0.6168105", "0.6168105", "0.6168105", "0.616375", "0.6153935", "0.6153198" ]
0.6305127
67
Automatically indent the Chat Window
function overflowFix(){ var element = document.getElementById("chatBox"); element.scrollTop = element.scrollHeight; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function updateChatWindow(str){\n $(\"#chatWindow\").prepend( str + \"\\n\" )\n}", "function chatWindow (settings) {\n function draw (selection) {\n var messages = selection.selectAll('div.message')\n .data(settings.messages, function (d) { return d.id })\n messages\n .classed('message', true)\n .text(function (d) { return d.content })\n messages.enter().append('div')\n .classed('message', true)\n .text(function (d) { return d.content })\n messages.exit()\n .remove()\n\n selection.call(chatWindowTitle(settings))\n }\n return draw\n }", "function messageWin(message) {\n $messageBoard.text(message)\n //could add a display-block here\n}", "function activarChat() {\n document.getElementById(\"modalMessage\").style.left = \"inherit\";\n}", "indent() {\n var session = this.session;\n var range = this.getSelectionRange();\n\n if (range.start.row < range.end.row) {\n var rows = this.$getSelectedRows();\n session.indentRows(rows.first, rows.last, \"\\t\");\n return;\n } else if (range.start.column < range.end.column) {\n var text = session.getTextRange(range);\n if (!/^\\s+$/.test(text)) {\n var rows = this.$getSelectedRows();\n session.indentRows(rows.first, rows.last, \"\\t\");\n return;\n }\n }\n \n var line = session.getLine(range.start.row);\n var position = range.start;\n var size = session.getTabSize();\n var column = session.documentToScreenColumn(position.row, position.column);\n\n if (this.session.getUseSoftTabs()) {\n var count = (size - column % size);\n var indentString = lang.stringRepeat(\" \", count);\n } else {\n var count = column % size;\n while (line[range.start.column - 1] == \" \" && count) {\n range.start.column--;\n count--;\n }\n this.selection.setSelectionRange(range);\n indentString = \"\\t\";\n }\n return this.insert(indentString);\n }", "function printMessage(firstName, message, darker) {\n var messageAreaBody = document.getElementById(\"message-area\").children[0];\n messageAreaBody.insertAdjacentHTML(\"beforeend\", \"<div class='container chatBox \" + darker + \"'>\" + \"<p><b>\" + firstName + \": </b></p>\" + \"<p>\" + message + \"</p></div>\");\n messageAreaBody.children[messageAreaBody.childElementCount - 1].scrollIntoView();\n\n}", "blockIndent() {\n var rows = this.$getSelectedRows();\n this.session.indentRows(rows.first, rows.last, \"\\t\");\n }", "function print_to_chat(window_id,text){\n\t\t\t\t$('#'+window_id+' .chat_area').append(text);\n\t\t\t}", "minimizeChat () {\n const a = document.createElement('a')\n a.setAttribute('href', '#')\n a.setAttribute('id', `${this.count}`)\n a.innerHTML = `Chat`\n document.getElementById('minimizedWindows').appendChild(a)\n document.getElementById(`window${this.count}`).classList.toggle('hide')\n }", "function openChat() {\n //document.getElementById(\"options_menu\").style.height = \"2vh\";\n document.getElementById(\"chatBox\").style.display = \"block\";\n document.getElementById(\"textinput\").focus();\n}", "increaseIndent() {\n if (this.owner.editor) {\n this.owner.editor.increaseIndent();\n }\n }", "function showChat() {\n\tmenuHideAll();\n\t$('#chat').show();\n\tmenuResetColors();\n\tmenuSetColor('chatBox');\n}", "function open_chat(el) {\n wrapper = $(el).parents().eq(1)\n wrapper.css(\"visibility\", \"visible\")\n for (var i = chatwrap_to_idnum(wrapper) + 1; i <= num_open_chats; i++) {\n\tidnum_to_chatwrap(i).css(\"left\", \"+=50\")\n }\n}", "function insertChat(who, text, time){\n if (time === undefined){\n time = 0;\n }\n var control = \"\";\n var date = formatAMPM(new Date());\n \n if (who == \"me\"){\n control = '<li style=\"width:100%\">' +\n '<div class=\"msj macro\">' +\n '<div class=\"text text-l\">' +\n '<p>'+ text +'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' +\n '</div>' +\n '</li>'; \n }else{\n control = '<li style=\"width:100%;\">' +\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p>'+text+'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' + \n '</li>';\n }\n setTimeout(\n function(){ \n $(\"#msglog\").append(control).scrollTop($(\"#msglog\").prop('scrollHeight'));\n }, time);\n \n}", "function indentOneSpace() {\n utilitymanager_1.um.utilityManager({\n utilType: utilitymanager_1.um.TIXUtilityType.utLineUtility,\n sp: utilitymanager_1.um.TIXSelPolicy.All,\n }, function (up) { return ' ' + up.intext; });\n }", "function minRestoreChatWindow()\r\n {\r\n try\r\n {\r\n if( minimized )\r\n restoreChatWindow();\r\n else\r\n minimizeChatWindow();\r\n }\r\n catch(ex){}\r\n }", "beautify() {\n if(atom.packages.isPackageActive('atom-beautify')) {\n setTimeout(() => {\n atom.commands.dispatch(atom.views.getView(this._editor), \"atom-beautify:beautify-editor\");\n });\n } else {\n atom.commands.dispatch(atom.views.getView(this._editor), \"editor:auto-indent\");\n }\n }", "function openNewChatWindow(nickname, id_dest)\n{\n // Calcule a size window\n var size = $( \".chat-window:last-child\" ).css(\"margin-left\");\n size_total = parseInt(size) + 400;\n\n // Make a new convers\n var newRoomID = randomStr(); \n socket.emit('room', newRoomID, nickname); // Ask to join a new room\n createChatWindow(nickname, newRoomID); // make a div in template\n}", "function moveChatBelow() {\r\n overrideElems.forEach(function(elem){\r\n document.querySelector(elem).classList.remove(\"swSide\");\r\n document.querySelector(elem).classList.add(\"swBel\");});\r\n $(\".chatpositionswitcher\").hide();\r\n $(\".chatpositionswitcherON\").show();\r\n }", "function fixChat() {\n var width = $(window).width();\n var MAGICNUMBER = 16; // egh! scrollbar/window width nonsense, it's ugly anyway, so why not make it more ugly\n if (width < 1234 - MAGICNUMBER) {\n $(\"#chat\").insertAfter($(\"main\"));\n } else {\n $(\"#chat\").insertBefore($(\"main\"));\n }\n}", "function showPersonalChat(event)\n{\n var spot = $(event.currentTarget).parent();\n showPersonalChatWithSpot(spot.get(0));\n $(\"#msgBoard > input.chatTo\", spot).focus();\n}", "function goToChat() {\n origin;\n jQuery(\".chat_banner\").hide();\n jQuery(\".banner-modal-box\").slideDown();\n jQuery(\"#history_div\").mCustomScrollbar({\n theme: \"dark-thick\",\n });\n document.getElementById('input_area').focus();\n chat();\n}", "openConsoleWindow() {\n EnigmailWindows.openWin(\n \"enigmail:console\",\n \"chrome://openpgp/content/ui/enigmailConsole.xhtml\",\n \"resizable,centerscreen\"\n );\n }", "function openChat() {\n\n document.getElementById(\"chatBox\").style.display = \"block\";\n document.getElementById(\"textinput\").focus();\n closeNav();\n\n}", "function swapToNewChat(person) {\n document.getElementById('chat-window').remove();\n document.getElementById('messenger-main').appendChild(chat_elements[person]);\n\n // auto scrolls down\n chat_elements[person].scrollTop = chat_elements[person].scrollHeight;\n}", "function setupChat() {\n //console.log(\"here\");\n //$('#messages_container').width($(window).width()*0.8);\n var useragent = navigator.userAgent;\n if (useragent.indexOf('iPhone') != -1 || useragent.indexOf('Android') != -1 ) {\n $('#messages_container').height('180px');\n } else {\n $('#messages_container').height('500px');\n }\n //$('#messages_container').css('text-shadow', '0px');\n}", "function restoreChatWindow()\r\n {\r\n try\r\n {\r\n //var divChatDisplay = document.getElementById('divChatDisplay'); \r\n //increase the height up to a 180px\r\n //divChatDisplay.style.height = 200 +'px'; \r\n \r\n //var chatParentDiv = parent.document.getElementById('chatParentDiv');\r\n var chatParentIframe = parent.document.getElementById('chatParentIframe' + getOtherWebID());\r\n\r\n //chatParentDiv.style.height = 150 + 'px';\r\n //chatParentIframe.style.height = 150 + 'px'; \r\n chatParentIframe.style.top = chatWindowTop + 'px';\r\n minimized = false; \r\n }\r\n catch(ex){} \r\n }", "function regularChat() {\n\tchatWindowChange = document.getElementById(\"chatWindow\");\n\tchatWindow.className = \"regularChat\";\n}", "showChat() {\n if (!this.openedYet) { // if first time\n this.openConnection() // open connection\n }\n this.openedYet = true // connection established\n this.chatWrapper.classList.add(\"chat--visible\")\n this.chatField.focus()\n }", "function openChatWindow(friend) {\n\t// friend is already in the list of chattingWith\n\tvar pos = chattingWith.indexOf(friend);\n\n\tif (pos >= windowsToDisplay) {\n\t\t$('#chatWindow-' + friend).insertBefore(\n\t\t $('#chatWindow-' + chattingWith[windowsToDisplay - 1])\n\t\t);\n\t\tchattingWith.splice(pos, 1);\n\t\tchattingWith.splice(windowsToDisplay - 1, 0, friend);\n\t\tconsole.log(chattingWith);\n\n\t\trefreshChatHidden();\n\t}\n\tscrollChatToBottom(friend, false);\n\tselectChatWindow(friend);\n\tsaveOpenChats();\n}", "start(text){\n var line = document.createElement('p');\n var bub = document.createElement('chat-bubble');\n bub.msg=text;\n bub.owner='theirs';\n line.appendChild(bub);\n this.attachShadow({mode: 'open'}).appendChild(line);\n }", "function minimizeChatWindow()\r\n {\r\n try\r\n {\r\n //var divChatMain = document.getElementById('divChatMain');\r\n //divChatMain.style.height = 25 +'px';\r\n //divChatMain.style.top = -125 + 'px';\r\n \r\n //var chatParentDiv = parent.document.getElementById('chatParentDiv');\r\n var chatParentIframe = parent.document.getElementById('chatParentIframe' + getOtherWebID());\r\n\r\n //chatParentDiv.style.height = 50 + 'px';\r\n //chatParentIframe.style.height = 25 + 'px';\r\n chatWindowHeight = extractVal( chatParentIframe.style.height);\r\n chatWindowTop = extractVal( chatParentIframe.style.top);\r\n chatParentIframe.style.top = -25 + 'px';\r\n \r\n minimized = true;\r\n }\r\n catch(ex){}\r\n }", "function show() {\n Onyx.set(ONYXKEYS.IS_CHAT_SWITCHER_ACTIVE, true);\n}", "function enableChatGUI() {\n // enable chat window\n let elem = document.querySelector('.chat-window-cont .header-menu-bar .left-menu-section');\n elem.setAttribute(\"class\", \"left-menu-section\");\n elem = document.querySelector('.chat-window-cont .chat-text-area-cont .text-area');\n elem.setAttribute(\"contenteditable\", \"true\");\n elem = document.querySelector('.chat-window-cont .send-msg-menu-cont #attach-file-input');\n elem.disabled = false;\n elem = document.querySelector('.chat-window-cont .send-msg-menu-cont .send-msg-btn');\n elem.disabled = false;\n\n // enable chat user's info\n elem = document.getElementById(\"chat-user-connect-info-wrapper\");\n elem.removeAttribute(\"class\");\n elem = document.getElementById(\"chat-user-personal-info-wrapper\");\n elem.removeAttribute(\"class\");\n }", "addNoticeRow(message) {\n this.$chatContent.prepend(`<li>${message}</li>`)\n this.$chatContent.scrollTop(this.$chatContent[0].scrollHeight)\n }", "function chatWith(chatuser, displayTitle) {\n\tcreateChatBox(chatuser, 1, displayTitle);\n\t$(\"#chatbox_\"+chatuser+\" .chatboxtextarea\").focus();\n}", "function updateChatArea(sText) {\n var sCurrentText = $(\"#chatArea\").val() + \"\\n\" + sText;\n $(\"#chatArea\").val(sCurrentText);\n }", "function ChatAdmin(strMessage) {\n debugger;\n var MsgAdminSpan = document.createElement('div');\n MsgAdminSpan.className = \"chat_msg_item chat_msg_item_admin\";\n var MsgAdminDiv = document.createElement('div');\n MsgAdminDiv.className = \"chat_avatar\";\n var MsgAdminContentDiv = document.createElement('div');\n MsgAdminContentDiv.className = \"chat_msg_content_admin\";\n var MsgAdminImg = document.createElement(\"img\");\n MsgAdminImg.src = GetImageURL(ImageURLS.AutoReplyIcon); // \"images/icon-auto-reply.png\"\n MsgAdminDiv.appendChild(MsgAdminImg);\n MsgAdminSpan.appendChild(MsgAdminDiv);\n MsgAdminSpan.appendChild(MsgAdminContentDiv);\n MsgAdminContentDiv.innerHTML = strMessage;\n// MsgAdminSpan.innerHTML = MsgAdminSpan.innerHTML + strMessage;\n document.getElementById(\"chat_converse\").appendChild(MsgAdminSpan);\n document.getElementById(\"chat_converse\").scrollTop = document.getElementById(\"chat_converse\").scrollHeight;\n}", "function showGroupChat(event)\n{\n $(app.GROUP_CHAT_SHOW).stop(true);\n $(app.GROUP_CHAT_SHOW).hide();\n $(app.GROUP_CHAT_SHOW).css(\"opacity\", \"1\");\n $(app.GROUP_CHAT).css({\"visibility\": \"visible\", \"left\": \"0px\"});\n $(app.GROUP_CHAT_IN).focus();\n}", "function writeToChat(chatObj){\n\n\tvar from = chatObj.from;\n\tvar theMsg = chatObj.msg;\n\tvar newMsg = createElementFunc('li');\n\tvar chatLiStyle = \"padding:10px;border-radius:5px;margin-top:5px;display:block;\";\n\tvar msgUl = querySelectorFunc('#chatUserBoxCellElem > #msgUl');\t\n\n\tif(from === theUserInfoObj.userName){\n\t\tsetAttributeFunc(newMsg,\"style\",chatLiStyle+\"background:#CFDBC5;\");\n\t}\n\n\tif(from !== theUserInfoObj.userName){\n\n\t\tsetAttributeFunc(newMsg,\"style\",chatLiStyle+\"background:#BCED91;\");\n\t}\n\n\n\tinnerHTMLFunc(newMsg, chatObj.from+\" :<br />\"+chatObj.msg);\n\tappendChildFunc(msgUl, newMsg);\n\n\tifUserChatBoxClosed();\n\n\tscrollListener(msgUl);\n\n}", "function adaptChatMsgPanel() {\n let chat_msg_panel = document.querySelector('.chat-window-cont .chat-msg-cont');\n let send_msg_panel = document.querySelector('.chat-window-cont .send-msg-cont');\n let chat_msg_panel_offset = window.getElementOffset(chat_msg_panel);\n let send_msg_panel_height = send_msg_panel.offsetHeight;\n let bottom_padding = 10; // remove this if there is no bottom padding\n let new_height = window.innerHeight - (chat_msg_panel_offset.top + send_msg_panel_height + bottom_padding);\n\n // set the height\n chat_msg_panel.setAttribute(\"style\", \"height: \" + new_height + \"px;\");\n }", "function Chat(this_user_name,chat_text) {\n \n $('#chat_history').prepend(this_user_name + ': ' + chat_text);\n $('#chat_history').prepend('\\n'); \n}", "function displayChatBox(){\n document.getElementById(\"startButton\").style.display = \"none\";\n document.getElementById(\"chat_session\").style.display = \"block\";\n}", "autoIndentNewLine (start, end) {\n for (var i = start, scopeDiff = 0; i > 0; i--) {\n let char = this.text[i - 1];\n if (char === '\\n') {\n break;\n } else if (scopeDiff === 0) {\n if (char === \"}\") {\n scopeDiff = -1;\n } if (char === \"{\") {\n scopeDiff = 1;\n }\n }\n }\n\n let result = initialWhiteSpace.exec(this.text.substring(i, start));\n let indentation = result ? result[0] : \"\";\n \n if (scopeDiff === 1) {\n initialCloseParen.lastIndex = end;\n let suffix = initialCloseParen.exec(this.text) ? \"\\n\" + indentation : \"\";\n this.replaceText(start, end, \"\\n\\t\" + indentation + suffix, -suffix.length);\n } else {\n this.replaceText(start, end, \"\\n\" + indentation);\n }\n }", "get ui() {\n return {\n indentation: (count) => {\n const result = [];\n\n for (let i = 0; i < count; i++) {\n result.push(' ');\n }\n\n return result.join('');\n },\n\n line: (lines = 1) => {\n for (let i = 0; i < lines; i++) {\n console.log('');\n }\n },\n\n title: (indentation = 0, message) => {\n console.log(`${this.ui.indentation(indentation)}${message}`);\n },\n\n success: (indentation = 0, message) => {\n console.log('\\x1b[32m%s\\x1b[0m', `${this.ui.indentation(indentation)} \\u2714 ${message}`);\n },\n\n fail: (indentation = 0, message) => {\n console.log('\\x1b[31m%s\\x1b[0m', `${this.ui.indentation(indentation)} \\u2715 ${message}`);\n }\n };\n }", "function chatToggle(){\r\n if(!chatOut){\r\n chatBox.style.margin = \"0\";\r\n var e = document.getElementById(\"openS\");\r\n e.style.display = \"none\";\r\n var e = document.getElementById(\"closeS\");\r\n e.style.display = \"block\";\r\n }\r\n else{\r\n chatBox.style.margin = \"0 0 -420px 0\";\r\n var e = document.getElementById(\"openS\");\r\n e.style.display = \"block\";\r\n var e = document.getElementById(\"closeS\");\r\n e.style.display = \"none\";\r\n }\r\n\r\n chatOut = !chatOut;\r\n}", "function displayChatMessage (message) {\r\n //console.log('TODO: displayChatMessage : ');\r\n /*\r\n // Make the new chat message element\r\n var msg = document.createElement(\"span\");\r\n msg.appendChild(document.createTextNode(message));\r\n msg.appendChild(document.createElement(\"br\"));\r\n\r\n // Append the new message to the chat\r\n var chatPane = document.getElementById(\"chatPane\");\r\n chatPane.appendChild(msg);\r\n \r\n // Trim the chat to 500 messages\r\n if (chatPane.childNodes.length > 500) {\r\n chatPane.removeChild(chatPane.firstChild);\r\n }\r\n chatPane.scrollTop = chatPane.scrollHeight;\r\n */\r\n $(\".chatPane\").html(message);\r\n}", "function chatLayout() {\n container.find('.panel').each(function (index, value) {\n $(this).attr('id', 'chat-000' + parseInt(index + 1));\n });\n }", "function resizeChatConversation() {\n // FIXME: this function can all be done with CSS. If Chat is ever rewritten,\n // do not copy over this logic.\n const msgareaHeight = $('#usermsg').outerHeight();\n const chatspace = $(`#${CHAT_CONTAINER_ID}`);\n const width = chatspace.width();\n const chat = $('#chatconversation');\n const smileys = $('#smileysarea'); // eslint-disable-line no-shadow\n\n smileys.height(msgareaHeight);\n $('#smileys').css('bottom', (msgareaHeight - 26) / 2);\n $('#smileysContainer').css('bottom', msgareaHeight);\n chat.width(width - 10);\n\n const maybeAMagicNumberForPaddingAndMargin = 100;\n const offset = maybeAMagicNumberForPaddingAndMargin\n + msgareaHeight + getToolboxHeight();\n\n chat.height(window.innerHeight - offset);\n}", "function updateChatsPanel() {\r\n // write chats to left side\r\n if (myFile.identified) {\r\n let adjective = '';\r\n let helper = '';\r\n leftSide.innerHTML = '';\r\n myFile.allChats.forEach( chat => {\r\n chat.hasAgent ? adjective = 'is being helped by' : adjective = 'needs agent!';\r\n console.log('chat in case: ', chat);\r\n if (chat.agent !== null) { helper = chat.agent } else { helper = ''; };\r\n leftSide.innerHTML += `<div class= \"chatsAtLeft ${chat.borders}\" id= \"${chat.chatId}\">\r\n ${chat.name} ${adjective} ${helper}</div>`;\r\n });\r\n }\r\n // event listener for chats at left\r\n const elements = document.getElementsByClassName('chatsAtLeft');\r\n for (var i = 0; i < elements.length; i++) {\r\n elements[i].addEventListener('click', clickedChat, false);\r\n }\r\n}", "function insertChat2(who, text, time){\n if (time === undefined){\n time = 0;\n }\n var control = \"\";\n var date = time;\n \n if (who == userName){\n control = '<li style=\"padding-top: 15px;margin-left: 5em;width:75%;\">' +\n '<div class=\"msj-rta macro\" style=\"background-color: #BFE9F9;\">' +\n '<div class=\"text text-r\">' +\n '<p style=\"color: #444950;word-break: break-all;\">'+text+'</p>' +\n '<p><small style=\"color: #444950;\">'+date+'</small></p>' +\n '</div></div></li>';\n }else{\n control = '<li style=\"width:75%\">' +\n '<h4 style=\"margin-bottom: -3px;margin-left: 10%;font-size: 12px;\">'+who+'</h4>'+\n '<div class=\"avatar\" style=\"padding:5px 0px 0px 10px !important\"><img class=\"img-circle\" style=\"width:90%;\" src=\"'+me.avatar+'\" /></div>'+\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p style=\"color: #444950;word-break: break-all;\">'+text+'</p>' +\n '<p><small style=\"color: #444950;\">'+date+'</small></p>' +\n '</div></div>' +\n '</li>';\n }\n setTimeout(\n function(){ \n $(\".frame2\").children('ul').append(control).scrollTop($(\".frame2\").children('ul').prop('scrollHeight'));\n }, time);\n \n }", "function openChat(set_focus) {\n isChatOpen = true;\n if (isHelpPaneOpen) {\n closeHelpPane();\n }\n $.ajax({\n url: '/players/player' + player_id,\n success: function (data) {\n setChatView(data);\n markAsSeen('player' + player_id);\n if(set_focus) { \n scrollToBottom('chat-msgs');\n $('#new_msg_text').focus();\n }\n },\n error: function (xhr, ajaxOptions, thrownError) {\n }\n });\n}", "function make_chat_dialog_box(to_user_id, to_user_name)\n{\n var modal_content = '<div id=\"user_dialog_'+to_user_id+'\" class=\"user_dialog\" title=\"You have a chat with '+to_user_name+'\">';\n modal_content += '<div style=\"height:400px; border:1px solid #ccc; overflow-y: scroll; margin-bottom:24px; padding:16px;\" class=\"chat_history\" data-touserid=\"'+to_user_id+'\" id=\"chat_history_'+to_user_id+'\">';\n modal_content += '</div>';\n modal_content += '<div class=\"form-group\">';\n modal_content += '<textarea name=\"chat_message_'+to_user_id+'\" id=\"chat_message_'+to_user_id+'\" class=\"form-control\"></textarea>';\n modal_content += '</div><div class=\"form-group\" align=\"right\">';\n modal_content+= '<button type=\"button\" name=\"send_chat\" id=\"send_chat\" class=\"btn btn-info send_chat\">Send</button></div></div>';\n $('#user_model_details').html(modal_content);\n}", "async _indentToLine() {\n const editor = vscode.window.activeTextEditor;\n\n if (editor && editor.selection.active.line) {\n const pos = editor.selection.active;\n\n await this._addUnderscore(editor.document, pos, '');\n\n // Update current line and preceeding lines\n const {lines, firstRow} = MagikUtils.indentRegion();\n if (lines) {\n await this._indentMagikLines(lines, firstRow, pos.line, true);\n }\n }\n }", "indent(uid) {\n const indents = this.suiteIndents[uid];\n return indents === 0 ? '' : Array(indents).join(' ');\n }", "function setup_messages() {\n $('<span class=\"message\" id=\"start\">Spacebar to play.</span>')\n .appendTo('#grid');\n $('#start').hide();\n $('<span class=\"message\" id=\"continue\">Spacebar to continue.</span>')\n .appendTo('#grid');\n $('#continue').hide();\n $('<span class=\"message\" id=\"end\">Spacebar to restart.</span>')\n .appendTo('#grid');\n $('#end').hide();\n}", "splitMessage(){\n //hide element with style\n //takes the text inserted into the message and seperates it into letters\n let root = document.documentElement;\n let bubble = document.querySelector(\".message\");\n let bubbleUp = bubble.innerHTML;\n let bubbleSplit = bubbleUp.split(\"\")\n let bassage = []\n //take each letter and 'thurns it into' a tspan object---targetable with css\n bubbleSplit.forEach((letter)=>{bassage.push(`<tspan class='bubbleLetter'>${letter}</tspan>`)})\n //this dictates the spaces between off and on letters \n setTimeout(()=>{\n //inserts our new tspaned letters\n // this.bubbleMsg.\n this.bubbleMsg.innerHTML= bassage.join(\"\");\n }, 200)\n }", "editorEnter (cm) {\n const cur = cm.getCursor()\n\n const { lineString, lineTokens } = this._getTokenLine(cm, cur)\n const [, indent, firstArrayItem] = lineString.match(/^(\\s*)(-\\s)?(.*?)?$/) || []\n let extraIntent = ''\n if (firstArrayItem) {\n extraIntent = `${repeat(' ', this.arrayBulletIndent)}`\n } else if (this._isTokenLineStartingObject(lineTokens)) {\n extraIntent = `${repeat(' ', this.indentUnit)}`\n }\n cm.replaceSelection(`\\n${indent}${extraIntent}`)\n }", "function insertChat1(who, text, time){\n if (time === undefined){\n time = 0;\n }\n var control = \"\";\n var date = time;\n \n if (who == userName){\n control = '<li style=\"padding-top: 15px;margin-left: 5em;width:75%;\">' +\n '<div class=\"msj-rta macro\" style=\"background-color: #BFE9F9;\">' +\n '<div class=\"text text-r\">' +\n '<p style=\"color: #444950;line-height: 17px;word-break: break-all;\">'+text+'</p>' +\n '<p><small style=\"color: #444950;\">'+date+'</small></p>' +\n '</div></div></li>';\n }else{\n control = '<li style=\"width:75%\">' +\n '<h4 style=\"margin-bottom: -3px;margin-left: 10%;font-size: 12px;\">'+who+'</h4>'+\n '<div class=\"avatar\" style=\"padding:5px 0px 0px 10px;width: 20%;margin-left: -12%;margin-top: 5%; !important\"><img class=\"img-circle\" style=\"width:90%;\" src=\"'+me.avatar+'\" /></div>'+\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p style=\"color: #444950;line-height: 17px;word-break: break-all;\">'+text+'</p>' +\n '<p><small style=\"color: #444950;\">'+date+'</small></p>' +\n '</div></div>' +\n '</li>';\n }\n setTimeout(\n function(){ \n $(\".chat\"+std).children('ul').append(control).scrollTop($(\".chat\"+std).children('ul').prop('scrollHeight'));\n }, time);\n \n }", "function enterChat(source) {\r\n var message = $('.message').val();\r\n if (/\\S/.test(message)) {\r\n var html = '<div class=\"chat-content\">' + '<p>' + message + '</p>' + '</div>';\r\n $('.chat:last-child .chat-body').append(html);\r\n $('.message').val('');\r\n $('.user-chats').scrollTop($('.user-chats > .chats').height());\r\n }\r\n}", "function insertChat(who, text, time){\n if (time === undefined){\n time = 0;\n }\n var control = \"\";\n var date = formatAMPM(new Date());\n\n if (who == \"me\"){\n control = '<li style=\"width:100%\">' +\n '<div class=\"msj macro\">' +\n '<div class=\"avatar\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+ me.avatar +'\" /></div>' +\n '<div class=\"text text-l\">' +\n '<p>'+ text +'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' +\n '</div>' +\n '</li>';\n }else{\n control = '<li style=\"width:100%;\">' +\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p>'+text+'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' +\n '<div class=\"avatar\" style=\"padding:0px 0px 0px 10px !important\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+you.avatar+'\" /></div>' +\n '</li>';\n }\n setTimeout(\n function(){\n $(\"ul\").append(control).scrollTop($(\"ul\").prop('scrollHeight'));\n }, time);\n\n}", "function addMessageToDisplay(who,message)\r\n {\r\n try\r\n {\r\n \r\n var divChatDisplay = document.getElementById('divChatDisplay');\r\n divChatDisplay.innerHTML = divChatDisplay.innerHTML + '<strong>'+who+':</strong>' + message + '<br/><div style=\"height:4px\"></div>';\r\n \r\n //if( who != 'me' )\r\n //{\r\n // toggleTitleBarColor(true);\r\n //}\r\n \r\n //increase the height up to a 170px\r\n //if(divChatDisplay.clientHeight < 170)\r\n //{\r\n // divChatDisplay.style.height = (divChatDisplay.clientHeight + 20) +'px';\r\n // divChatDisplayHeight = divChatDisplay.style.height;\r\n //}\r\n \r\n //increase the parent height up to a 300px\r\n // if(document.documentElement.clientHeight < 300)\r\n // {\r\n // var chatParentIframe = parent.document.getElementById('chatParentIframe' + getOtherWebID());\r\n \r\n // chatParentIframe.style.height = (document.documentElement.clientHeight + 20)+'px'; \r\n \r\n // divChatDisplayParentHeight = chatParentIframe.style.height;\r\n // } \r\n \r\n //-var chatParentIframe = parent.document.getElementById('chatParentIframe' + getOtherWebID()); \r\n //-var origH = extractVal(chatParentIframe.style.height);\r\n \r\n //increase the parent height up to a 300px\r\n //if(origH < 290)\r\n //{\r\n //var chatParentDiv = parent.document.getElementById('chatParentDiv');\r\n \r\n //chatParentDiv.style.height = (document.documentElement.clientHeight + 20) + 'px'; \r\n //chatParentIframe.style.height = (document.documentElement.clientHeight + 20)+'px';\r\n //-chatParentIframe.style.height = (origH + 20) + 'px';\r\n \r\n //-var origT = extractVal(chatParentIframe.style.top); \r\n //-chatParentIframe.style.top = (origT - 20) + 'px';\r\n \r\n //divChatDisplayParentHeight = chatParentIframe.style.height; \r\n //if(parent.adjustChatDivTop)\r\n //{\r\n // parent.adjustChatDivTop();\r\n //}\r\n //}\r\n \r\n \r\n // scroll the div to the bottom to display the newest message \r\n divChatDisplay.scrollTop = divChatDisplay.scrollHeight; \r\n setTimeout(\"document.getElementById('divChatDisplay').scrollTop = document.getElementById('divChatDisplay').scrollHeight\",0);\r\n \r\n hideLastMessageDiv();\r\n \r\n lastMessageDt = new Date();\r\n showLastMessageDate();\r\n \r\n return true;\r\n }\r\n catch(ex){return false;}\r\n }", "function insertChat(who, text, time = 0){\r\n var control = \"\";\r\n var date = formatAMPM(new Date());\r\n \r\n if (who == \"me\"){\r\n \r\n control = '<li style=\"width:100%\">' +\r\n '<div class=\"msj macro\">' +\r\n '<div class=\"text text-l\">' +\r\n '<p>'+ text +'</p>' +\r\n '<p><small>'+date+'</small></p>' +\r\n '</div>' +\r\n '</div>' +\r\n '</li>'; \r\n }else{\r\n control = '<li style=\"width:100%;\">' +\r\n '<div class=\"msj-rta macro\">' +\r\n '<div class=\"text text-r\">' +\r\n '<p>'+text+'</p>' +\r\n '<p><small>'+date+'</small></p>' +\r\n '</div>' +\r\n '<div class=\"avatar\" style=\"padding:0px 0px 0px 10px !important\"></div>' + \r\n '</li>';\r\n }\r\n setTimeout(\r\n function(){ \r\n $(\"ul\").append(control);\r\n\r\n }, time);\r\n \r\n}", "function insertChat(who, text, val) {\n var control = \"\";\n var date = formatAMPM(new Date());\n if (who == \"me\") {\n control =\n '<div class=\"chatmsgsender hider pull-right\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"' +\n date +\n '\" style=\"opacity: 1;\"><p class=\"msgtext\">' +\n text +\n \"</p></div>\" +\n '<div class=\"seen hider hider pull-right \" id=\"seen\" style=\"display:none\"><p class=\"msgtext\">seen</p></div>';\n } else {\n control =\n '<div class=\"chatmsgreciever hider pull-left\" data-toggle=\"tooltip\" data-placement=\"bottom\" title=\"' +\n date +\n '\" style=\"opacity: 1;\"><p class=\"msgtext\">' +\n text +\n \"</p></div>\";\n }\n $(\"#chatareaid\" + val).append(control);\n $(\"#chatareaid\" + val).animate(\n {\n scrollTop: $(\"#chatareaid\" + val).prop(\"scrollHeight\")\n },\n 0\n );\n}", "function message(contents) {\n\tvar msg = '<div class=\"message\"><i class=\"icon icon-chat-admin\"></i><span class=\"from admin \">[AutoWoot] </span><span class=\"text\">&nbsp;' + contents + '</span></div>';\n\t$('#chat-messages').append(msg);\n}", "function insertChat(who, text, time){\n if (time === undefined){\n time = 0;\n }\n timePassed += Math.sqrt(text.length) * 400 + time;\n var control = \"\";\n var date = formatAMPM(new Date());\n\n if (who == \"me\"){\n control = '<li style=\"width:100%\">' +\n '<div class=\"msj macro\">' +\n '<div class=\"avatar\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+ me.avatar +'\" /></div>' +\n '<div class=\"text text-l\">' +\n '<p>'+ text +'</p>' +\n '<p><small>'+\"Fermatta\"+'</small></p>' +\n '</div>' +\n '</div>' +\n '</li>';\n }else{\n control = '<li style=\"width:100%;\">' +\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p>'+text+'</p>' +\n '<p><small>'+\"Tempo\"+'</small></p>' +\n '</div>' +\n '<div class=\"avatar\" style=\"padding:0px 0px 0px 10px !important\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+you.avatar+'\" /></div>' +\n '</li>';\n }\n setTimeout(\n function(){\n $(\"ul\").append(control).scrollTop($(\"ul\").prop('scrollHeight'));\n }, timePassed);\n\n}", "function insertChat(who, text, time){\n if (time === undefined){\n time = 0;\n }\n timePassed += Math.sqrt(text.length) * 400 + time;\n var control = \"\";\n var date = formatAMPM(new Date());\n\n if (who == \"me\"){\n control = '<li style=\"width:100%\">' +\n '<div class=\"msj macro\">' +\n '<div class=\"avatar\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+ me.avatar +'\" /></div>' +\n '<div class=\"text text-l\">' +\n '<p>'+ text +'</p>' +\n '<p><small>'+\"Fermatta\"+'</small></p>' +\n '</div>' +\n '</div>' +\n '</li>';\n }else{\n control = '<li style=\"width:100%;\">' +\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p>'+text+'</p>' +\n '<p><small>'+\"Tempo\"+'</small></p>' +\n '</div>' +\n '<div class=\"avatar\" style=\"padding:0px 0px 0px 10px !important\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+you.avatar+'\" /></div>' +\n '</li>';\n }\n setTimeout(\n function(){\n $(\"ul\").append(control).scrollTop($(\"ul\").prop('scrollHeight'));\n }, timePassed);\n\n}", "function startNewChat(){\n\tdocument.getElementById(\"logbox\").innerHTML = \"\";\n\tdocument.getElementById(\"logbox\").innerHTML\n\t= \"<div id='connecting' class='logitem'><div class='statuslog'><code>Menunggu server...</code></div></div><div id='looking' class='logitem'><div class='statuslog'><code>Menunggu seseorang dulu...</code></div></div><div id='sayHi' class='logitem'><div class='statuslog'><code>Temen kamu udah ada yang masuk..</code></div></div><div id='chatDisconnected' class='logitem'><div class='statuslog'><code>Obrolan di tutup.</code></div></div>\";\n\tstartChat();\n}", "function sendChatBtn() {\n\t\t\t\tsendLine();\n\t\t\t\tsetVisitorTyping(false);\n\t\t\t}", "function insertChat(who, text, time){\n if (time === undefined){\n time = 0;\n }\n var control = \"\";\n var date = time;\n \n if (who == \"me\"){\n control = '<li style=\"width:100%\">' +\n '<div class=\"msj macro\">' +\n '<div class=\"avatar\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+ me.avatar +'\" /></div>' +\n '<div class=\"text text-l\">' +\n '<p>'+ text +'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' +\n '</div>' +\n '</li>'; \n }else{\n control = '<li style=\"width:100%;\">' +\n '<div class=\"msj-rta macro\">' +\n '<div class=\"text text-r\">' +\n '<p>'+text+'</p>' +\n '<p><small>'+date+'</small></p>' +\n '</div>' +\n '<div class=\"avatar\" style=\"padding:0px 0px 0px 10px !important\"><img class=\"img-circle\" style=\"width:100%;\" src=\"'+you.avatar+'\" /></div>' + \n '</li>';\n }\n setTimeout(\n function(){ \n $(\"body #chat\"+tkid+\" .frame > ul\").append(control).scrollTop($(\"body #chat\"+tkid+\" .frame > ul\").prop('scrollHeight'));\n }, time);\n \n }", "function showChatMessageModal(chatMessageModalModalSelctor) {\n chatMessageModalModalSelctor.style.display = 'block';\n $scope.chatMessageStatus.save = false;\n $scope.chatMessageStatus.delete = false;\n $scope.chatMessageStatus.duplicate = false;\n }", "function displayMessage(message) {\n\tvar oScroll = document.getElementById(\"chatWindow\");\n\tvar scrollDown = (oScroll.scrollHeight - oScroll.scrollTop <= oScroll.offsetHeight );\n\toScroll.innerHTML += message;\n\toScroll.scrollTop = scrollDown ? oScroll.scrollHeight : oScroll.scrollTop;\n}", "function AnonMessage() {\n\tif(wgUserGroups == null) {\n\t\t$('.anonmessage').css('display', 'inline');\n\t}\n}", "function printConversation(conver) {\n const right = document.getElementById(\"right\");\n const sameConversationOpen = right.num === conver.num && right.querySelector(\"section.messages\");\n if (!sameConversationOpen) {\n // if it's not the same conversation we do not need to be careful to not override the footer,\n // cllean it all\n right.innerHTML = \"\";\n }\n const header = right.querySelector(\"header\") || document.createElement('header');\n header.innerHTML = \"\";\n // the header holds all the info about the conversation and the buttons to administrate it\n const conversation = data.conversations[conver.num];\n const participants = conversationParticipants(conversation);\n const name = conversationName(conversation);\n const img = conversationImg(conversation, \"current-conversation-img\");\n header.appendChild(img);\n header.innerHTML +=\n `<div class=\"current-conversation-info\">\n <div class=\"current-conversation-name\">${name}</div>\n <div class=\"current-conversation-participants\">${participants}</div>\n </div>`;\n // if the user is the creator of the conversation AND the conversation is not private\n if (conversation.creator == data.user.id && conversation.private!=1) {\n // we show the options to add or remove participants or leave teh conversation\n header.innerHTML += `\n <div class=\"buttons\">\n <input type=\"button\" class=\"add\" value=\"Add Participant\" onclick=\"addSingleParticipant();\">\n <input type=\"button\" class=\"remove\" value=\"Remove Participant\" onclick=\"removeParticipant();\">\n <input type=\"button\" class=\"exit\" value=\"Leave Conversation\" onclick=\"leaveConversation();\">\n </div>`;\n } else {\n // if the conversation is private there's no possibility of adding or removing users\n // and if you are not the creator you don't have any power either, just the possibility to leave\n header.innerHTML += `\n <div class=\"buttons\">\n <input type=\"button\" class=\"exit\" value=\"Leave Conversation\" onclick=\"leaveConversation();\">\n </div>`;\n }\n if (!sameConversationOpen) {\n right.appendChild(header);\n }\n // here we repaint the message section\n const section = document.createElement('section') || right.querySelector(\"section\");\n section.innerHTML = \"\";\n section.classList.add(\"messages\");\n // ensure only one listener is added to mark the conversation as read once the user reach the bottom of it\n section.onscroll = function() {\n const atTheBottom = this.scrollHeight - this.scrollTop - this.clientHeight < 1;\n if (atTheBottom) {\n // mark as read conversation here\n markConversationAsRead(right.num);\n }\n };\n for (const msg of Object.values(data.conversations[conver.num].messages)) {\n section.appendChild(msgDiv(msg));\n }\n if (!sameConversationOpen) {\n right.appendChild(section);\n }\n if (!sameConversationOpen) {\n // if it's a different conversation we repaint the footer too\n // this has the input text, the button to attach images or files, and the send button\n const footer = document.createElement('footer');\n footer.innerHTML += \n `<form autocomplete=\"off\" id=\"send-message\">\n <input class=\"pill\" type=\"text\" name=\"inputmessage\" placeholder=\"Write here your message…\">\n <label for=\"attachment\">\n <svg id=\"clip\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" width=\"24\" height=\"24\">\n <path fill=\"#FFF\" fill-opacity=\"1\" d=\"M1.816 15.556v.002c0 1.502.584 2.912 1.646 3.972s2.472 1.647 3.974 1.647a5.58 5.58 0 0 0 3.972-1.645l9.547-9.548c.769-.768 1.147-1.767 1.058-2.817-.079-.968-.548-1.927-1.319-2.698-1.594-1.592-4.068-1.711-5.517-.262l-7.916 7.915c-.881.881-.792 2.25.214 3.261.959.958 2.423 1.053 3.263.215l5.511-5.512c.28-.28.267-.722.053-.936l-.244-.244c-.191-.191-.567-.349-.957.04l-5.506 5.506c-.18.18-.635.127-.976-.214-.098-.097-.576-.613-.213-.973l7.915-7.917c.818-.817 2.267-.699 3.23.262.5.501.802 1.1.849 1.685.051.573-.156 1.111-.589 1.543l-9.547 9.549a3.97 3.97 0 0 1-2.829 1.171 3.975 3.975 0 0 1-2.83-1.173 3.973 3.973 0 0 1-1.172-2.828c0-1.071.415-2.076 1.172-2.83l7.209-7.211c.157-.157.264-.579.028-.814L11.5 4.36a.572.572 0 0 0-.834.018l-7.205 7.207a5.577 5.577 0 0 0-1.645 3.971z\"></path>\n </svg>\n </label>\n <input type=\"file\" name=\"attachment\" id=\"attachment\">\n <button type=\"submit\">\n <svg id=\"plane\" xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 -1 28 23\" width=\"24\" height=\"21\">\n <path fill=\"#FFF\" d=\"M5.101 21.757L27.8 12.028 5.101 2.3l.011 7.912 13.623 1.816-13.623 1.817-.011 7.912z\"></path>\n </svg>\n </button>\n </form>`;\n right.appendChild(footer);\n document.getElementById(\"attachment\").addEventListener('change', somethingAttached);\n document.getElementById(\"send-message\").addEventListener('submit', sendMessage);\n }\n section.scrollTop = section.scrollHeight;\n // we ensure the right side has a propriety marked that shows that the current conversation is _this_ one\n right.num = conver.num;\n // and mark the conversation as read since we just opened it\n markConversationAsRead(conver.num);\n}", "function addChatMessage(r) {\n\tvar chat = document.getElementById('chat_box');\n\tchat.innerHTML += formatChatMessage(r);\n\tchat.scrollTop = chat.scrollHeight;\n}", "function ChatUser(strMessage) {\n debugger;\n var MsgUserSpan = document.createElement('div');\n MsgUserSpan.className = \"chat_msg_item chat_msg_item_user\";\n var MsgUserDiv = document.createElement('div');\n MsgUserDiv.className = \"chat_avatar\";\n var MsgUserContentDiv = document.createElement('div');\n MsgUserContentDiv.className = \"chat_msg_content_user\";\n var MsgUserImg = document.createElement(\"img\");\n MsgUserImg.src = GetImageURL(ImageURLS.UserIcon); // \"images/icon-auto-reply.png\"\n MsgUserDiv.appendChild(MsgUserImg);\n MsgUserSpan.appendChild(MsgUserContentDiv);\n MsgUserSpan.appendChild(MsgUserDiv);\n MsgUserContentDiv.innerHTML = strMessage;\n// MsgUserSpan.innerHTML = strMessage;\n document.getElementById(\"chat_converse\").appendChild(MsgUserSpan);\n\n //var MsgUserStatusSpan = document.createElement('span');\n //MsgUserStatusSpan.className = \"chat_msg_item status\";\n //MsgUserStatusSpan.innerHTML = GetCurrentTime();\n //document.getElementById(\"chat_converse\").appendChild(MsgUserStatusSpan);\n //alert(document.getElementById(\"chat_converse\").innerHTML);\n document.getElementById(\"chat_converse\").scrollTop = document.getElementById(\"chat_converse\").scrollHeight;\n}", "function display_msg(data){\n if(!data.v) {\n var from = \"\";\n if(data.who != \"\") {\n from = data.who + \": \";\n\n }\n $(\"#conversation\").append(\"<div class='msg' style='color:\"+data.c+\"'>\"+ from + data.m+\"</div>\");\n } else if(data.v) {\n $(\"#conversation\").append(\"<span class='msg' style='color:\"+data.c+\"'>\"+data.who + \": \" + \"</span>\");\n var message = data.m;\n var messageArray = message.split(\" \");\n var delayPerWord = 60;\n var delayForNewLine = (messageArray.length+2) * delayPerWord;\n\n //to get color of emotion\n var emotion = data.emotion;\n var color = \"#FFFFFF\";\n //var color = $.xcolor.gradientlevel('#fc0', '#f00', 23, 100);\n //console.log(\"color: \" + color);\n if(emotion == \":)\" || emotion == \":-)\") {\n color = \"#F2EF3D\"; //happy color\n } else if(emotion == \"lol\" || emotion == \":D\" || emotion == \":-D\") {\n color = \"#F09E07\"; //laughter color\n } else if(emotion == \":(\" || emotion == \":-(\" || emotion == \":'-(\") {\n color = \"#2B619E\"; //sad color\n } else if(emotion == \":o\" || emotion == \"o_o\" || emotion == \":-o\") {\n color = \"#F06237\"; //surprise color\n } else if(emotion == \";)\" || emotion == \";-)\") {\n color = \"#A125E8\"; //wink color\n } else if(emotion == \"<3\") {\n color = \"#F748AB\"; //love color\n } else if(emotion == \":/\" || emotion == \":-/\" || emotion == \"=/\") {\n color = \"#8C815E\"; //skeptical color\n }\n $(\"#topBox\").css(\"background-color\", color);\n $(\"#bottomBox\").css(\"background-color\", color);\n //var color = \"#FFFFFF\";\n\n // to get text to appear word by word, foreshadowing video\n var whereToAppend = $(\"#conversation\");\n var wordColor = data.c;\n var steps = messageArray.length;\n var rainbow = new Rainbow();\n rainbow.setNumberRange(1, steps);\n rainbow.setSpectrum(wordColor, color);\n var gradientColors = [];\n for (var i = 0; i < steps; i++) {\n var hexColor = rainbow.colourAt(i);\n console.log(\"at i=\" + i + \", color=\" + hexColor);\n gradientColors.push('#' + hexColor);\n }\n var step = 0;\n var addTextByDelay = function(messageArray, whereToAppend, delay, j) {\n if(messageArray.length > 0) {\n console.log(\"color should be \" + gradientColors[j]);\n whereToAppend.append(\"<span style='color:\"+gradientColors[j]+\"'>\"+messageArray[0] + \" </span>\");\n setTimeout(function() {\n addTextByDelay(messageArray.slice(1), whereToAppend, delay, j+1);\n }, delay);\n }\n }\n addTextByDelay(messageArray, whereToAppend, delayPerWord, step);\n setTimeout(function() {\n $(\"#conversation\").append(\"<br/>\");\n }, delayForNewLine);\n\n\n // for video element\n var video1 = document.createElement(\"video\");\n \n video1.autoplay = true;\n video1.controls = false; // optional\n video1.loop = true;\n video1.width = 1000;\n\n var source = document.createElement(\"source\");\n source.src = URL.createObjectURL(base64_to_blob(data.v));\n source.type = \"video/webm\";\n\n video1.appendChild(source);\n if(username != data.who) {\n\n setTimeout(function() {\n document.getElementById(\"recorded_video\").appendChild(video1);\n $(\"#bottomBox\").show();\n $(\"#topBox\").show();\n $(\"#word\").show();\n $(\"#word\").text(emotion);\n /*\n emotionText = document.createTextNode(emotion);\n console.log(\"emoticon: \" + emotionText);\n var emotionPar = document.createElement('p');\n emotionPar.appendChild(emotionText);\n document.getElementById(\"word\").appendChild(emotionPar);\n */\n //$(\"#recorded_video\").animate({opacity, 'hide'}, 2000);\n /*\n setTimeout(function() {\n $(\"#recorded_video\").fadeOut();\n }, 2000);\n */\n //to make the video disappear\n setTimeout(function() {\n $(\"#recorded_video\").empty();\n $(\"#word\").hide();\n $(\"#bottomBox\").fadeOut('slow');\n $(\"#topBox\").hide();\n }, 2000);\n }, delayForNewLine*2);\n } else {\n setTimeout(function() {\n $(\"#video_sent\").fadeIn();\n setTimeout(function() {\n $(\"#video_sent\").fadeOut();\n }, 1000);\n }, delayForNewLine*2);\n }\n\n // for gif instead, use this code below and change mediaRecorder.mimeType in onMediaSuccess below\n // var video = document.createElement(\"img\");\n // video.src = URL.createObjectURL(base64_to_blob(data.v));\n \n //this line was from starter code to add video into conversation\n //document.getElementById(\"conversation\").appendChild(video1);\n }\n }", "function sendUserMessage() {\n var node = document.createElement(\"P\"); \n var textnode = document.createTextNode(message); \n node.appendChild(textnode);\n node.className = \"userBubble\"; \n document.getElementById(\"output\").appendChild(node); \n document.getElementById(\"chatbox\").scrollTop = document.getElementById(\"chatbox\").scrollHeight;\n window.scrollTo(0,document.body.scrollHeight);\n}", "function darkChat() {\n\tchatWindowChange = document.getElementById(\"chatWindow\");\n\tchatWindow.className = \"darkChat\";\n}", "function setIndentation(editor, indentation) {\n var command = indentation == 0 /* Increase */ ? \"indent\" /* Indent */ : \"outdent\" /* Outdent */;\n editor.addUndoSnapshot(function () {\n editor.focus();\n var listNode = editor.getElementAtCursor('OL,UL');\n var newNode;\n if (listNode) {\n // There is already list node, setIndentation() will increase/decrease the list level,\n // so we need to process the list when change indentation\n newNode = processList_1.default(editor, command);\n }\n else {\n // No existing list node, browser will create <Blockquote> node for indentation.\n // We need to set top and bottom margin to 0 to avoid unnecessary spaces\n editor.getDocument().execCommand(command, false, null);\n editor.queryElements('BLOCKQUOTE', 1 /* OnSelection */, function (node) {\n newNode = newNode || node;\n node.style.marginTop = '0px';\n node.style.marginBottom = '0px';\n });\n }\n return newNode;\n }, \"Format\" /* Format */);\n}", "function showChat(pathFotoProfilo, nomeUtente){\r\n\r\n\t//Div che contiene la chat (inizialmente non visibile)\r\n\tdocument.getElementById(\"divChatBackground\").style.display = \"block\";\r\n\r\n\t//Settaggio dell'immagine profilo\r\n\tif(pathFotoProfilo != \"default\"){ //Se l'immagine è quella di default, l'url è già nel CSS\r\n\t\tvar pathBase = \"../upload/\";\r\n\t\tvar pathFinale = pathBase + pathFotoProfilo;\r\n\t\tdocument.getElementById(\"divImgProfiloChat\").style.backgroundImage = \"url('\" + pathFinale + \"')\";\r\n\t}\r\n\r\n\t//Settaggio del nome dell'utente con cui stiamo parlando\r\n\tvar titoloNomeUtente = document.getElementById(\"chatNomeUtente\")\r\n\tif(titoloNomeUtente == null){\r\n\t\ttitoloNomeUtente = document.createElement(\"h5\");\r\n\t\ttitoloNomeUtente.id = \"chatNomeUtente\";\r\n\t\tdocument.getElementById(\"divChatUp\").appendChild(titoloNomeUtente);\r\n\t}\r\n\ttitoloNomeUtente.textContent = nomeUtente;\r\n\t\r\n\r\n\t//Richiamiamo periodicamente la funzione che controlla i nuovi messaggi in arrivo\r\n\tintervalloChat = setInterval(checkNewMessage, 1000);\r\n}", "function isInterativeChat(){\n\t\t\t\treturn lpInteractiveChat ? true: false;\n\t\t\t}", "function printMsg(msgOwner, msg) {\n var msgElement = $('#messages');\n msgElement.append('<div class=\"' + msgOwner + '\">' + msg + '</div>');\n msgElement.scrollTop(msgElement.prop(\"scrollHeight\"));\n}", "function printMessage(fromUser, message) {\n // if (message.search(\"@anon\")>=0)\n // {\n // fromUser=\"hidden\";\n // }\n var $user = $('<span class=\"username\">').text(fromUser + ':');\n if (fromUser === username) {\n $user.addClass('me');\n }\n var $message = $('<span class=\"message\">').text(message);\n var $container = $('<div class=\"message-container\">');\n $container.append($user).append($message);\n\n $chatWindow.append($container);\n //console.log(message)\n\n\n\n $chatWindow.scrollTop($chatWindow[0].scrollHeight);\n //wait(10000);\n //$chatWindow.append(\"yo\");\n }", "function showChat(){\n showListChat();\n}", "function showChat(){\n showListChat();\n}", "function openChat(event)\n{\n if (!event) {\n return false;\n }\n event.preventDefault();\n var cTarget, cX, cY,\n jqWin = $('#boxes > div#chatInp'),\n url, recipientId, recipient, ename,\n jqMask, winW, winH, wcH, wcW;\n /*\n * Get target. */\n cTarget = event.currentTarget;\n if ($(cTarget).hasClass('feedback')) {\n $('span', jqWin).attr('id', 'feedback').text('Feedback message:');\n }\n else if ($(cTarget).hasClass('typeContent')) {\n url = $(cTarget).attr('url');\n if (url.length > 0)\n {\n window.open(url, '_blank', 'width=800,height=600');\n }\n return false;\n }\n // Click position.\n cX = event.clientX;\n cY = event.clientY;\n // Transition effect.\n jqMask = $('#mask');\n jqMask.fadeIn(500, activateWindow('#chatInp'));\n jqMask.fadeTo('fast', 0.3);\n // Position chat Inp.\n winW = $(window).width();\n winH = $(window).height();\n wcW = jqWin.outerWidth();\n wcH = jqWin.outerHeight();\n if ((cY + wcH) > winH) {\n jqWin.css('top', winH - wcH);\n }\n else {\n jqWin.css('top', cY);\n }\n if ((cX + wcW) > winW) {\n jqWin.css('left', winW - wcW);\n }\n else {\n jqWin.css('left', cX);\n }\n // Transition effect for Chat Input Window.\n jqWin.fadeIn(700);\n // Add class active.\n jqWin.addClass('active');\n // Add focus to input text.\n $('input.chatTo', jqWin).focus();\n return false;\n}", "function renderIndentation(inputObject, inputLine) {\n\n var leadingIndentTag = \"<a class=\\\"mIndentation\\\" data-toggle=\\\"tooltip\\\" data-placement=\\\"top\\\" title=\\\"Line Level\\\">\";\n var trailingTag = \"</a>\";\n var tmpIndentation = \"\";\n\n if (inputObject.lineIndentationArray) {\n if (inputObject.lineIndentationArray.length > 0) {\n for (var i in inputObject.lineIndentationArray) {\n tmpIndentation = tmpIndentation + leadingIndentTag + \".\" + trailingTag + inputObject.lineIndentationArray[i];\n }\n inputLine = inputLine + tmpIndentation;\n }\n }\n return inputLine;\n}", "function scrollChatBox() {\n chatBox.scrollTop(chatBox[0].scrollHeight - chatBox[0].clientHeight);\n}", "function highlight(){\r\n\tmessages.push({command:\"highlight\"});\r\n\tgetCurrentTabAndSendMessages();\r\n}", "function startChatArea(){\n let notification = $(\"#notificationArea\");\n let chatArea = $(\"#chatArea\");\n hideElement(notification);\n showElement(chatArea);\n}", "function addChat(boardId) {\n $('#bord').before('<div class=\"chat-col draggable\" id = \"bord' + boardId + '\" ondragstart = \"drag(event)\" style=\"z-index: '+ colUAZindex++ + '\">'\n + '<div id=\"menu' + boardId + '\" class=\"chat_menu\"><div style=\"float: left;padding-top:5px;\">Group Chat</div>'\n + '<a type=\"button\" style=\"float:right;\" id = \"delete_chat' + boardId + '\"><i class=\"fas fa-times chaticon\" style=\"padding:3px 5px 3px 5px;\"></i></a>'\n + '<a type=\"button\" style=\"float:right;\" id = \"max_chat' + boardId + '\"><i class=\"fas fa-window-restore chaticon\" style=\"padding:0px 5px 0px 5px;\"></i></a>'\n + '<a type=\"button\" style=\"float:right;\" id = \"min_chat' + boardId + '\"><i class=\"fas fa-window-minimize chaticon\" style=\"padding:3px 5px 3px 5px;\"></i></a></div>'\n + '<div style=\"padding: 5px 10px 5px 10px;\">'\n + '<div class=\"col-2\" style=\"padding-top: 20px;padding-bottom: 5px;\">User:</div><div class=\"col-4\" style=\"padding-bottom: 5px;\"><input type=\"text\" id=\"userInput\" /></div>'\n + '<div class=\"col-2\" style=\"padding-bottom: 5px;\">Message:</div><div class=\"col-10\" style=\"padding-bottom: 10px;\"><input type=\"text\" id=\"messageInput\" style=\"width: 100%;\" /></div>'\n + '<div class=\"col-6\" style=\"padding-bottom: 5px;\"><input type=\"button\" id=\"sendButton\" value=\"Send Message\" /></div>'\n + '</div>'\n + '<div class=\"col-12\">'\n + '<hr />'\n + '</div>'\n + '<div>'\n + '<div class=\"col-6\">&nbsp;</div>'\n + '<div class=\"col-6\">'\n + '<ul id=\"messagesList\" class=\"scrollbar bord-scroll bord-track bord-thumb\" style=\"width: 240px; height: 400px; overflow: auto\"></ul>'\n + '</div>'\n + '</div>');\n /*Set column dragable*/\n $('#bord' + boardId).attr('draggable', 'true');\n\n /*Delete selected column. */\n $('a[id ^= \"delete_chat' + boardId + '\"]').on('click', function (event) {\n var column = $(this).parent().parent().attr('id');\n $('#' + column).remove();\n });\n\n $('a[id ^= \"min_chat' + boardId + '\"]').on('click', function (event) {\n var column = $(this).parent().parent().attr('id');\n $('#' + column).css({ \"height\": \"150px\" });\n });\n\n $('a[id ^= \"max_chat' + boardId + '\"]').on('click', function (event) {\n var column = $(this).parent().parent().attr('id');\n $('#' + column).css({ \"height\": \"\" });\n });\n $(function () {\n $(\".chat-col\").draggable({\n handle: $('#menu' + boardId), stop: function dragEnd(ev) {\n data = ev.target.id;\n $('.chat-col').css('border', '1px solid grey');\n }\n });\n/*move the work area to the top as the item is dragged over the other work areas by increasing the z-index*/\n $(\"#bord\" + boardId).droppable({\n over: function (event, ui) {\n $(\"#\" + dragFrom).css(\"z-index\", colUAZindex++);\n }\n });\n });\n\n \"use strict\";\n\n var connection = new signalR.HubConnectionBuilder().withUrl(\"/chatHub\").build();\n\n //Disable send button until connection is established\n\n document.getElementById(\"sendButton\").disabled = true;\n\n connection.on(\"ReceiveMessage\", function (user, message) {\n var msg = message.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n var encodedMsg = user + \" says \" + msg;\n var li = document.createElement(\"li\");\n li.textContent = encodedMsg;\n document.getElementById(\"messagesList\").appendChild(li);\n });\n\n connection.start().then(function () {\n document.getElementById(\"sendButton\").disabled = false;\n }).catch(function (err) {\n return console.error(err.toString());\n });\n\n document.getElementById(\"sendButton\").addEventListener(\"click\", function (event) {\n var user = document.getElementById(\"userInput\").value;\n var message = document.getElementById(\"messageInput\").value;\n connection.invoke(\"SendMessage\", user, message).catch(function (err) {\n return console.error(err.toString());\n });\n event.preventDefault();\n });\n}", "function activate(context) {\n // Create a decorator types that we use to decorate indent levels\n let timeout = null;\n let enabled = true;\n let currentLanguageId = null;\n let activeEditor = vscode.window.activeTextEditor;\n\n let currentIndentDecorationType;\n\n if (activeEditor && checkLanguage()) {\n triggerUpdateDecorations();\n }\n\n vscode.window.onDidChangeTextEditorOptions(function(event) {\n const options = event.options;\n const indentChange = options && (options.insertSpaces !== undefined || options.tabSize !== undefined);\n if (indentChange && checkLanguage()) {\n clearDecorations();\n triggerUpdateDecorations();\n }\n }, null, context.subscriptions);\n\n vscode.window.onDidChangeActiveTextEditor(function(editor) {\n activeEditor = editor;\n if (editor && checkLanguage()) {\n clearDecorations();\n triggerUpdateDecorations();\n }\n }, null, context.subscriptions);\n\n vscode.workspace.onDidChangeTextDocument(function(event) {\n if (activeEditor && event.document === activeEditor.document && checkLanguage()) {\n triggerUpdateDecorations();\n }\n }, null, context.subscriptions);\n\n vscode.commands.registerCommand('stretchySpaces.disable', () => {\n if (enabled) {\n enabled = false;\n clearDecorations();\n }\n });\n\n vscode.commands.registerCommand('stretchySpaces.enable', () => {\n if (!enabled) {\n enabled = true;\n if (activeEditor && checkLanguage()) {\n triggerUpdateDecorations();\n }\n }\n });\n\n function checkLanguage() {\n if (activeEditor) {\n if (currentLanguageId !== activeEditor.document.languageId) {\n const inclang = vscode.workspace.getConfiguration('stretchySpaces').includedLanguages || [];\n const exclang = vscode.workspace.getConfiguration('stretchySpaces').excludedLanguages || [];\n currentLanguageId = activeEditor.document.languageId;\n if (inclang.length !== 0) {\n if (inclang.indexOf(currentLanguageId) === -1) {\n return false;\n }\n }\n if (exclang.length !== 0) {\n if (exclang.indexOf(currentLanguageId) !== -1) {\n return false;\n }\n }\n }\n }\n return true;\n }\n\n function clearDecorations() {\n if (activeEditor && currentIndentDecorationType) {\n activeEditor.setDecorations(currentIndentDecorationType, []);\n currentIndentDecorationType = null;\n }\n }\n\n function triggerUpdateDecorations() {\n if (!enabled) {\n return;\n }\n if (timeout) {\n clearTimeout(timeout);\n }\n const updateDelay = vscode.workspace.getConfiguration('stretchySpaces').updateDelay || 100;\n timeout = setTimeout(updateDecorations, updateDelay);\n }\n\n function updateDecorations() {\n if (!activeEditor || !enabled) {\n return;\n }\n const targetIndentation = vscode.workspace.getConfiguration('stretchySpaces').targetIndentation;\n const indentFactor = targetIndentation / activeEditor.options.tabSize;\n if (!activeEditor.options.insertSpaces || indentFactor === 1) {\n return;\n }\n const decorationRanges = [];\n const regEx = /^ +/gm;\n const text = activeEditor.document.getText();\n\n if (!currentIndentDecorationType) {\n currentIndentDecorationType = vscode.window.createTextEditorDecorationType({\n letterSpacing: 8 * indentFactor - 8 + 'px'\n });\n }\n\n let match;\n\n while (match = regEx.exec(text)) {\n const matchText = match[0];\n const matchLength = matchText.length;\n const startPos = activeEditor.document.positionAt(match.index);\n const endPos = activeEditor.document.positionAt(match.index + matchLength);\n decorationRanges.push({ range: new vscode.Range(startPos, endPos), hoverMessage: null });\n }\n activeEditor.setDecorations(currentIndentDecorationType, decorationRanges);\n }\n}", "function openPersonalChat(\n msginfo // Message Information Object.\n)\n{\n /*\n * Transition effect. */\n var jqMask = $('#mask'),\n jqWin, id, jqO, cY, cX, winW, winH,\n wcW, wcH,\n item;\n /*\n * Set position based on nick id. */\n id = app.str2id(msginfo.nick);\n jqO = $('#meeting > #streams > #scarousel div#' + id);\n\n if (jqO.length === 0 && msginfo.nick === \"overseer\") // from user not found, check if overseer\n {\n item = app.carousel.getItem(1);\n if (!item)\n {\n return;\n }\n jqO = $(item.object);\n }\n jqMask.fadeIn(500, activateWindow('#personalChat'));\n jqMask.fadeTo('fast', 0.3);\n /*\n * Set message. */\n jqWin = $('#boxes > div#personalChat');\n $('p.msg', jqWin).text('').html(decodeURI(msginfo.body));\n cY = jqO.offset().top;\n cX = jqO.offset().left;\n winW = $(window).width();\n winH = $(window).height();\n wcW = jqWin.outerWidth();\n wcH = jqWin.outerHeight();\n if ((cY + wcH) > winH) {\n jqWin.css('top', winH - wcH);\n }\n else {\n jqWin.css('top', cY);\n }\n if ((cX + wcW) > winW) {\n jqWin.css('left', winW - wcW);\n }\n else {\n jqWin.css('left', cX);\n }\n /*\n * Transition effect for Personal Chat Window.*/\n jqWin.fadeIn(700);\n /*\n * Add class active. */\n jqWin.addClass('active');\n return false;\n}", "function trk_chat_st() {\n var chat = $(\".olrk-available\");\n var statediv = chat && chat.find(\"#habla_window_state_div\");\n var cls = statediv && statediv.attr(\"class\");\n var win = chat && chat.find(\"#habla_window_div\");\n var chat_shown = win && win.css(\"display\") != \"none\";\n var chat_open = cls && cls.indexOf(\"olrk-state-expanded\") >= 0;\n var prechat = chat && chat.find(\"#habla_pre_chat_div\");\n var in_prechat = prechat && prechat.css(\"display\") != \"none\";\n var conv = win && win.find(\"#habla_conversation_div\");\n var conv_sent = conv && conv.find(\".habla_conversation_person1\").length > 0;\n var conv_answered = conv && conv.find(\".habla_conversation_person2\").length > 0;\n var conv_ended = conv && conv.find(\".habla_conversation_notification\").length > 0;\n var sane = chat && statediv && win && conv;\n sane = sane ? 1 : 0;\n chat_shown = chat_shown ? 1 : 0;\n chat_open = chat_open ? 1 : 0;\n in_prechat = in_prechat ? 1 : 0;\n conv_sent = conv_sent ? 1 : 0;\n conv_answered = conv_answered ? 1 : 0;\n conv_ended = conv_ended ? 1 : 0;\n if (!sane || !chat_shown || chat_open || conv_sent || conv_answered ||\n\tconv_ended) {\n\treturn [sane, chat_open, in_prechat, conv_sent, conv_answered,\n\t\tconv_ended];\n }\n return [];\n}", "function indentSelection(textArea, direction) {\n\tvar textAreaObj = $(textArea);\n\t\n\tvar oldVal = textAreaObj.val();\n\t\n\tvar selectionStart = textAreaObj[0].selectionStart;\n\tvar selectionEnd = textAreaObj[0].selectionEnd;\n\t\n\tvar toReplace;\n\tvar replacement;\n\t\n\t\n\tvar firstPart = oldVal.substring(0, selectionStart);\n\tvar secondPart = oldVal.substring(selectionStart, selectionEnd);\n\tvar thirdPart = oldVal.substring(selectionEnd);\n\t\n\tif (selectionStart == selectionEnd && direction != 'left') {\n\t\tvar newVal = firstPart + ' ' + thirdPart;\n\t\n\t\tvar newCaretPos = selectionStart + 4;\n\t\n\t\ttextAreaObj.val(newVal);\n\t\ttextAreaObj[0].setSelectionRange(newCaretPos, newCaretPos);\n\t}\n\telse {\n\t\tif (direction == 'left') {\n\t\t\ttoReplace = '\\n ';\n\t\t\treplacement = '\\n';\n\t\t}\n\t\telse {\n\t\t\ttoReplace = '\\n';\n\t\t\treplacement = '\\n ';\n\t\t}\n\t\n\t\tvar firstPartLastIndexOfN = firstPart.lastIndexOf('\\n');\n\n\t\tvar selectionStartDiff = 0;\n\n\t\tif (direction == 'left') {\n\t\t\tif (firstPart.lastIndexOf('\\n ') == firstPart.lastIndexOf('\\n')) {\n\t\t\t\tselectionStartDiff = -4;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tselectionStartDiff = 4;\n\t\t}\n\n\t\tif (firstPartLastIndexOfN != -1) {\n\t\t\tfirstPart = oldVal.substring(0, firstPartLastIndexOfN);\n\t\t\tsecondPart = oldVal.substring(firstPartLastIndexOfN, selectionStart) + secondPart;\n\t\t}\n\n\t\tif (secondPart.endsWith('\\n')) {\n\t\t\tsecondPart = secondPart.substring(0, secondPart.length-1);\n\t\t\tthirdPart = '\\n' + thirdPart;\n\t\t}\n\t\n\t\tsecondPart = secondPart.split(toReplace).join(replacement);\n\t\n\t\tvar newVal = firstPart + secondPart + thirdPart;\n\t\n\t\tvar lengthDiff = newVal.length - oldVal.length;\n\t\n\t\ttextAreaObj.val(newVal);\n\t\ttextAreaObj[0].setSelectionRange(selectionStart + selectionStartDiff, selectionEnd + lengthDiff);\n\t}\n}", "function C012_AfterClass_Jennifer_StartChat() {\n\tif (!ActorIsGagged()) {\n\t\tActorSetPose(\"\");\n\t\tC012_AfterClass_Jennifer_CurrentStage = 500;\n\t\tGameLogAdd(\"ChatDone\");\n\t\tLeaveIcon = \"\";\n\t\tC012_AfterClass_Jennifer_ChatAvail = false;\n\t} else C012_AfterClass_Jennifer_GaggedAnswer();\n}", "function addMessage(name, time, message) {\n if (!CheckWinFocus())\n GetNotification(name, time, message);\n\n var header = name.charAt(0);\n var chatMessage = '';\n if (userName !== name) {\n chatMessage = `<li>\n <div class=\"conversation-list\">\n <div class=\"avatar-xs\">\n <span class=\"avatar-title rounded-circle bg-soft-primary text-primary\">\n ` + header.toUpperCase() + `\n </span>\n </div>\n \n <div class=\"user-chat-content\">\n <div class=\"ctext-wrap\">\n <div class=\"ctext-wrap-content\">\n <p class=\"mb-0\">\n `+ message + `\n </p>\n <p class=\"chat-time mb-0\"><i class=\"ri-time-line align-middle\"></i> <span class=\"align-middle\">`+ time + `</span></p>\n </div>\n \n </div>\n <div class=\"conversation-name\">`+ name + `</div>\n </div>\n </div>\n </li>`;\n }\n else {\n chatMessage = `<li class=\"right\">\n <div class=\"conversation-list\">\n <div class=\"chat-avatar\">\n <span class=\"avatar-title rounded-circle bg-soft-primary text-primary\">\n ` + header.toUpperCase() + `\n </span>\n </div>\n \n <div class=\"user-chat-content\">\n <div class=\"ctext-wrap\">\n <div class=\"ctext-wrap-content\">\n <p class=\"mb-0\">\n `+ message + `\n </p>\n <p class=\"chat-time mb-0\"><i class=\"ri-time-line align-middle\"></i> <span class=\"align-middle\">`+ time + `</span></p>\n </div>\n \n </div>\n <div class=\"conversation-name\">`+ name + `</div>\n </div>\n </div>\n </li>`;\n }\n\n\n\n $(\"#chatHistory\").append(chatMessage);\n\n\n roomHistoryEl.scrollTop = roomHistoryEl.scrollHeight - roomHistoryEl.clientHeight;\n\n}", "function addChatText(by,text){\n\t \tif(text !== \"\"){\n\t \t\tvar ca = document.getElementById('contents'); \n\t\t ca.innerHTML +=\"<li class=\"+ by +\"><div class='messages'><p> \"+ text + \"</p><time datetime='T20:14D11'2009'> \"+timestamp()+ \" </time></div></li>\";\n\t \tca.scrollTop = 50000;\n\t \t} \n \n \t}", "function insertTags(tag, saveSel, inner, tagEquals)\r\n{\r\n\tvar msgBox = document.getElementById(\"messagearea\");\r\n\tif (msgBox && tag)\r\n\t{\r\n\t\tvar tagOpen;\r\n\t\tvar tagClose;\r\n\t\tif (tagEquals)\r\n\t\t{\r\n\t\t\ttagOpen = \"[\" + tag + \"=\" + tagEquals + \"]\";\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\ttagOpen = \"[\" + tag + \"]\";\r\n\t\t}\r\n\t\ttagClose = \"[/\" + tag + \"]\";\r\n\t\t\r\n\t\tvar selStart = msgBox.selectionStart;\r\n\t\tvar selEnd = msgBox.selectionEnd;\r\n\r\n\t\tif (tag === \"*\") { // special case for [*] tags which should to be inside a [list]\r\n\t\t\tif (msgBox.value.indexOf(\"[list]\") === -1 || msgBox.value.indexOf(\"[list]\") > selStart)\r\n\t\t\t{\r\n\t\t\t\ttagOpen = \"[list]\\n\" + tagOpen;\r\n\t\t\t}\r\n\t\t\tif (msgBox.value.indexOf(\"[/list]\") < selEnd)\r\n\t\t\t{\r\n\t\t\t\ttagClose = \"\\n[/list]\";\r\n\t\t\t} else {\r\n\t\t\t\ttagClose = '';\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tmsgBox.focus();\r\n\t\tif (inner)\r\n\t\t{\r\n\t\t\tlet insert = tagOpen + inner + tagClose;\r\n\t\t\tmsgBox.value = msgBox.value.substring(0, selStart) + insert + msgBox.value.substring(selEnd);\r\n\t\t\tif (saveSel)\r\n\t\t\t{\r\n\t\t\t\tmsgBox.setSelectionRange(selStart + tagOpen.length, selStart + tagOpen.length + inner.length);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tmsgBox.setSelectionRange(selStart + insert.length, selStart + insert.length);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tmsgBox.value = msgBox.value.substring(0, selStart) + tagOpen + tagClose + msgBox.value.substring(selEnd);\r\n\t\t\tmsgBox.setSelectionRange(selStart + tagOpen.length, selStart + tagOpen.length);\r\n\t\t}\r\n\t\tdoPreview();\r\n\t}\r\n}", "function openChat(callback) {\n for(var x in grps){\n\t\tcurrentMessages = new Object();\n if(grps[x].name.toLowerCase().replace(/\\W/g, '') == currentChatName.toLowerCase().replace(/\\W/g, '')) {\n \n\t\t\tvar theName = grps[x].name;\n var theId = grps[x].id;\n\n getMessages(theId, function(result) {\n\t\t\t\tmssgs = result.messages;\n msgs = result.messages;\n\t\t\t\tfor(var h in msgs) {\n\t\t\t\t\tcurrentMessages[h] = msgs[h].id;\n\t\t\t\t}\n term.clear();\n term.blue(\"\\n\" + theName + \"\\n\");\n drawLine();\n writeMessages(msgs);\n callback(theId);\n });\n }\n }\n}" ]
[ "0.59158736", "0.5746999", "0.573626", "0.5684531", "0.5594022", "0.548549", "0.54789877", "0.54735273", "0.5453367", "0.53605527", "0.5331817", "0.5316855", "0.5314494", "0.5304399", "0.5295936", "0.5258274", "0.5228602", "0.5215712", "0.5211028", "0.5169184", "0.515939", "0.51439637", "0.5141355", "0.5141039", "0.5127262", "0.51232064", "0.511348", "0.5112795", "0.51126385", "0.51007825", "0.5083684", "0.5081544", "0.50763524", "0.5072281", "0.50684613", "0.506505", "0.5063339", "0.5061924", "0.50596935", "0.5053914", "0.5047265", "0.50359726", "0.50070775", "0.50050145", "0.49934143", "0.49880645", "0.49855435", "0.497895", "0.4977154", "0.49769163", "0.49746993", "0.49677795", "0.4966272", "0.4963619", "0.49633873", "0.4958607", "0.49579328", "0.4951351", "0.494975", "0.49486688", "0.49458557", "0.4943617", "0.4933748", "0.49327248", "0.49266034", "0.4926054", "0.4926054", "0.49251115", "0.49193257", "0.4918113", "0.49162042", "0.4905809", "0.48994586", "0.48962945", "0.48957878", "0.48946476", "0.48909453", "0.48867077", "0.48853678", "0.4883231", "0.4881491", "0.4881469", "0.48726085", "0.4868966", "0.48670268", "0.48670268", "0.48657423", "0.48628002", "0.48569232", "0.4850816", "0.48452792", "0.4843397", "0.48424077", "0.48412317", "0.48405963", "0.48390794", "0.48360574", "0.48319498", "0.48314106", "0.48289955", "0.48277342" ]
0.0
-1
quando viene premuto il tasto ENTER/INVIO su tastiera, invia messaggio
function onEnterSendMessage(e) { if (e.keyCode === 13) { onSendMessage(sex, name); return false; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function tastoInvio(event) {\r\n if (event.which == 13) {\r\n inviaMessaggio();\r\n }\r\n }", "function invioTasto(e){\r\n var key = e.which;\r\n var inputCercaFilm = inputFilm.val();\r\n if(key == 13){ // 13 tasto invio\r\n ricercaTitolo();\r\n }\r\n }", "function PremiInvio(event){\n if(event.key === \"Enter\") EseguiForm();\n}", "function enterMessage(e) {\n if (e.code === 'Enter'){\n addMessage($(this));\n }\n if(e.code === 'Escape' ){\n deleteMessage($(this).parent());\n }\n}", "function enter(event) {\n var messageSent = document.getElementById(\"input\");\n var i = event.keyCode;\n if (i == 13)\n {\n if(messageSent.value == '')\n {\n alert(\"Enter some text\");\n } else {\n connection.send(messageSent.value);\n }\n } else {\n return false;\n }\n messageSent.value = \"\";\n}", "function enterPressed(e) {\n if (e.keyCode == 13)// Enter Taste\n sendMessage();\n }", "function enterpressalert(e){\n clientResponse1 = e.target.value\n var code = (e.keyCode ? e.keyCode : e.which);\n if(code == 13) { \n sendMsg()\n }\n}", "function keyPressed() {\r\n if (keyCode === ENTER) {\r\n sendMsg();\r\n }\r\n}", "function sendKeyupPressed(event) {\n var keyPressed = event.which;\n // console.log(\"tasto premuto\", keyPressed);\n\n if(keyPressed === 13) {\n var inputSelected = $(this);\n var textInserted = inputSelected.val();\n if(textInserted.length > 0) {\n inputSelected.val(\"\");\n console.log(\"testo catturato \", textInserted);\n\n sentMsgConsole(textInserted); // 3step DEBUG : su console\n\n setTimeout(function(){// step4 : messaggio bubble con ritardo\n sentMsgBubble(textInserted);\n // scrolling function : premendo il testo invia il box dei messaggi scrolla automaticamente\n $('.msg-box.active').animate({\n scrollTop: $('.msg-box.active').get(0).scrollHeight\n }, 1500);\n }, 150);\n\n setTimeout(function(){// step5 : arriva messaggio di risposta con ritardo\n gettinMsgBubble();\n\n $('.msg-box.active').animate({\n scrollTop: $('.msg-box.active').get(0).scrollHeight\n }, 1500);\n\n }, 3000);\n\n }\n\n }\n\n}", "function EnterPressRSenha(){\r\n if(event.keyCode == 13){\r\n // 13 = código do botão ENTER\r\n Cadastrar() // Clica no botão de cadastrar!\r\n }\r\n}", "function userMsgSend(e){\n\tif(e.which==13){\n\t\tif($('#userText').val()!=0){\n\t\t\topenAdminOpChat();\n\t\t}\n\t}\n}", "function enter_pressed(e){if(e.keyCode==13){oraculo();}}", "onPress(e) {\n if(e.key === 'Enter') {\n if(this.props.checkPrivate) {\n Meteor.call('sendPrivateMessage', this.props.filterCriteria, this.refs.textarea.value, Meteor.user().username);\n } else {\n Meteor.call('sendMessage', this.props.filterCriteria, this.refs.textarea.value, Meteor.user().username);\n }\n this.refs.textarea.value = '';\n }\n }", "function updateOnEnter(e){\n\tvar enterKey = 13;\n\tif (e.which == enterKey){\n\t\tupdateChat();\n\t\t// now clear the message box!\n\t\tchatmsg.value = '';\n\t}\n}", "function send(){\n if (event.which == 13 || event.keydown == 13 ) {\n var messaggio = $('#mioMessaggio').val();\n // invio il mio messaggio\n if(messaggio!=\"\"){\n var clonazione = $('.template .message').clone();\n var ora = time();\n clonazione.append('<p class=\"testo-msg\">' + messaggio + '</p>');\n clonazione.append('<p class=\"ora-msg\">' + ora + '</p>');\n clonazione.append('<div class=\"quadrato-verde\"></div>');\n clonazione.addClass('msg-mio');\n\n $('#area-dx #area-chat').append(clonazione);\n document.getElementById(\"mioMessaggio\").value=\"\";\n setInterval(updateScroll,0);\n // creo una funzione per rispondere automaticamente\n setTimeout(function(){\n copiaClone = $('.template .message').clone();\n var tuoMessaggio = arrAnswer[rispostaRandom(arrAnswer.length, 0)];\n copiaClone.append('<p class=\"testo-msg\">' + tuoMessaggio + '</p>');\n copiaClone.append('<p class=\"ora-msg\">' + ora + '</p>');\n copiaClone.append('<div class=\"quadrato-bianco\"></div>');\n copiaClone.addClass('msg-altro');\n $('#area-dx #area-chat').append(copiaClone);\n setInterval(updateScroll,0);\n },1000)\n }\n }\n }", "function _simpan_transaksi(){\r\n\t\t//not available\r\n\t\t//transaksi di simpan pada saat kolom jml transaksi event keypress keycode 13 [enter]\t\r\n\t}", "function enter(event){\r\n if (!textoEntrada.value==\"\"){\r\n if (event.keyCode == 13 || event.which == 13){\r\n analizar();\r\n }\r\n }\r\n}", "function keyPress(e) {\n\t var x = e || window.event;\n\t var key = (x.keyCode || x.which);\n\t if (key == 13 || key == 3) {\n\t\t//runs this function when enter is pressed\n\t\tnewEntry();\n\t }\n\t if (key == 38) {\n\t\tconsole.log('hi')\n\t\t //document.getElementById(\"chatbox\").value = lastUserMessage;\n\t }\n\t}", "function checkEnter(e)\r\n { \r\n try\r\n {\r\n // catches the return key event to send the message\r\n var characterCode\r\n\r\n // firefox and IE key event getter\r\n if(e && e.which){\r\n e = e\r\n characterCode = e.which \r\n }\r\n else{\r\n e = event\r\n characterCode = e.keyCode \r\n }\r\n\r\n if(characterCode == 13){ //send the message if enter was hit \r\n\r\n // get the message to send from the txtInput box\r\n var message = getMessageToSend(); \r\n //only send the mesage if it is not blank\r\n if(message!=''){ \r\n //display the message in the display box\r\n \r\n addMessageToDisplay('me', message);\r\n \r\n hideLastMessageDiv();\r\n // send the message\r\n sendMessage(message); \r\n //empty the chat window\r\n document.getElementById('txtInput').value = '';\r\n //return false so no 'enter' key is displayed in the input box\r\n }\r\n return false;\r\n }\r\n }\r\n catch(ex){}\r\n }", "function enterKeyCheck(keyCode) {\r\n if (keyCode == 13) {\r\n // option A (might not work on actual webpage)\r\n sendLocalMessage();\r\n // option B\r\n // document.getElementById(\"sendButton\").click();\r\n }\r\n}", "handlePressEnter(event) {\n let message;\n if (event.key === 'Enter') {\n let date = new Date().toDateString();\n let sender = \"You\";\n let context = event.target.value;\n event.target.value = \"\";\n message = {\n context:context,\n sender:sender,\n sentDate:date\n };\n this.state.addMessage(message);\n }\n\n }", "function keywordsMsg(e)\n{\n var event = e || window.event;\n if(event.keyCode == 13)\n {\n $('#send').click();\n }\n}", "function submitEnterKey(){\r\n\r\nvar messagetxt = document.getElementById('message');\r\nvar sendbtnvar = document.getElementById('sendbtn');\r\n\r\nmessagetxt.addEventListener(\"keyup\",function(event){\r\nevent.preventDefault();\r\n\t\tif(event.keyCode == 13){\r\n\t\t//The \"g\" switch is global replace, \"m\" means it should happen more than once. Note: If you are replacing a value (and not a regular expression), \r\n\t\t// only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier. \r\n\t\t// piece of code with the javascript replace method removes all three types of line breaks by using this bit of a regular expression: \\r\\n|\\n|\\r. \r\n\t\t//This tells it to replace all instance of the \\r\\n then replace all \\n than finally replace all \\r. It goes through and removes all types of line \r\n\t\t//breaks from the designated text string. The \"gm\" at the end of the regex statement signifies that the replacement should take place over many \r\n\t\t// lines (m) and that it should happen more than once (g). The \"g\" in the javascript replace code stands for \"greedy\" which means the replacement \r\n\t\t// should happen more than once if possible. If for some reason you only wanted the first found occurrence in the string to be replaced then you \r\n\t\t//would not use the \"g\". http://www.textfixer.com/tutorials/javascript-line-breaks.php\r\n\r\n\t\tmessagetxt.value = messagetxt.value.replace(/(\\r\\n|\\n|\\r)/gm,\"\");\r\n\t\tsendbtnvar.click();\r\n\t\t}\r\n\t});\r\n}", "function keyEventMessage(e){\n var event1 = e || window.event;\n if(event1.keyCode == 13){\n $('#sendMsg').click();\n e.preventDefault();\n }\n else if(event1.keyCode == 10) {\n var text = $('#msg').val();\n $('#msg').val(text + \"\\n\");\n }\n return false;\n}", "onMsgSubmission(event) {\n if(event.which === 13) {\n this.props.addMessage(event.target.value);\n event.target.value = '';\n }\n }", "function etapa9() {\n var qtdHorario = document.getElementById('qtdHorario').value;\n \n msgTratamentoEtapa8.innerHTML = \"\";\n \n if(qtdHorario == 0){\n \n msgTratamentoEtapa8.textContent = \"Não foi possível seguir para 9º Etapa! É obrigatório adicionar no mínimo um horário. =)\";\n\n }else{\n //recebendo H3 e setando nela o texto com o nome do cliente\n var tituloDaEtapa = document.querySelector(\"#tituloDaEtapa\");\n tituloDaEtapa.textContent = \"9º Etapa - Local do Evento\"; \n \n document.getElementById('inserirEndereco').style.display = ''; //habilita a etapa 9\n document.getElementById('inserirHorarios').style.display = 'none'; //desabilita a etapa 8\n }\n }", "function keywordsMsg(e)\n{\n var event = e || window.event;\n if(event.keyCode == 13)\n {\n $('#send').click(); \n }\n}", "function inviaMessaggioUtente(){\n var text_user=($('.send').val());\n if (text_user) { //la dicitura cosi senza condizione, stà a dire text_user=0\n templateMsg = $(\".template-message .new-message\").clone()\n templateMsg.find(\".text-message\").text(text_user);\n templateMsg.find(\".time-message\").text(ora);\n templateMsg.addClass(\"sendbyUser\");\n $(\".conversation\").append(templateMsg);\n $(\".send\").val(\"\");\n setTimeout(stampaMessaggioCpu, 2000);\n\n var pixelScroll=$('.containChat')[0].scrollHeight;\n $(\".containChat\").scrollTop(pixelScroll);\n }\n }", "function EnterPressEmail(){\r\n if(event.keyCode == 13){\r\n // 13 = código do botão ENTER\r\n document.getElementById(\"Senha\").focus() // Foca no proximo campo!\r\n }\r\n}", "function reactionEnter (e) {\n if (e.key && String(e.key) == \"Enter\" // Falls Entertaste (Firefox/Internet Explorer) ...\n || e.keyCode == 13) // Falls Entertaste (Chrome) ...\n reaction(true); // ... Daten übernehmen, rechnen, Ausgabe aktualisieren \n }", "function keyPress(e) {\n var x = e || window.event;\n var key = x.keyCode || x.which;\n if (key == 13 || key == 3) {\n //runs this function when enter is pressed\n newEntry();\n }\n if (key == 38) {\n console.log('hi');\n //document.getElementById(\"chatbox\").value = lastUserMessage;\n }\n }", "function beberAgua() {\n console.log(\"Você vai até o rio e mata sua sede\")\n prompt(textos.enter)\n infos.sede = 100\n mainJogo()\n}", "function keyEventMsgToOne(e){\n\tvar event1 = e || window.event;\n\tif(event1.keyCode == 13){\n\t\t$('#btn_toOne').click();\n\t}\n}", "function detectarEnter(e){\n if(i.key == 'Enter'){\n suma ()\n }\n}", "function handleClickEnter() {\n \n if(validEmail==true && validName==true)\n {\n //navigate into ChooseHelp screen\n navigation.navigate(\"ChooseHelp\", {\n userName: nameText,\n userEmail: emailText,\n });\n }\n else // in case the validation fail we pop up alert\n {\n Alert.alert(\"שגיאה\",\"אנא הזן שם ואימייל תקניים\",[{text:\"אישור\"}])\n }\n \n }", "function inviaMessaggio() {\r\n var templateMex = $(\".template .messaggi\").clone();\r\n var txtMex = $(\".txt-mex\").val();\r\n if (txtMex != \"\") {\r\n // Trovo gli elementi a cui stampare messaggio e ora\r\n templateMex.find(\".text\").text(txtMex);\r\n // L'elemento 'ora-chat' richiama la 'funzione ora()'\r\n templateMex.find(\".ora-chat\").text(ora());\r\n templateMex.addClass(\"right\");\r\n $(\".elenco_messaggi.active\").append(templateMex);\r\n $(\".txt-mex\").val(\"\");\r\n scrollDown();\r\n // Ottieni una risposta dopo un secondo\r\n setTimeout(function() {\r\n risposta();\r\n scrollDown();\r\n }, 1000);\r\n } else {\r\n console.log(\"err\");\r\n }\r\n }", "function outgoingMessageKeyDown(event) {\n\t\tif (event.which == 13) {\n\t\t event.preventDefault();\n\t\t if ($('#outgoingMessage').val().trim().length <= 0) {\n\t\t\treturn;\n\t\t }\n\t\t sendMessage();\n\t\t $('#outgoingMessage').val('');\n\t\t}\n\t}", "function OperatE_ideapremenuenter(){\n\t//basic\n\tvar tex=$('#PrelanboX').text();\n\t\n\t//box style set by num\n\tif(tex==''){\n\t\t$('#PrelanboX').addClass('prelanholder');\n\t\t\t$('#PrelanboX').css('color','rgba(255,255,255,0.5)');\t\t\t\t\n\t}\n\telse{\t\t\t\t\t\t\n\t\t$('#PrelanboX').off('click');\n\t\t\t$('#PrelanboX').removeClass('prelanholder');\n\t\t\t\t$('#PrelanboX').css('color','rgba(255,255,255,1)');\t\t\t\t\n\t}\n\t\n\t//box enter str by num \n\tvar texl=tex.length;\n\tvar texl=125 - texl;\n\t$('#PrelaN_enteralbenum').text(texl);\t\t\t\n\tif(texl < 0){\n\t\t$('#PrelaN_enteralbenum').css('color','rgba(255,0,0,1)');\n\t}\n\telse if(texl >= 0){\n\t\t$('#PrelaN_enteralbenum').css('color','rgba(0,125,0,1)');\t\t\t\t\t\t\n\t}\t\n}", "function reactionEnter (e) {\r\n if (e.key && String(e.key) == \"Enter\" // Falls Entertaste (Firefox/Internet Explorer) ...\r\n || e.keyCode == 13) // Falls Entertaste (Chrome) ...\r\n reaction(); // ... Daten übernehmen und rechnen \r\n paint(); // Neu zeichnen\r\n }", "function sendMessage(ev) {\n var textField = document.getElementById('message');\n console.log(ev.key);\n if((ev.key === \"Enter\" || ev.type === \"click\") && textField.value !== '') {\n ws.send(JSON.stringify({\n uuid: uuid,\n message: textField.value\n }));\n textField.value = '';\n } else if(ev.key === 'Escape') {\n disconnect();\n }\n}", "function va0xEnter(){\r\n\tif(isBlank(z_va02_order)) {\r\n\t\tif(_language == 'E') {\r\n\t\t\tmessage('E: Enter Order Number');\r\n\t\t}\r\n\t\tif(_language == 'J') {\r\n\t\t\tmessage('E: 注文番号を入力してください');\t\t\r\n\t\t}\r\n\t\tenter('?');\r\n\t\tgoto SCRIPT_END;\r\n\t}\r\n\r\n\t// Change Sales Order: Initial Screen\r\n\tonscreen 'SAPMV45A.0102'\r\n\t\tset('F[VBAK-VBELN]','&V[z_va02_order]');\r\n\t\tenter();\r\n\t\tonmessage\r\n\t\tif(_message.substring(0,2) == 'E:') {\r\n\t\t\tmessage(_message);\r\n\t\t\tenter('/n');\r\n\t\t\tgoto SCRIPT_END;\r\n\t\t}\r\n\r\n\t// Change Sales Order: Initial Screen\r\n\tonscreen 'SAPMSDYP.0010'\r\n\t\tenter();\r\n\t\r\n\tonscreen 'SAPMV45A.4001'\r\n\t\tgoto SAPMV45A_4008;\r\n\r\n\tonscreen 'SAPMV45A.4008'\r\n\t\tSAPMV45A_4008:;\r\n\t\tenter('=KKAU');\r\n\t\tHANDLE_WARNINGS:;\r\n\t\tonmessage\r\n\t\tif(_message.substring(0,2) == 'W:') {\r\n\t\t\tmessage(_message);\r\n\t\t\tenter();\r\n\t\t\tgoto HANDLE_WARNINGS;\r\n\t\t}\r\n\r\n\tonscreen 'SAPMV45A.4002'\r\n\t\tset(\"V[z_va01_price_list]\",\"&F[VBKD-PLTYP]\");\r\n\t\tenter('KRPL');\r\n\r\n\tonscreen 'SAPLV60F.4001'\r\n\t\tset('V[z_vaxx_total]','&F[FPLAA-ENDWR]');\r\n\t\tenter('T\\\\06');\r\n\r\n\tonscreen 'SAPMV45A.5002'\r\n\t\tset('V[z_vaxx_tax]','&F[KOMP-MWSBP]');\r\n\t\tenter('KSTA');\r\n\r\n\tonscreen 'SAPMV45A.4002'\r\n\t\t//Overall status\r\n\t\tif(<'F[VBUK-GBSTK]'>.isValid)\r\n\t\t\tset('V[z_vaxx_overallStatus]','&F[VBUK-GBSTK]');\r\n\t\t//Rejection status\r\n\t\tif(<'F[VBUK-ABSTK]'>.isValid)\r\n\t\t\tset('V[z_vaxx_rejectionStatus]','&F[VBUK-ABSTK]');\r\n\t\t//Delivery status\r\n\t\tif(<'F[VBUK-LFSTK]'>.isValid)\r\n\t\t\tset('V[z_vaxx_deliveryStatus]','&F[VBUK-LFSTK]');\r\n\t\t//Credit status\r\n\t\tif(<'F[VBUK-CMGST]'>.isValid)\r\n\t\t\tset('V[z_vaxx_creditStatus]','&F[VBUK-CMGST]');\r\n\t\tenter('/3');\r\n\r\n\tSCRIPT_END:;\r\n}", "function reactionEnter(e) {\n if (e.key && String(e.key) == \"Enter\" /* Si la tecla Enter (Firefox / Internet Explorer) ...*/ || e.keyCode == 13) /*Si la tecla Enter (Chrome*/\n reaction(); // ... acepta y calcula datos \n paint(); // Dibuja de nuevo\n}", "function EnterPressSenha(){\r\n if(event.keyCode == 13){\r\n // 13 = código do botão ENTER\r\n document.getElementById(\"Rsenha\").focus() // Foca no proximo campo!\r\n }\r\n}", "function emailChangeConfirmPress(event) {\n //if enter gets pressed, change the email\n if (event.keyCode == 13)\n changeEmail();\n}", "enterMessage(event){\n if (event.key === \"Enter\"){\n this.submitMessage()\n }\n }", "function outgoingMessageKeyDown(event) {\n\tif (event.which == 13) {\n\t\tevent.preventDefault();\n\t\tif ($('#outgoingMessage').val().trim().length <= 0) { return; }\n\t\tsendMessage();\n\t\t$('#outgoingMessage').val('');\n\t}\n}", "function InvioBarCode(tasto) {\r\n var BarCode =document.getElementById(\"txtBarCode\").value;\r\n \r\n // controlla se nella stringa letta dal lettore ci sia il codice di 'invio' o se l'utente abbia premuto il tasto di invio\r\n // In caso affermativo manda la stringa a PHP\r\n if (tasto.keyCode==13) {\r\n document.getElementById(\"hdnID\").value=BarCode;\r\n \r\n document.getElementById(\"CercaIscritti\").submit();\r\n }\r\n \r\nreturn;\r\n}", "function checkEnter(e){\n if(e.keyCode === 13)\n getTwitchData();\n}", "function runScript(e) {\r\n if (e.keyCode == 13) {\r\n var tb = document.getElementById(\"txt\");\r\n $.get(\"/api/beta/send/channel-message/\",\r\n { msg: tb.value },\r\n function (data){\r\n document.getElementById(\"txt\").value = \"\";\r\n });\r\n return false;\r\n }\r\n}", "_startDialogue () {\n this.app.DOM.messengerBtn.onclick = () => {\n let value = this.app.DOM.messengerInput.value;\n\n if (value != '') this._sendMessageFromUser(value);\n this.app.DOM.messengerInput.value = '';\n }\n }", "function reactionEnter (e) {\n if (e.key && String(e.key) == \"Enter\" // Falls Entertaste (Firefox/Internet Explorer) ...\n || e.keyCode == 13) // Falls Entertaste (Chrome) ...\n reaction(); // ... Daten übernehmen und rechnen \n paint(); // Neu zeichnen\n }", "function enCartaEscandallo(idescandallo,nombreescandallo){\n\tvar mensaje = \"Va a Poner ACTIVO este Escandallo:\\n\\nID: \"+idescandallo+\"\\nNombre:\"+nombreescandallo+\"\\n\\nEsto le permite que pueda ser incluido en una o varias cartas.\\n\\nCONFIRME QUE DESEA HACER ESTO\";\n\tif (confirm(mensaje)){\n\t\tdocument.getElementById(\"idEscandallo\").value=idescandallo;\n\t\tdocument.getElementById(\"accion\").value=\"ponActivo\";\n\t\t// envia formulario\n\t\tdocument.DatosEscandallo.submit();\n\t}\n\t\n}", "function BOT_chatboxOnKeypress(obj,evt) {\r\n\t\tif(BOT_theNavigator == null) return;\r\n\t\tvar s = obj.value; \r\n\t\tif(BOT_theNavigator == \"IE\" && evt.keyCode == 13) {\r\n\t\t\tevt.keyCode = null;\r\n\t\t\tBOT_chatboxMainProcess(s);\r\n\t\t\tBOT_agentSpeech(); \r\n\t\t\t}\r\n\t\tif(BOT_theNavigator == \"NN\" && evt.which == 13) {\r\n\t\t\tBOT_chatboxMainProcess(s);\r\n\t\t\tBOT_agentSpeech(); \r\n\t\t\t}\r\n}", "enterA13(ctx) {\n\t}", "function showPrompt(idPedido) {\n ons.notification.prompt('Ingrese un comentario')\n .then(function (input) {\n agregarComentario(idPedido, input);\n var message = input ? 'Gracias por su comentario' : 'El comentario no puede estar vacio';\n ons.notification.alert(message);\n });\n}", "function sent() {\n console.info(\"Fine processo d'invio notizie\")\n}", "function enter(e){\n if(e.which == 13 && !e.shiftKey){\n $('#send').click();\n e.preventDefault();\n }\n}", "function inputKeyDown(event, inputBox) {\n // Submit on enter key, dis-allowing blank messages\n if (event.keyCode === 13 && inputBox.value) {\n // Retrieve the context from the previous server response\n let context;\n const latestResponse = Api.getResponsePayload();\n if (latestResponse) {\n context = latestResponse.context;\n }\n\n // Send the user message\n Api.sendRequest(inputBox.value, context);\n\n // Clear input box for further messages\n inputBox.value = '';\n Common.fireEvent(inputBox, 'input');\n }\n }", "handleKeyboard (event) {\n\t\tif (event.keyCode != 13) return;\n\t\tthis.sendMessage();\n\t}", "function buttonEnter() {\n\t\tdocument.onkeydown = function (e) {\n\t\t\te = e || window.event;\n\t\t\tif (e.keyCode === 13)\n\t\t\t\talert(\"you press enter!\")\n\t\t};\n\t}", "function confirmarPedido() {\n valorTotal = valorPrato + valorBebida + valorSobremesa;\n const botao = document.querySelector(\".botao-confirmar\");\n if(botao.classList.contains(\"liberar-confirmacao\")) {\n nomeUsuario = prompt(\"Qual é o seu nome?\");\n enderecoUsuario = prompt(\"Qual é o seu endereço?\");\n mensagem = encodeURIComponent( `Olá, gostaria de fazer o pedido:\n - Prato: ${nomePrato}\n - Bebida: ${nomeBebida}\n - Sobremesa: ${nomeSobremesa}\n Total: R$ ${valorTotal.toFixed(2)}\n \n Nome: ${nomeUsuario}\n Endereço: ${enderecoUsuario}`);\n janelaConfirmacao();\n }\n}", "function keyPress(e) {\n var x = e || window.event;\n var key = x.keyCode || x.which;\n if (key == 13 || key == 3) {\n //runs this function when enter is pressed\n newEntry();\n }\n if (key == 38) {\n console.log(\"hi\");\n //document.getElementById(\"chatbox\").value = lastUserMessage;\n }\n}", "function sendMessageOnEnterKeyPress(e) {\n let code = e.keyCode || e.which;\n\n // check if use press only enter key\n if (!e.shiftKey && (code == 13 || e.key == \"Enter\")) {\n e.preventDefault();\n\n // pass to function that will run the process\n if (chat_text_area.innerText.trim().length > 0) {\n processSendMessage();\n }\n }\n }", "function enter(e) {\n if (e.key === 'Enter') {\n postChatMessage() // fires off post message function\n }\n}", "function chatInputEnterPressed() {\n //console.log(lzm_chatInputEditor.grabHtml());\n sendChat(lzm_chatInputEditor.grabHtml());\n lzm_chatInputEditor.setHtml('');\n}", "function keyPress(e) {\n var x = e || window.event;\n var key = (x.keyCode || x.which);\n if (key == 13 || key == 3) {\n //runs this function when enter is pressed\n $('#interaction').append($(\"<div id='usr_msg'>\"+document.getElementById(\"chatbox\").value+\"</div><div class='clear'></div>\"));\n document.getElementById(\"chatbox\").placeholder = \"\";\n newEntry();\n }\n if (key == 38) {\n console.log('hi')\n //document.getElementById(\"chatbox\").value = lastUserMessage;\n }\n}", "function confirmStampe() {\n\tvar message = \"Al termine dell'operazione verra' inviata un'email di riepilogo a info@urbanialimentari.com.\\nConfermi?\";\n\treturn confirm(message);\n}", "function textKeyPress(e) {\n if (e.keyCode == ENTER_KEY) {\n postRemark();\n }\n}", "function OnEnter() \n{\n\tif (window.event.keyCode == 13) \n\t{\n\t\t//\n\t\t// Send chat data to user\n\t\t//\n\t\tSendChatData();\n }\n}", "function vl02nEnter(){\r\n\tif(isBlank(z_vl02n_dlv)) {\r\n\t\tif(_language == 'E') { \r\n\t\t\tmessage('E: Enter Delivery Number');\r\n\t\t}\r\n\t\tif(_language == 'J') { \r\n\t\t\tmessage('E: 配達番号を入力してください');\r\n\t\t}\r\n\t\tenter('?');\r\n\t\tgoto SCRIPT_END;\r\n\t}\r\n\t\r\n\t//onscreen v102n\r\n\tonscreen 'SAPMV50A.4004'\r\n\t\tset('F[LIKP-VBELN]','&V[z_vl02n_dlv]');\r\n\t\tenter();\r\n\t\tonmessage\r\n\t\tif(_message.substring(0,2) == 'E:') {\r\n\t\t\tmessage(_message);\r\n\t\t\tenter('/n');\r\n\t\t\tgoto SCRIPT_END;\r\n\t\t}\r\n\t\r\n\tSCRIPT_END:;\r\n}", "function pasajeFoco(){\n var correo = document.getElementById(\"correo\");\n var contraseña = document.getElementById(\"contraseña\");\n var boton = document.getElementById(\"boton\");\n \n correo.focus();\n\n const enter = (e) => {\n switch (e.target.name) {\n case 'correo':\n if (e.keyCode === 13) {\n e.preventDefault();\n contraseña.focus();\n }\n break;\n case 'contraseña':\n if (e.keyCode === 13) {\n boton.focus();//Revisar\n }\n break;\n default:\n enviar();\n break;\n }\n };\n\n correo.addEventListener('keypress', enter);\n contraseña.addEventListener('keypress', enter);\n boton.addEventListener('click', enter);\n}", "function onkey(x) {\n if (x.keyCode == 13) {\n alertAmount();\n }\n}", "function validar(e) {\n tecla = (document.all) ? e.keyCode : e.which;\n if (tecla==13) {\n aceptar()\n }\n}", "function submitNewMessage(){\n $('#message-content').keydown(function(event) {\n if (event.keyCode === 13) {\n let msg = event.target.value\n let chatroomId = messages.attr('data-chat-room-id')\n App.global_chat.send({body: msg, chat_room_id: chatroomId})\n $('#message-content').val(\" \")\n return false;\n }\n });\n }", "function inputKeyDown(event, inputBox) {\n // Submit on enter key, dis-allowing blank messages\n if (event.keyCode === 13 && inputBox.value) {\n Api.sendRequest(inputBox.value);\n\n // Clear input box for further messages\n inputBox.value = '';\n Common.fireEvent(inputBox, 'input');\n }\n}", "function inputKeyDown(event, inputBox) {\n // Submit on enter key, dis-allowing blank messages\n if (event.keyCode === 13 && inputBox.value) {\n // Retrieve the context from the previous server response \n var context;\n var latestResponse = Api.getResponsePayload();\n if (latestResponse) {\n context = latestResponse.context;\n }\n\n // Send the user message \n Api.sendRequest(inputBox.value, context);\n \n //hide pincode on html\n var responseText = $(\"#scrollingChat .segments:eq(-2) .message-inner\").text();\n if(responseText.split('.').length>1){\n responseText = responseText.split('.')[1].trim();\n }\n if(inputBox.value.match(/^\\d+$/) && inputBox.value.length < 5 &&\n responseText == \"Please enter your 4-digit PIN\"\n || responseText == \"Please enter your PIN again\") {\n var tx = inputBox.value.replace(/./g,'*'); \n $(\"#scrollingChat .segments:last .message-inner p\").html(tx)\n }\n \n // Clear input box for further messages\n inputBox.value = '';\n Common.fireEvent(inputBox, 'input');\n }\n }", "function enterToSend() {\n $('body').keydown((event) => {\n if ( event.keyCode == 13 ) {\n sendChatMessage();\n }\n })\n}", "function pressEnter() {\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n rl.question(\" \", function (input) {\n rl.close();\n\n chosenAdvice(input);\n });\n}", "function enterTrigger(e){\n if(e.keyCode === 13){\n handleAddTask();\n }\n}", "function buscar_asociado(e) {\r\n tecla = (document.all) ? e.keyCode : e.which;\r\n if (tecla==13){\r\n tablaresultados_asociado(2);\r\n }\r\n}", "function handleKey(e) {\n\te = (!e) ? window.event : e;\n\tcode = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));\n\n\t// if enter is pressed it sends message without the send button being clicked\n\tif (e.type == \"keydown\") {\n\t\tif (code == 13) {\n\t\t\tsendMessage();\n\t\t}\n\t}\n}", "function buscarproducto(e) {\r\n tecla = (document.all) ? e.keyCode : e.which;\r\n \r\n if (tecla==13){\r\n tablaresultadosproducto(2);\r\n }\r\n}", "function buscarproducto(e) {\r\n tecla = (document.all) ? e.keyCode : e.which;\r\n \r\n if (tecla==13){\r\n tablaresultadosproducto(2);\r\n }\r\n}", "function buscarproducto(e) {\r\n tecla = (document.all) ? e.keyCode : e.which;\r\n \r\n if (tecla==13){\r\n tablaresultadosproducto(2);\r\n }\r\n}", "function reprompt(){\n inquirer.prompt([{\n type: \"confirm\",\n name: \"reply\",\n message: \"Would you like to purchase another item?\"\n }]).then(function(ans){\n if(ans.reply){\n start();\n } else{\n console.log(\"See you soon!\");\n }\n });\n}", "function ClickAdicionarEscudo() {\n gEntradas.escudos.push({ chave: 'nenhum', obra_prima: false, bonus: 0 });\n AtualizaGeralSemLerEntradas();\n}", "confirmShuffleOnInput ( ev ) {\n\t\tif ( ev.keyCode === 13 ) {\n\t\t\tev.preventDefault();\n\t\t\tthis.setShuffleTimes();\n\t\t\tthis.startGame();\n\t\t\tev.target.blur();\n\t\t}\n\t}", "function messaggioInviato() {\n var valoreInserito = $(\"#msg-input\").val();\n var messaggioInterno = $(\".active .msg-structure .user\").clone();\n var orario = time();\n\n if (valoreInserito !=\"\") {\n messaggioInterno.find(\".testo-msg\").text(valoreInserito);\n messaggioInterno.find(\".ora-msg\").text(orario);\n $(\".active\").append(messaggioInterno);\n $(\"#msg-input\").val(\"\");\n };\n}", "function AmexBrandrecepient()\r\n{\r\n\tdebugger;\r\n\tif (this.checked)\r\n\t {\r\n\t\tvar AmexBrandobj=\"SPAmexBrandrecipient\"\r\n\t\t$('#additinalrecipientpopup').modal('show');\r\n\t\t$(\"#additionalrecipienttext\").empty().append('<textarea class=\"form-control\" id=\"SPrecipienttext\" placeholder=\"Enter emails here, hit enter when finished...\"></textarea>');\r\n\t \t$(\"#recipienttext\").val(''); \t\r\n\t\t \t$('#SPrecipienttext').keypress(function (e) {\r\n\t\t\tdebugger;\r\n\t\t\t var key = e.which;\r\n\t\t\t if(key == 13) // the enter key code\r\n\t\t\t { \r\n\t\t\t \tSPupdaterecipient(AmexBrandobj); \r\n\t \t\t\t}\r\n\t\t\t}); \r\n \t }\r\n \t else\r\n \t {\r\n \t \t$('#additinalrecipientpopup').modal('hide');\r\n \t }\r\n}", "function ctrlEnter_st(e){\n var ie =navigator.appName==\"Microsoft Internet Explorer\"?true:false;\n if(ie){\n if(event.ctrlKey && window.event.keyCode==13){sendTalk();}\n } else {\n if(isKeyTrigger(e,13,true)){sendTalk();}\n }\n}", "function ctrlEnter_st(e){\n var ie =navigator.appName==\"Microsoft Internet Explorer\"?true:false;\n if(ie){\n if(event.ctrlKey && window.event.keyCode==13){sendTalk();}\n } else {\n if(isKeyTrigger(e,13,true)){sendTalk();}\n }\n}", "function irAAgregarMaestro(){\r\n\tvar msg = \"Desea Agregar un NUEVO REGISTRO?.. \";\r\n\tif(confirm(msg)) Cons_maestro(\"\", \"agregar\",tabla,titulo);\r\n}", "onMessageSubmit(event) {\n if(event.charCode === 13) {\n this.props.messageGenerator(this.state.currentUser.name, this.state.message);\n this.setState({\n message: ''\n })\n }\n }", "function abreEfechaCaixaMensagem(){\r\n areaMensagensFull.classList.toggle('area-mensagens-full-on');\r\n $('#message').on('keypress', submitOnEnter);\r\n}", "function focoafecha(z){\t\nvar sitio=document.getElementById(\"lugar\").value;\ntecla=(document.all) ? z.keyCode : z.which;\n\n if(tecla==13 && sitio!=\"\") \n {\n document.trabajo.lugar.className=\"correcto\";\t \n document.trabajo.fecha.focus();\n}\nif(tecla==13 && sitio==\"\" ){\n\talert(\"Rectifque el campo \\\"Lugar de Trabajo\\\" \");\n\treturn;\n}\n}", "function onKeyDown() {\n document.addEventListener('keydown',function (key) {\n if(key.which === 13) {\n sendMessage();\n }\n });\n}", "enterKey() {\n switch (this.currentScreen) {\n case \"settings\":\n this.settingsComplete()\n break\n case \"awaitingAnswer\":\n this.submitQuestion()\n break\n case \"questionAnswered\":\n this.displayNextQuestionOrSummary()\n break\n }\n }", "function givenUserInput(e) {\n if (e.keyCode == 13) {\n let userResponse = chatInput.value.trim();\n if (userResponse !== \"\") {\n setUserResponse()\n send(userResponse)\n }\n }\n}", "function SendMessage(e) {\n if (e.keyCode == 13) {\n event.preventDefault();\n if (document.getElementById(\"chatSend\").value.toLowerCase() == \"y\") {\n window.location.href = \"https://www-inova-org-i.caretechweb.com/Physicians/Results.aspx?Gender=M&Language=10000&SearchTerm=Allergy\";\n ChatAdmin(\"We are refining your search, please wait ...\");\n document.getElementById(\"chatSend\").value = \"\";\n return false;\n }\n ChatMessage();\n }\n}", "function presionarEnter( e ) \r\n{\r\n\tvar keycode;\r\n\r\n\tif ( window.event ) \r\n\t\tkeycode = window.event.keycode;\r\n\r\n\telse \r\n\t\tif ( e ) \r\n\t\t keycode = e.which;\r\n\t\telse \r\n\t\t\treturn true;\r\n\r\n\tif ( keycode == 13 ) \r\n\t{\r\n\t return true;\r\n\t}\r\n\telse\r\n\t return false;\r\n}" ]
[ "0.8452439", "0.7159661", "0.7050387", "0.68797225", "0.6662516", "0.6651202", "0.6587322", "0.6563563", "0.65477324", "0.6506453", "0.6471627", "0.6415464", "0.63980526", "0.6384608", "0.6382589", "0.6364818", "0.6337972", "0.6326123", "0.63210106", "0.6305891", "0.6303539", "0.62984216", "0.6292191", "0.62906826", "0.6279006", "0.62729126", "0.6269209", "0.62675655", "0.62575746", "0.6253401", "0.6236074", "0.62339616", "0.6217928", "0.6199912", "0.61979854", "0.6177725", "0.6160694", "0.61406386", "0.61383986", "0.61378133", "0.61344653", "0.61274624", "0.61203897", "0.6118359", "0.61150163", "0.61129546", "0.611291", "0.6103583", "0.6097183", "0.609687", "0.60954607", "0.6094262", "0.6074585", "0.6073188", "0.60715526", "0.6065878", "0.6061434", "0.6059488", "0.6059476", "0.6057405", "0.6056132", "0.60551816", "0.60550004", "0.6040983", "0.60257983", "0.6016791", "0.60050184", "0.5993282", "0.5990366", "0.59900635", "0.59798294", "0.5970358", "0.59380853", "0.59377444", "0.59273857", "0.5917714", "0.5903246", "0.58992773", "0.58957195", "0.5891765", "0.5890622", "0.5888709", "0.5888709", "0.5888709", "0.5886246", "0.5870657", "0.58627415", "0.5861172", "0.5855288", "0.58449", "0.58449", "0.5843785", "0.5841345", "0.5840359", "0.5837368", "0.5828218", "0.58282095", "0.5827338", "0.58272827", "0.5822168" ]
0.6432059
11
Helper Functions Checks if input is a valid number.
function _isValidNumber(number) { var errorMessage = ""; if (number.length == 0) { errorMessage = "Must enter a valid number"; } else if (Math.sign(number) == -1) { errorMessage = "Cannot be negative"; } else if (number == 0) { errorMessage = "Cannot be zero"; } else if (number.toString()[0] == "0") { errorMessage = "Cannot have leading 0"; } else if (number.indexOf('.') !== -1) { errorMessage = "has decimal"; } return errorMessage; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isValidNumber ( input ) {\r\n\t\treturn typeof input === 'number' && isFinite( input );\r\n\t}", "function isValidNumber ( input ) {\r\n\t\treturn typeof input === 'number' && isFinite( input );\r\n\t}", "function isValidNumber(input) {\n return typeof input === 'number' && isFinite(input);\n }", "function isValidNumber ( input ) {\n\t\treturn typeof input === 'number' && isFinite( input );\n\t}", "function isValidNumber ( input ) {\n\t\treturn typeof input === 'number' && isFinite( input );\n\t}", "function validNumber(input){\r\n\treturn (input.length == 10 || input[0] == \"0\");\r\n}", "function isValidNumber(input) {\n return typeof input === 'number' && isFinite(input);\n }", "function isValidNumber(input) {\n return typeof input === \"number\" && isFinite(input);\n }", "function isValidNumber(input) {\n // var num = Number.parseInt(input);\n // var numText = num + \"\";\n if (isNaN(input)) {\n return false;\n }\n return true;\n}", "function validInput(input) {\n return isInteger(input) && input > 0\n}", "function numberCheck (input) {\n\tif (input >= 0 && input <= 9) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function numberIsNumber(userInput) {\n var userInputNumber = parseInt(userInput)\n\n if (Number.isNaN(userInputNumber) && !userInput) {\n\n return false\n }\n return true\n}", "function validateNumber (inputVal) {\n let inputNum = Number(inputVal);\n if (inputNum || inputVal === '' || inputVal === '.' || Number.isInteger(inputNum)) {\n return true;\n }\n return false;\n}", "function oneDigitAtLeastInput(input) {\n return /\\d+/.test(input.value);\n}", "function isNumber(input) {\n if (input.match(/[0-9]+/)) {\n return true;\n } else {\n return false;\n }\n}", "function checkNumber(x) {\n return !isNaN(+x);\n}", "function isNumeric(input) { return (input - 0) == input && input.length > 0;}", "function isNumber(input){\n\tif (input.match(/[0-9]+/)) {\n return true;\n } else {\n return false;\n }\n}", "function checkNumber (input) {\n\t\tif (input <= 100 && input >= 1) {\n\t\t\tfizzbuzz();\n\t\t} else if (isNaN(input)) {\n\t\t\tprompt('You did not enter a number. Please enter a number between 1 and 100');\n\t\t} else {\n\t\t\tprompt('Your number (' + input + ') is not between 1 and 100. Please enter a number between 1 and 100');\n\t\t}\n\t}", "function validate(num) {\r\n // return Number.isInteger(num);\r\n\r\n //return num !== isNaN && num >= 0 && num <= 100;\r\n return typeof num === \"number\" && num >= 0 && num <= 100;\r\n\r\n\r\n\r\n}", "function checkisNum(number) {\n if(typeof number=== 'number' && number>0 ){\n return true;\n }\n return false;\n}", "function validateNum(num){\n var reg = /^\\d+$/;\n return reg.test(num) || \"Please enter a number!\";\n}", "function is_valid_number()\r\n{\r\n\treturn isValidNumber.apply(this, arguments)\r\n}", "function validateInputNumber(input) {\n\tinput.value = formatNumber(input.value);\n\tif (!isNumber(input.value)) {\n\t\tinput.value = '';\n\t}\n}", "hasNumber(inputString) {\r\n return /\\d/.test(inputString);\r\n }", "function inputNumberValid(inputVal) {\n if ( !(inputVal && inputVal.trim().length) || isNaN(Number(inputVal)) || inputVal < 0) {\n throw new Error(\"Invalid input! A positive numbers only accepted\");\n }\n return inputVal;\n}", "function validarNumeros(parametro) {\r\n\tif (!/^([0-9])*$/.test(parametro)) {\r\n\t\treturn false;\r\n\t}else {\r\n\t\treturn true;\r\n\t}\r\n}", "function numericTypeCheck(input) {\r\n return /^-?[0-9]\\d*(\\.\\d+)?$/.test(input);\r\n}", "function isNumber()\n{\n var validNum = false;\n if ( parseInt(numInString) )\n {\n validNum = true;\n }\n return validNum;\n}", "function validateInput(input) {\n\n var number = parseInt(input);\n \n if (isNaN(number) || number < 0 || number > 7) {\n return 0;\n }\n else {\n return number;\n }\n}", "function checkInput(value) {\n return !isNaN(value);\n}", "function checkNum(str){\n var num = parseInt(str, 10);\n return (!isNaN(num) && !(num < 1));\n}", "function isNumeric(input) {\n return (typeof input) == \"number\";\n}", "function isNumberOk(num) {\n if (num > 0 && num < 99999999) return true;\n return false;\n}", "function validate_isValidNumber() {\n var _normalizeArguments = getNumberType_normalizeArguments(arguments),\n input = _normalizeArguments.input,\n options = _normalizeArguments.options,\n metadata = _normalizeArguments.metadata;\n\n return isValidNumber(input, options, metadata);\n}", "function checkfornumber(element)\n{\n\tif(checkNumber(element) && checkRequired(element))\n\t{\n\t\treturn true;\n\t}\n\telse\n\t{\n\t\treturn false;\n\t}\n}", "function numericCheck(inputString) {\n return /^[0-9]+$/.test(inputString);\n}", "function validateInput(input) {\n\t\n\t/*---------- check if string contains only digits, space & non-zero value ----------*/\n\t\n\tif(isAllAreDigits(input)){\n\n\t\tinput.trim(); \n\n\t\t/*---------- remove intermediate spaces ----------*/\n\t\t\n\t\tinput = input.replace(/\\s+/g,' ').trim();\n\n\t\tinputDigits = input.split(\" \");\n\n\n\t\t/*---------- check maximum value limit ----------*/\n\t\t\n\t\tif( !isLessThanMaxValuePlusNonZero() ){\n\n\t\t\treturn false;\n\t\t}\n\n\n\t\t/*---------- check input length ----------*/\n\t\t\n\t\tif(inputDigits.length > 10){\n\n\t\t\terrorMessage = \"Numbers exceed maximum limit, Please try again\";\n\n\t\t\treturn false;\n\t\t}\n\n\n\n\n\t\treturn true;\n\t}\n\n\treturn false;\n}", "function isInputNumber(e) {\n let regularExpresion = new RegExp('^[1-9]?[0-9]{1}$|^100$');\n let regExpOk = regularExpresion.test(e.target.value);\n if ( !regExpOk && (e.target.value != '') ){\n e.preventDefault();\n e.target.value = '';\n return false;\n } else {\n return true;\n }\n}", "function isNumber(num){\n return !isNaN(num)\n}", "function numCheck(){\n let input = document.querySelector('input[type=\"text\"]').value;\n let check = parseInt(input);\n if (isNaN(check) && input != \"\"){\n return false;\n } else {\n return true;\n }\n}", "function check_number(input) {\r\n var re = new RegExp('^[0-9]{1,2}$');\r\n if (input.match(re)) { return true; }\r\n else { return false; }\r\n}", "function isNumeric(input) {\n return (input - 0) == input && (''+input).trim().length > 0;\n}", "function isNumeric(input) {\n return input !== undefined\n && input !== null\n && (typeof input === 'number' || parseInt(input, 10) == input);\n}", "function isNumber(n) {\n return !isNaN(parseInt(n))\n}", "function isNumeric(input) {\n if(isNaN(parseFloat(input))) {\n return false;\n } else {\n return true;\n }\n}", "function invalidNumber(number) {\n return number.trimStart() === '' || Number.isNaN(Number(number));\n}", "function isNumeric(input) {\n var numericBoolean = !isNaN(input);\n return numericBoolean\n}", "function validNumber(value) {\n const intNumber = Number.isInteger(parseFloat(value));\n const sign = Math.sign(value);\n\n if (intNumber && (sign === 1)) {\n return true;\n } else {\n return 'Please use whole non-zero numbers only.';\n }\n}", "function validateNumber(value) {\n var valid = Number.isInteger(parseFloat(value));\n var sign = Math.sign(value);\n\n if (valid && (sign === 1)) {\n return true;\n } else {\n return \"Please enter a number\";\n }\n}", "function validar(num1){\n if(isNaN(num1)){\n return false;\n } else {\n return true;\n }\n}", "function validateNumber(answer) {\n\n var reg = /^\\d+$/;\n return reg.test(answer) || \"Please input a number!\";\n\n}", "function validateNumber(answer) {\n\n var reg = /^\\d+$/;\n return reg.test(answer) || \"Please input a number!\";\n\n}", "function numCheck(entry) {\n\tlet regex = /^[0-9]+$/i;\n\tif (entry != null && entry.match(regex)) {\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n}", "function checkForNumber(t) {\n let regex = /\\d/g;\n return regex.test(t);\n}", "function checkForNumber(t) {\n let regex = /\\d/g;\n return regex.test(t);\n}", "function validateNumber(numberInput) {\n var x = numberInput;\n \n try {\n if(x == \"\") throw \"is empty\"\n if(isNaN(x)) throw \"is not a number\"\n x = Number(x);\n if(x > 10) throw \"is too high\"\n if(x < 5) throw \"is too low\"\n \n }\n catch(err) {\n console.log(\"Catch : \" + err);\n }\n finally {\n console.log(\"Finally : \");\n }\n}", "function isValidNumber() {\n\tvar _normalizeArguments = Object(_getNumberType__WEBPACK_IMPORTED_MODULE_1__[\"normalizeArguments\"])(arguments),\n\t input = _normalizeArguments.input,\n\t options = _normalizeArguments.options,\n\t metadata = _normalizeArguments.metadata;\n\n\treturn Object(_validate___WEBPACK_IMPORTED_MODULE_0__[\"default\"])(input, options, metadata);\n}", "function verifyInt(input)\n{\n var x = parseInt(input.value, 10);\n if (isNaN(x) || x < 0) {\n input.value = \"\";\n input.focus();\n } else\n gasUse();\n return;\n}", "function verifyNumber(number) {\n\tlet regex = RegExp(/^1?[2-9][0-9]{9}$/);\n\tif (!number || number === '')\n\t\treturn '';\n\telse if (regex.test(number))\n\t\treturn number;\n\tthrow new Error(\"invalid number\");\n}", "function isNumber(num){\n\t\treturn !isNaN(num);\n\t}", "function checkNum() {\n for (let i = arguments.length - 1; i >= 0; i--) {\n if (isNaN(arguments[i]) || arguments[i] < 0) {\n return false;\n }\n continue;\n }\n return true;\n }", "function CheckNumeric(num) {\r\n\tif (isNaN(num) || num == '' || num == null) {\r\n\t\tnum = 0;\r\n\t}\r\n\treturn num;\r\n}", "function CheckNumeric(num) {\r\n\tif (isNaN(num) || num == '' || num == null) {\r\n\t\tnum = 0;\r\n\t}\r\n\treturn num;\r\n}", "function numeric(campo){\r\n if (isNaN(parseInt(campo.value))) {\r\n alert('Este campo debe ser un número');\r\n return false;\r\n }else{\r\n \treturn true;\r\n }\r\n\r\n}", "function isNumber(n) {\n return RegExp(/^[0-9]+$/).test(n);\n }", "function isNumber(n) {\n return !isNaN(parseInt(n)) && isFinite(n);\n}", "function isNum(n) {\n return (!isNaN(parseFloat(n)) && isFinite(n));\n}", "function isNumber(n) { return !isNaN(parseFloat(n)) && !isNaN(n - 0) }", "checkNumInput(txt, min, max, err_reason, err_msg){\n var val\n // Handle input with errors\n if (txt === ''){\n val = ''\n }\n else if (Number.isNaN(parseInt(txt))){\n val = ''\n this.setInputNumberErrorMessage(err_reason, err_msg)\n } else if (parseInt(txt).toString() !== txt){\n val = parseInt(txt)\n this.setInputNumberErrorMessage(err_reason, err_msg)\n } else if (parseInt(txt) < min){\n val = min\n this.setInputNumberErrorMessage(err_reason, err_msg)\n } else if (parseInt(txt) > max){\n val = max\n this.setInputNumberErrorMessage(err_reason, err_msg)\n } else {\n val = parseInt(txt)\n }\n\n return val\n }", "function isANumber(n){\n return typeof n === \"number\" && !Number.isNaN(n);\n}", "function isValidNumber(x) {\r\n\r\n //\r\n // Notes on the issue:\r\n //\r\n // http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric\r\n //\r\n // http://stackoverflow.com/questions/18082/validate-decimal-numbers-in-javascript-isnumeric/174921#174921\r\n //\r\n // https://dl.dropboxusercontent.com/u/35146/js/tests/isNumber.html //\r\n //\r\n if (!(!isNaN(parseFloat(x)) && isFinite(x))) {\r\n throw \"!isNaN(parseFloat(x)) && isFinite(x) says invalid x=\" + x;\r\n }\r\n\r\n //\r\n // Note: There are plenty of ways to test for NaN that\r\n // *do not* work.\r\n //\r\n // Note: Read about Number.isNaN(abs) to ensure NaN is detected without\r\n // aliases. For example Javascript will convert parsable strings and\r\n // values such as \"bool\" to numbers. (Bool translates to 0 or 1, both\r\n // valid numbers).\r\n //\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN\r\n //\r\n\r\n if (typeof(x) == \"undefined\") {\r\n throw \"Number is invalid by typeof(x) == \\\"undefined\\\", x=\" + x;\r\n }\r\n\r\n // Currently the universal (though not 100% reliable) test for a bad number.\r\n if (x != x) {\r\n throw \"Number is invalid by x != x, x=\" + x;\r\n }\r\n\r\n //\r\n // Some functions are considered global in browsers and widely supported\r\n //\r\n\r\n // Test against the global isNaN() function\r\n if (isNaN(x)) {\r\n throw \"Number is invalid by isNaN(x) x=\" + x;\r\n }\r\n\r\n //\r\n // Standard comparsion tests against values\r\n // is whats available on all (or most) Javascript engines.\r\n //\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\r\n //\r\n\r\n //\r\n // We can't trust these are present on all platforms so\r\n // validate there presence.\r\n //\r\n // They throw so we can \"know our platform\" and its compromises\r\n // to number validation.\r\n //\r\n // Javascript has the interesting property that a test\r\n // against an undefined will be false, so you would not even\r\n // know that the platform does not allow us to indicate bad numbers.\r\n //\r\n if (typeof(Infinity) == \"undefined\") {\r\n throw \"Infinity is undefined\";\r\n }\r\n\r\n if (typeof(Number.NaN) == \"undefined\") {\r\n throw \"Number.NaN is undefined\";\r\n }\r\n\r\n if (typeof(Number.NEGATIVE_INFINITY) == \"undefined\") {\r\n throw \"Number.NEGATIVE_INFINITY is undefined\";\r\n }\r\n\r\n if (typeof(Number.POSITIVE_INFINITY) == \"undefined\") {\r\n throw \"Number.POSITIVE_INFINITY is undefined\";\r\n }\r\n\r\n if (typeof(Number.MAX_VALUE) == \"undefined\") {\r\n throw \"Number.MAX_VALUE is undefined\";\r\n }\r\n\r\n if (typeof(Number.MIN_VALUE) == \"undefined\") {\r\n throw \"Number.MIN_VALUE is undefined\";\r\n }\r\n\r\n if (typeof(Number.MAX_SAFE_INTEGER) == \"undefined\") {\r\n // Not on current Node.js 01/2015\r\n //throw \"Number.MAX_SAFE_INTEGER is undefined\";\r\n }\r\n else {\r\n if (!(x < Number.MAX_SAFE_INTEGER)) {\r\n throw \"Number is invalid by < MAX_SAFE_INTEGER x=\" + x;\r\n }\r\n }\r\n\r\n if (typeof(Number.MIN_SAFE_INTEGER) == \"undefined\") {\r\n // Not on current Node.js 01/2015\r\n //throw \"Number.MIN_SAFE_INTEGER is undefined\";\r\n }\r\n else {\r\n if (!(x > Number.MIN_SAFE_INTEGER)) {\r\n throw \"Number is invalid by x < MIN_SAFE_INTEGER x=\" + x;\r\n }\r\n }\r\n\r\n // Test for Infinity\r\n if (x == Infinity) {\r\n throw \"Number is invalid by x == Infinity x=\" + x;\r\n }\r\n\r\n if (x == Number.NaN) {\r\n throw \"Number is invalid by x == Number.NaN x=\" + x;\r\n }\r\n\r\n if (x == Number.NEGATIVE_INFINITY) {\r\n throw \"Number is invalid by x == NEGATIVE_INFINITY x=\" + x;\r\n }\r\n\r\n if (x == Number.POSITIVE_INFINITY) {\r\n throw \"Number is invalid by x == POSITIVE_INFINITY x=\" + x;\r\n }\r\n\r\n if (!(x < Number.MAX_VALUE)) {\r\n throw \"Number is invalid by > MAX_VALUE x=\" + x;\r\n }\r\n\r\n if (x == 0) {\r\n // we must take 0 as ok, since the tests below fail on 0\r\n }\r\n else if (x < 0) {\r\n var abs = Math.abs(x);\r\n if (isNaN(abs)) throw \"Math.abs(x) == isNaN()\";\r\n if (!(abs > Number.MIN_VALUE)) {\r\n throw \"Number is invalid by < MIN_VALUE x=\" + x;\r\n }\r\n }\r\n else {\r\n if (!(x > Number.MIN_VALUE)) {\r\n throw \"Number is invalid by x > MIN_VALUE x=\" + x;\r\n }\r\n }\r\n\r\n //\r\n // The presence of validation functions is currently (01/2015) considered\r\n // ECMA Version 6 experimental features. Support is really spotty\r\n // across browsers. Though the Chrome V8 engine is up to date. Not\r\n // sure where this maps to Node.js versions.\r\n //\r\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite\r\n //\r\n/*\r\nREMOVE 01/18/2015 does not work on Node.js as of 01/2015\r\n\r\n if (typeof(Number.isFinite) != \"undefined\") {\r\n\r\n if (!Number.isFinite(x)) {\r\n // This throws on 0, 0.00, 0.2188, etc. Node.js as of 01/2015\r\n //throw \"number is not finite x=\" + x;\r\n // Version, platform issues?\r\n }\r\n }\r\n*/\r\n\r\n/*\r\n01/18/2015 not sure if we want this since strictly a float\r\nvalue of 1.23 is not an integer.\r\n\r\n if (typeof(Number.isInteger) != \"undefined\") {\r\n\r\n // NOTE: As of Node.js 01/2015 0.4375, etc. pass this test!\r\n if (!Number.isInteger(x)) {\r\n throw \"number is not integer x=\" + x;\r\n }\r\n }\r\n*/\r\n\r\n if (typeof(Number.isNaN) != \"undefined\") {\r\n if (Number.isNaN(x)) {\r\n throw \"Number is invalid by Number.isNaN(x) x=\" + x;\r\n }\r\n }\r\n\r\n if (typeof(Number.isSafeInteger) != \"undefined\") {\r\n if (!Number.isSafeInteger(x)) {\r\n throw \"number is not safe integer x=\" + x;\r\n }\r\n }\r\n\r\n return;\r\n}", "function isNum(num, err) {\n if (isNaN(num) || num == \"\" || num == null) {\n alert(err);\n return true;\n } else {\n return false;\n }\n}", "function validateNum(){\r\n\tvar num = document.survey_form.informative.value; //get the value\r\n\t//make sure the entry is a number\r\n\tvar numPattern = /^[0-9]+$/;\r\n\tif(!numPattern.test(num)){alert(\"Please enter a numerical value.\" )}\r\n\t//if the value is less than 0 or greater than 10, it is not valid.\r\n\tif (num < 0 || num > 10)\t\t\t\r\n\t\t{alert(\"Please enter a number between 0 and 10\" )}\t\r\n\t}", "function validateInput(value) {\n\tvar integer = Number.isInteger(parseFloat(value));\n\tvar sign = Math.sign(value);\n\n\tif (integer && (sign === 1)) {\n\t\treturn true;\n\t} else {\n\t\treturn 'Please enter a whole non-zero number.';\n\t}\n}", "function checkNumber(numb) {\n return (/^\\d|\\(([^)]+)\\)|-|$/).test(numb)\n }", "function validateNumericInput(input) {\n let message = \"Please enter one or more digits without spaces\";\n if (input.length > 0) {\n return input.match(/^[0-9]\\w*/g) ? true : message;\n } else return message;\n}", "function validateInput(value) {\n var integer = Number.isInteger(parseFloat(value));\n var sign = Math.sign(value);\n\n if (integer && (sign === 1)) {\n return true;\n } else {\n return 'Please enter a whole non-zero number.';\n }\n}", "function validateNumber(val) {\n if(Number.isInteger(parseFloat(val)) == true && Math.sign(val) == 1) {\n return true\n } else {\n return 'Invalid quantity input!!'\n } \n}", "function isValidNumber() {\n var _normalizeArguments = Object(_getNumberType__WEBPACK_IMPORTED_MODULE_1__[\"normalizeArguments\"])(arguments),\n input = _normalizeArguments.input,\n options = _normalizeArguments.options,\n metadata = _normalizeArguments.metadata;\n\n return Object(_validate___WEBPACK_IMPORTED_MODULE_0__[\"default\"])(input, options, metadata);\n}", "function CheckNumeric(num){\r\n if(isNaN(num) || num=='' || num==null)\r\n {\r\n num=0;\r\n }\r\n return num;\r\n}", "function CheckNumeric(num){\r\n if(isNaN(num) || num=='' || num==null)\r\n {\r\n num=0;\r\n }\r\n return num;\r\n}", "function inputChecksOut(input){\n // if(Number.isInteger(input)){\n // return true\n // }\n // else{\n // return false\n // }\n\n //Or ?\n\n return Number.isInteger(input) && input > 0\n }", "function isStringOfNumbers(input) {\n //Test for non-numeric chars\n let test = input.replace(/,|\\.|-|\\s/g, '');\n let res = validator.isNumeric(test);\n // let res = validator.isNumeric(input);\n if (!res) {\n const invalidChars = '[' + test.replace(/[0-9]/g, '').split('').join(',') + ']';\n return \"Contains non-numeric values, such as \" + invalidChars;\n }\n return true;\n}", "function numberValidation(input) {\n var name = input.id;\n var value = parseFloat(input.value);\n var min = parseFloat(input.min);\n var max = parseFloat(input.max);\n if (!(value >= min && value <= max)) {\n return name + \" not in range (\" + input.min + \", \" + input.max + \")\";\n } else return \"valid\";\n}", "function isnum(num) {\n return (/^\\d+$/.test(num + \"\"));\n}", "function inputCheck(){\n\tif(isNaN(input.value)){return false;}\n\telse return true;\n}", "function ValidateNumber(input1, input2) {\n if (Number.isNaN(input1) && Number.isNaN(input2))\n return false;\n\n return true;\n}", "validateValue (value) {\n return TypeNumber.isNumber(value) && !isNaN(value)\n }", "function validateInput(value) {\n var integer = Number.isInteger(parseFloat(value));\n var sign = Math.sign(value);\n\n if (integer && (sign === 1)) {\n return true;\n } else {\n return 'Please enter a whole number larger than zero.';\n }\n}", "function validateNumber(value) {\n if (value % 1 === 0 && value > 0) {\n return true;\n } else {\n console.log(\" **** Please enter a whole number above zero. ****\");\n }\n}", "function isValid(x) {\n return !isNaN(x);\n\n}", "static checkNumber(number) {\n try {\n if (typeof number === \"number\" || parseInt(number)) {\n PositiveNumber.validate(+number, NUMBER_CONSTRAINTS);\n }\n return \"\";\n }\n catch (error) {\n console.error(error);\n return \"The number of the street must be a positive value!\";\n }\n }", "function checkInputTypeNumber(){\n\n\t\tvar inputElem = document.createElement('input'),\n\t\tsmile = ':)',\n\t\tbool = false;\n\n\t\tinputElem.setAttribute('type', 'number');\n\t\tbool = inputElem.type !== 'text';\n\t\tif( bool ) {\n\t\t\tinputElem.value = smile;\n\t\t\tbool = inputElem.value != smile;\n\t\t}\n\n\t\treturn bool;\n\t}", "verifyPositiveNumber(value) {\n return parseInt(value) >= 0;\n }", "function hasNumber(str) {\n return /\\d/.test(str);\n}", "function isNumber(n){\n return !isNaN(parseFloat(n)) && isFinite(n);\n}", "function isNum(num){\r\n return typeof(num) === 'number'; \r\n}", "function isValidNumber(x) {\n return !isNaN(x) && (x != Infinity) && (x != -Infinity);\n}", "function isValidNumber(x) {\n return !isNaN(x) && (x != Infinity) && (x != -Infinity);\n}" ]
[ "0.8498495", "0.8498495", "0.8494983", "0.84911335", "0.84911335", "0.8454034", "0.84370553", "0.8434083", "0.8341299", "0.80753624", "0.80330265", "0.7917614", "0.77989614", "0.76512975", "0.76502633", "0.76326776", "0.7621404", "0.75786793", "0.75480574", "0.7543008", "0.74995154", "0.74770135", "0.74713373", "0.7459984", "0.7450527", "0.74476606", "0.74375826", "0.74261534", "0.74256766", "0.74248695", "0.7407902", "0.74044025", "0.73878443", "0.73819524", "0.7368215", "0.7364663", "0.7336618", "0.73275995", "0.73258084", "0.7322663", "0.73154163", "0.7298906", "0.72958523", "0.7288737", "0.7286993", "0.7276798", "0.72687775", "0.7262042", "0.72560585", "0.7248016", "0.723746", "0.72350967", "0.72350967", "0.72336566", "0.7226205", "0.7226205", "0.7214345", "0.7208353", "0.72020125", "0.71997637", "0.71956176", "0.71714723", "0.7166417", "0.7166417", "0.7164167", "0.7160246", "0.7159029", "0.7152176", "0.7127086", "0.71256757", "0.7120106", "0.71148163", "0.7104653", "0.7099355", "0.7097819", "0.70966315", "0.7087582", "0.7086564", "0.7083842", "0.7081086", "0.707825", "0.707825", "0.7076176", "0.7075914", "0.7056641", "0.70444393", "0.70393974", "0.7036512", "0.70342404", "0.7025117", "0.7024844", "0.70178926", "0.699508", "0.6993607", "0.6987741", "0.697525", "0.6974661", "0.69716936", "0.6971664", "0.6971664" ]
0.70356685
88
Checks if inches value is more than 11
function _inchesMoreThan12(number) { var errorMessage = "" if (number > 11) { return errorMessage = "Cannot be more than 11 in"; } return errorMessage; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function inchesConvert() {\n var newFt = parseInt($heightInput.val()) || 0;\n var newIn = parseInt($heightInputIn.val());\n while (newIn >= 12) {\n newFt++;\n newIn -= 12;\n }\n $heightInput.val(newFt);\n $heightInputIn.val(newIn);\n }", "function areYouWithinTwentyDigitsOf(integer) {\n if ((100 - integer) <= 20 || (120 - integer) <= 20) {\n console.log(true)\n } else if ((400 - integer) <= 20 || (420 - integer) <= 20) {\n console.log(true)\n } else {\n console.log(false);\n }\n\n}", "function getInchesFromFeet(feet) {\nreturn feet * 12;\n}", "function imperial(num) {\n let total = num + selector(58,14);\n let feet = Math.floor(total / 12);\n let inches = total % 12;\n return config.height = feet + \"'\" + inches + '\"';\n }", "function inchFeet(inch){\n var feet = inch/12;\n return feet \n}", "function isLessThanThirty(num) {\n return num < 30 ? true : false;\n}", "function under10(num) {\n return num < 10;\n}", "function len(feet, inches, eigths) {\n var l = (12 * (feet || 0)) + (inches || 0) + ((eigths || 0) / 8); \n return pixels(l);\n}", "function metersToInches(meters){\n return (meters * 39.3701);\n}", "function inchToFeet(inch){\n var feet = inch / 12;\n return feet;\n}", "function testLessOrEqual(val) {\r\n if (val <= 22) { \r\n document.write (\"Smaller Than or Equal to 12 <br><br>\") ;\r\n }\r\n \r\n if (val <= 24) { \r\n document.write (\"Smaller Than or Equal to 24 <br><br>\") ;\r\n }\r\n \r\n else{\r\n document.write (\"More Than 24 <br><br>\") ;\r\n } }", "function isWithinSafeBounds(){\n const value = parseFloat(\"0.\" + String( $( window ).width() / $(\".result-container:first\").outerWidth(true) ).split(\".\")[1])\n if( (0.3 < value && value < 0.7) ) { return true; }\n else { return false; }\n }", "function inchToFeet(inch){\n var feet=inch/12;\n return feet;\n}", "function inchToFeet(inch){\n var feet=inch/12;\n return feet;\n}", "function testIt(f){\n let num = Math.round(+((f-32)/9*5)*100)/100\n return (num >= -273.15) ? num : \"Invalid input!\";\n}", "function isHeightValid(hgt) {\n if (/\\d+cm\\b/.test(hgt)) {\n // If cm, the number must be at least 150 and at most 193.\n const number = parseInt(hgt.match(/\\d+/g)[0]);\n return number >= 150 && number <= 193;\n }\n else if (/\\d+in\\b/.test(hgt)) {\n // If in, the number must be at least 59 and at most 76.\n const number = parseInt(hgt.match(/\\d+/g)[0]);\n return number >= 59 && number <= 76;\n }\n \n return false;\n}", "function metersToInches(meters) {\n return meters * 39.3701;\n}", "function isBelowThreshold(currentValue) {\r\n return currentValue < 40;\r\n }", "function isBelowThreshold(item) {\n return item < 10;\n }", "function checkBorderC(num){\n if(num<15&&num>=0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "function inchTofeet(inch)\n{\n var feet = inch/12;\n return feet;\n}", "function inchToFeet(inch){\n var feet = inch/12;\n return feet;\n}", "function numberIn20(x) {\n return ((Math.abs(100 - x) <= 20) ||\n (Math.abs(400 - x) <= 20));\n}", "function totalInches(feet,inches){\n return (feet*12)+inches;\n }", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function e(t){return t%100===11||t%10!==1}", "function convertInchesToFeet(inches){\n const inchesInOneFoot = 12;\n let feet = Math.floor(inches / inchesInOneFoot);\n let leftOverInches = inches % inchesInOneFoot;\n\n return `${feet}'-${leftOverInches}\"`;\n}", "function inchToFeet(inch) {\n const feet = inch / 12;\n return feet;\n}", "function isBigEnough(value) {\n return value >= 10;\n}", "function greaterThan80(x){\r\n return x > 80;\r\n}", "function centimeterToFeet(cm) {\n const feet = cm / 30.48;\n return feet;\n}", "function magCheck(mag){\n if (mag <= 1){\n return 8\n }\n return mag * 8;\n}", "function HeatNum(obj) {\n var value = obj.value.replace(/\\D/g, '');\n if (value > 30) {\n obj.value = 30;\n } else {\n obj.value = value;\n }\n}", "function isBigEnough(value) {\n if (value >= 10) {\n return true;\n }\n return false;\n}", "function couldDigitize() {\n return getDigitizeUses() < getMaximumDigitizeUses();\n}", "function inToFet(inch){\n\n var feet = inch/12;\n\n return feet;\n}", "function isFive(x) {\n return parseFloat(x) === 5;\n}", "function testLessOrEqual(val) {\n if (val <= 12) { // Change this line\n return \"Smaller Than or Equal to 12\";\n }\n\n if (val <= 24) { // Change this line\n return \"Smaller Than or Equal to 24\";\n }\n\n return \"More Than 24\";\n}", "function checkDigit () {\n c = 0;\n for (i = 0; i < nif.length - 1; ++i) {\n c += Number(nif[i]) * (10 - i - 1);\n }\n c = 11 - (c % 11);\n return c >= 10 ? 0 : c;\n }", "function testLessOrEqual(val) {\n if (val <= 12) { // Change this line\n return \"Smaller Than or Equal to 12\";\n }\n if (val <= 24) { // Change this line\n return \"Smaller Than or Equal to 24\";\n }\n return \"More Than 24\";\n}", "function isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}", "function isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}", "function checkBorderR(num){\n if(num<19&&num>=0)\n {\n return true;\n }\n else\n {\n return false;\n }\n}", "function testLessOrEqual(val) {\n if (val <= 12) { // Change this line\n return \"Smaller Than or Equal to 12\";\n }\n\n if (val <= 24) { // Change this line\n return \"Smaller Than or Equal to 24\";\n }\n\n return \"More Than 24\";\n}", "function isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}", "getHeightInFeetAndInches(cm) {\n let feetAndInches = (cm * 0.032808).toFixed(2)\n let feetAndInchesArray = feetAndInches.split('.')\n\n return `${feetAndInchesArray[0]}ft/${feetAndInchesArray[1]}in`\n }", "function isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n }", "getMeters(inches) {\n return inches === 'unknown' ? '---' : `${Math.round((parseInt(inches) * .0254) * 100) / 100}<i>m</i>`;\n }", "function lessBy10(a, b, c){\n let max1 = Math.max(a, b);\n max1 = Math.max(max1, c);\n if(max1 - a >= 10 || max1 - b >= 10 || max1 - c >= 10)\n return true;\n else\n return false;\n}", "static isValidHeightInCm(heightInCm) {\n return (!Number.isNaN(heightInCm) && Number.isInteger(heightInCm) && heightInCm >= BMI.minHeightInCm && heightInCm <= BMI.maxHeightInCm)\n }", "function beyondSI(exponent) {\n return exponent > 14 || exponent < -15;\n}", "function beyondSI(exponent) {\n return exponent > 14 || exponent < -15;\n}", "function checkNumerator() {\n var medMin = 10;\n\n // List of medications\n var medList = patient.medications();\n\n // Filters\n var medActive = filter_activeMeds(medList);\n\n return isMatch(medActive) && ( medMin <= medActive.length );\n\n }", "function beyondSI(exponent) {\n return exponent > 14 || exponent < -15;\n}", "function isScannerInput() {\n return (((inputStop - inputStart) / $(\"#area_scanner\").val().length) < 15);\n }", "function isScannerInput() {\n return (((inputStop - inputStart) / $(\"#area_scanner\").val().length) < 15);\n }", "function isScannerInput() {\n return (((inputStop - inputStart) / $(\"#area_scanner\").val().length) < 15);\n }", "function isMeasurementValue(value) {\n\t return typeof value === 'number' && isFinite(value);\n\t}", "function number (data) {\n return typeof data === 'number' && data > neginf && data < posinf;\n }", "function checkSpeed(speed) {\n const speedLimit = 70;\n const kmPerPoints = 5;\n if (speed < speedLimit + kmPerPoints) {\n console.log('ok');\n } else {\n const points = Math.floor((speed - speedLimit) / kmPerPoints);\n if (points >= 12) {\n console.log('driver license suspended');\n } else {\n console.log('Points: ' + points);\n }\n }\n}", "function checkLengthOfNum(value){\r\n\treturn (value.length <= 20);\r\n}", "function lessThan6(num){\n return num < 6;\n}", "function chkGoUp(n){\n if ( (Math.round(n) - n) >= 0.9){\n return Math.round(n);\n }\n return Math.floor(n);\n}", "function inchToFeet(inches) {\n var feet = inches / 12;\n return feet;\n console.log(feet);\n}", "function e(A){return A%100===11||A%10!==1}", "function Display() {\n if (num > 60) {\n alert(\"Supérieur à 60\");\n }\n else if (num == 60) {\n alert(\"égale à 60\");\n }\n else {\n alert(\"Inférieur à 60\");\n }\n}", "isMin(value, limit) {\n return parseFloat(value) >= limit;\n }", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}", "function t(e){return e%100===11||e%10!==1}" ]
[ "0.6157761", "0.60477793", "0.58263224", "0.58233494", "0.5759308", "0.5754653", "0.5723126", "0.57037085", "0.57028764", "0.56930906", "0.5671446", "0.5647488", "0.5646766", "0.5646766", "0.5629582", "0.56227756", "0.5621705", "0.5594497", "0.55896497", "0.5557051", "0.5541724", "0.5541134", "0.5520557", "0.5519523", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.55165094", "0.54923224", "0.5455625", "0.5450746", "0.54360825", "0.5421766", "0.5409208", "0.54089254", "0.53811353", "0.5373278", "0.5358177", "0.53576815", "0.53548384", "0.53452057", "0.5343448", "0.5343128", "0.5343128", "0.53364235", "0.53341424", "0.5325785", "0.5325123", "0.53124005", "0.5307374", "0.5304408", "0.5304134", "0.52948135", "0.52948135", "0.52930486", "0.528813", "0.5287536", "0.5287536", "0.5286653", "0.5282732", "0.52814263", "0.5276593", "0.5275701", "0.52730095", "0.5264844", "0.5258634", "0.5243735", "0.524059", "0.52356726", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295", "0.52346295" ]
0.61885566
0
CREATE USER PROFILE FUNCTION Compiles user input into a map to create a "profile", returns a map called User
function createUserProfile() { const user = new Map(); user.set("age", document.getElementById("age").value); user.set("gender", document.querySelector("input[name='gender']:checked").value.toLowerCase()); user.set("weight", document.getElementById("weight").value); user.set("feet", document.getElementById("feet").value); user.set("inches", document.getElementById("inches").value); user.set("activity", document.getElementById("activity-level").value.toLowerCase()); return user; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getUserProfile(user) {\n return {\n coords: [noise(user.longitude), noise(user.latitude)],\n name: user.name,\n location: user.city + ', ' + user.state,\n email: user.email,\n company: user.currentemployer,\n cohort: user.cohort\n };\n}", "createProfile() {}", "function createUserProfile() {\n return {\n /* eslint-disable no-multi-spaces, key-spacing */\n _id: undefined,\n user_name: undefined, // undefined means that the field won't be saved.\n user_hash: undefined,\n authenticate_id: undefined,\n user_pwd: undefined,\n pwd_last_changed: undefined,\n is_authorized: undefined,\n receive_notifications: undefined,\n is_admin: undefined,\n user_role: undefined,\n user_status: undefined,\n created_by: undefined,\n date_created: new Date(),\n date_modified: undefined,\n modified_user_id: undefined,\n reports_to_id: undefined,\n description: undefined,\n first_name: undefined,\n last_name: undefined,\n title: undefined,\n department: undefined,\n phone_mobile: undefined,\n phone_work: undefined,\n phone_other: undefined,\n phone_fax: undefined,\n phone_home: undefined,\n email_address_work: undefined,\n email_address_home: undefined,\n address_street: undefined,\n address_city: undefined,\n address_state: undefined,\n address_country: undefined,\n address_postalcode: undefined,\n /* eslint-enable no-multi-spaces, key-spacing */\n };\n}", "function user(firstName, lastName) {\n return {\n // firstName: firstName, // key : value\n firstName,\n lastName, // literals\n fullName: firstName + \" \" + lastName,\n };\n }", "function createUser (profile) {\n const newChatUser = new db.UserModel({\n profileId: profile.id,\n fullName: profile.displayName,\n profilePic: profile.photos[0].value || '/img/user.jpg'\n })\n return newChatUser.save()\n}", "function mapProfileToModel(profileDto, categoriesDto, recipesDto, ingredientsDto) {\n var profile = new Profile(\n profileDto.name, \n profileDto.username,\n profileDto.email,\n profileDto.avatar,\n profileDto.birthdate,\n recipesDto,\n categoriesDto,\n ingredientsDto,\n profileDto.celiac,\n profileDto.vegan,\n profileDto.vegetarian,\n profileDto.diabetic,\n profileDto.badges\n );\n return profile;\n }", "function createUser(name, lastName, age) {\n return {\n name,\n lastName,\n age\n };\n}", "function userCreator(name, score) {\n const newUser = Object.create(userFunctionStore);\n newUser.name = name;\n newUser.score = score;\n return newUser;\n}", "getUserProfile(success, failure) {\n ApolloService.query({\n query: Queries.GET_USER_PROFILE\n }).then(data => { success(this.handleResponse(data.data.getUserProfile, \"user\")) }).catch(error => failure(error));\n }", "function buildUser(first, last){\n let fullName = first + \" \" + last;\n\n return {first, last, fullName};\n}", "function create(req, res) { \n // identify user creating the profile \n req.body.byUser = req.user._id \n Profile.create(req.body) \n .then(profile => {res.json(profile)}) \n .catch(err => {res.json(err)});\n}", "function buildUser( first, last ) { \n let fullName = first + \" \" + last;\n return { first: first, last: last, fullName: fullName };\n}", "function ProfileMapper() {\n this.toRaw = function(profile) {\n var raw = {\n email: profile.email,\n full_name: profile.full_name,\n avatar_url: profile.avatar_url,\n role: profile.role,\n location: profile.location,\n description: profile.description\n }\n if (profile.password) {\n raw.password = profile.password;\n raw.password_confirmation = profile.password_confirmation;\n }\n return raw;\n }\n}", "function createUser(accessToken, refreshToken, profile, done, conn) {\n var newUser = new Object();\n newUser.profile = profile;\n newUser.facebook_id = profile.id;\n newUser.access_token = accessToken;\n newUser.pools = [];\n newUser.powerbucks = 100;\n var sql = 'INSERT INTO users (facebook_id, access_token, profile, pools, powerbucks, registered) VALUES ($1, $2, $3, $4, $5, $6)';\n var vars = [\n profile.id,\n accessToken,\n JSON.stringify(profile),\n JSON.stringify(newUser.pools),\n newUser.powerbucks,\n 0];\n var q = conn.query(sql, vars);\n q.on('end', function() {\n if (done) {\n done(null, newUser);\n }\n });\n}", "static findOrCreateProfile(profile) {\n return this.findOrCreate({\n where: {\n oid: { [Op.eq]: profile.oid },\n },\n defaults: {\n oid: profile.oid,\n email: profile.upn,\n given_name: profile.name.givenName,\n family_name: profile.name.familyName,\n },\n }).then(([user]) => {\n user.changed('updatedAt', true);\n return user.save();\n });\n }", "static findOrCreateProfile(profile) {\n return this.findOrCreate({\n where: {\n oid: { [Op.eq]: profile.oid }\n },\n defaults: {\n oid: profile.oid,\n email: profile.upn,\n given_name: profile.name.givenName,\n family_name: profile.name.familyName\n }\n }).then(([user]) => {\n user.changed('updatedAt', true);\n return user.save();\n });\n }", "function getProfile(username) {\n return db.query(\n `SELECT first_name, last_name, age, email, bio, img_path FROM USERS WHERE username = \"${username}\";`\n );\n}", "function userCreatorFunction(name, score) {\n let newUser = {}\n newUser.name = name\n newUser.score = score\n newUser.increment = function() {\n newUser.score++\n }\n return newUser\n}", "function buildUser(first, last){\n let fullName = first + \" \" + last;\n\n return {first: first, last: last, fullName: fullName};\n}", "function parseUser({ firstname, lastname, address, skills }) {\n updateUser({ firstname, lastname });\n updateSkills(skills.map(s => s.name));\n if(address){\n address.map(address => addNewAddress(address));\n }\n }", "function userProfile() {\n return baseUser().get();\n }", "function createUser() {}", "function user(){\r\n uProfile(req, res);\r\n }", "function makeUser(name,age){\n return{\n name,\n age,\n job: 'engineer',\n };\n}", "function output_user_profile(res, login, userInfo, userInterests, userFriends, peopleWithSameInterests) {\n\tres.render('profile.jade',\n\t\t { title: \"Profile for User with login \" + login,\n\t\t\t userInfo: userInfo,\n\t\t\t userInterests: userInterests,\n\t\t\t userFriends: userFriends,\n\t\t\t peopleWithSameInterests : peopleWithSameInterests}\n\t );\n}", "build (userId, callback) {\n this.db.list('rawProfiles', 'profiles', {key: userId}, (err, json) => {\n if (err)\n return callback(err);\n\n if (json.id === null)\n return callback(new UserNotFoundError(userId));\n\n callback(null, new Profile(json));\n });\n }", "function create(){\n // PREPARE\n let uid = $rootScope.account.authData.uid;\n let profile = instance.extract($rootScope.account.authData);\n\n // INITIALIZE\n $rootScope.db.users.child(uid).set(profile);\n $rootScope.account.profile = profile;\n }", "function createUserProfile() {\n // Set question header text\n $questionHeader.html($titles.introTitle);\n\n // Disable form input autocomplete\n $('form').attr('autocomplete', 'off');\n\n // Hide all but first question\n $userProfile.filter('h3').not(':first-child').hide();\n $userAura.hide();\n\n // Initialize birthday date picker (hidden for now)\n createDatePicker();\n // Add input from username field to welcome\n setUserName();\n // Set welcome image - user zodiac sign - according to input from birthday date picker\n setUserZodiac();\n // Set stylesheet according to aura\n setUserStyle();\n\n // Initialize product carousel and hide for now\n suggestedProducts();\n $products.hide();\n\n}", "function getProfileData() {\n // obtener los datos del usuario al iniciar sesión\n IN.API.Raw(\"people/~:(first-name,last-name,id,num-connections,picture-url,location,positions,summary,public-profile-url)\").result(onSuccess).error(onError); \n }", "static async register({ username, password, profilePicture, bio, isAdmin }) {\n /** Check for a duplicate username before registering */\n\n const duplicateCheck = await db.query(\n `SELECT username\n FROM users\n WHERE username = $1`,\n [username]\n );\n\n if (duplicateCheck.rows[0]) {\n throw new BadRequestError(`Duplicate username: ${username}`);\n }\n\n const hashedPassword = await bcrypt.hash(password, BCRYPT_WORK_FACTOR);\n\n const result = await db.query(\n `INSERT INTO users\n (username,\n password,\n profile_picture,\n bio,\n is_admin)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING username, is_admin AS \"isAdmin\"`,\n [username, hashedPassword, defaultImg, defaultBio, isAdmin]\n );\n\n const user = result.rows[0];\n\n return user;\n }", "function create_user(userobject){\n\n}", "function buildUser( first, last, postCount){\n let fullName = first + \" \" + last;\n const ACTIVE_POST_COUNT = 10;\n\n return { \n first, \n last,\n fullName,\n isActive(){\n return postCount >= ACTIVE_POST_COUNT;\n }}\n}", "get userProfile() {\r\n return this.clone(ProfileLoader_1, \"getuserprofile\").postCore();\r\n }", "userProfile(user) {\n let response = {\n status: 200,\n data: {\n id: user.id,\n first_name: user.first_name,\n last_name: user.last_name,\n email: user.email,\n address: user.address\n }\n }\n return response;\n }", "async function createProfile(req, res, next) {\n const { firstName, lastName, username, email, password } = req.body;\n\n const { errorObj } = res.locals;\n\n if (Object.keys(errorObj).length > 0) {\n return res\n .status(500)\n .json({ message: \"failed attempt\", payload: errorObj });\n }\n\n try {\n let salt = await bcrypt.genSalt(12);\n let securePassword = await bcrypt.hash(password, salt);\n\n const createdProfile = new User({\n firstName,\n lastName,\n email,\n username,\n password: securePassword,\n });\n await createdProfile.save();\n\n res.json({ message: \"You have successfully created a profile\" });\n } catch (e) {\n next(e);\n }\n}", "function createProfile() {\n var protoClass = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'proto-icon';\n var description = arguments.length > 1 ? arguments[1] : undefined;\n var username = arguments.length > 2 ? arguments[2] : undefined;\n var img = arguments.length > 3 ? arguments[3] : undefined;\n var newProfile = document.getElementsByClassName(protoClass)[0].cloneNode(true);\n newProfile.getElementsByTagName('img')[0].src = img;\n newProfile.getElementsByTagName('h1')[0].textContent = username;\n newProfile.getElementsByTagName('p')[0].textContent = description;\n return newProfile;\n} //-----------addFriend function-----------", "function mapStateToProps({ prof }) {\n return {\n firstName: prof.firstName,\n lastName: prof.lastName,\n profileImage: prof.profileImage\n };\n}", "function createUser(){\n return {\n userName: faker.internet.userName(),\n avatar: faker.internet.avatar(),\n id: faker.random.uuid(),\n isStaff: faker.random.boolean() && faker.random.boolean()\n }\n}", "function userCreater(name,score){\n\t//let newUser = objects.create()\n\tlet newUser = Object.create(userFunctions);\n\tnewUser.name = name;\n\tnewUser.score = score;\n\treturn newUser;\n}", "async getProfile (userName) {\n let res = await Http.get(`/api/users/${userName}?view=true`)\n return new User(res.data.user)\n }", "async function BuildMyProfile() {\n await initserver();\n addMyProfileBox();\n addCurrentUserProfile();\n TasksCreatedByUser();\n TasksAssignedToUser();\n}", "function createUserInformation(){\n\tconsole.log(\"function: createUserInformation\");\n\t$().SPServices({\n\t\toperation: \"UpdateListItems\",\n\t\twebURL: siteUrl,\n\t\tasync: false,\n\t\tbatchCmd: \"New\",\n\t\tlistName:\"ccUsers\",\n\t\tvaluepairs:[\n\t\t\t\t\t\t[\"Title\", personInformation().pseudoName], \n\t\t\t\t\t\t[\"PERSON_EMAIL\", personInformation().personEmail], \n\t\t\t\t\t\t[\"P_LAST_NAME\", personInformation().personLastName],\t\n\t\t\t\t\t\t[\"P_FIRST_NAME\", personInformation().personFirstName], \n\t\t\t\t\t\t[\"PERSON_ROLE\", personInformation().personRole], \n\t\t\t\t\t\t[\"PERSON_RANK\", personInformation().personRank], \n\t\t\t\t\t\t[\"PERSON_DIRECTORATE\", personInformation().personDirectorate], \n\t\t\t\t\t\t[\"PERSON_ACTIVE\", personInformation().personActive],\n\t\t\t\t\t\t[\"PERSON_ATTRIBUTES\", personAttributes()],\n\t\t\t\t\t\t[\"PERSON_TRAINING\", personTraining()]\n\t\t\t\t\t],\n\t\tcompletefunc: function (xData, Status) {\n\t\t\t$(xData.responseXML).SPFilterNode(\"z:row\").each(function(){\n\t\t\t\tuserId = $(this).attr(\"ows_ID\");\n\t\t\t})\n\t\t}\n\t});\n\t// Redirect\n\tsetTimeout(function(){\n\t\tsetUserInformationRedirect(userId);\n\t}, 2000);\t\n}", "function getUserData() {\n\n let myUsername = document.getElementById('myUsername').value;\n let myPassword = sha256(document.getElementById('myPassword').value);\n let myEmail = document.getElementById('myEmail').value;\n let profilePicUpload = document.getElementById('profile-pic-upload').value.split('\\\\')[2];\n\n return createUser(myUsername, myPassword, myEmail, profilePicUpload);\n}", "newUserProfile(address) {\n return {\n \"address\": address,\n \"amount_0_given\": ethers.utils.bigNumberify(\"0\"), // Amount weth sold\n \"amount_1_received\": ethers.utils.bigNumberify(\"0\"), // Amount dai received for sells\n \"amount_1_given\": ethers.utils.bigNumberify(\"0\"), // Amount dai given for buys\n \"amount_0_received\": ethers.utils.bigNumberify(\"0\"), // Amount weth bought\n };\n }", "function createNewProfile(req, res) {\n console.log('CREATE NEW PROFILE', req.body)\n db.Profile.create(req.body, function(err, newProfile) {\n if (err) {\n console.log('ERROR ON CREATE', err)\n }\n res.json(newProfile);\n console.log('NEW PROFILE INFO SENT BACK', newProfile)\n })\n}", "async create(profile) {\n if (!profile.id) profile.id = uniqid__WEBPACK_IMPORTED_MODULE_1___default()();\n profile.createdAt = new Date();\n profile.updatedAt = new Date();\n this.profiles[profile.id] = profile;\n return profile;\n }", "function Profile() {\n\t}", "function createNewAccountHelper(profile, newAccountObj, done) {\n\n /*\n ! IMPORTANT: First npm mongoose-findorcreate package, require-in, before installing the plugin \n ! CAUTION: Be sure to require the correct modules into correct locations in the correct order\n ? NOTE: See database/db.js to view plugin, middleware order, etc.\n */\n\n User.findOrCreate({ username: profile._json.email }, async function (err, user) {\n if (!err) {\n if (user && !user.accounts) {\n user.accounts = new Map();\n user.accounts.set(newAccountObj.accountType, newAccountObj);\n user.save();\n }\n // If the specified account does not exists in the already existing account map\n else if (!user.accounts.get(newAccountObj.accountType)) {\n user.accounts.set(newAccountObj.accountType, newAccountObj);\n user.save();\n }\n return done(err, user);\n } else {\n console.log(err);\n }\n });\n}", "function generateUser() {\n\treturn {\n\t\t firstName: faker.name.firstName(),\n\t\t lastName: faker.name.lastName(),\n\t\t phoneNumber: faker.phone.phoneNumber(),\n\t\t address: faker.address.streetAddress(),\n\t\t address2: faker.address.secondaryAddress(),\n\t\t city: faker.address.city(),\n\t\t state: faker.address.stateAbbr(),\n\t\t zipCode: faker.address.zipCode(),\n\t\t email: faker.internet.email(),\n\t\t password: faker.internet.password(),\n\t\t type: generateType(),\n\t\t status: generateStatus()\n\t}\n}", "function createUser(name, score) {\n\n //let newUser = {}; //OR \n let newUser = Object.create(null);\n newUser.name = name;\n newUser.score = score;\n newUser.increment = function(){ newUser.score++;}\n newUser.logIn = function(){console.log(\"You are now logged In!!!\");}\n return newUser;\n}", "function getUserData() {\n return {\n \"id\": Math.floor(Math.random() * 100 + 1),\n \"username\": generateName(),\n \"balance\":2500\n }\n}", "get profile() {\n const value = this.get(PROFILE_STORAGE_KEY);\n\n if (value) {\n const profile = new UserProfile();\n\n // Patch in the values\n Object.assign(profile, JSON.parse(value));\n\n return profile;\n }\n }", "function makeUser(name, age) {\n return {\n name: name,\n age: age,\n // ... other properties\n };\n}", "function createUser (userName, avatar){\n\n return{\n userName,\n avatar,\n\n setUserName:function(userName){\n this.userName = userName;\n return this;\n }\n }\n}", "createUser(username) {\n var createUser = {\n 'username': username,\n 'password': this.password\n };\n var userdata = [];\n userdata.push(createUser);\n var map = new Map(JSON.parse(localStorage.getItem('userstorage')));\n if (!map.has(this.email)) {\n map.set(this.email, createUser);\n localStorage.setItem('userstorage', JSON.stringify(Array.from(map.entries())));\n return true;\n }\n return false;\n }", "function CreateNewUser()\n{\n return { \n name: \"unset\",\n email: \"unset\",\n phone: \"unset\",\n wheelId: \"default-wheel-id\",\n prizeWon: null,\n numSpins: 0,\n \"timestamp\" : GetTimeStampNow()\n }\n}", "function createProfile(api, body) {\n return api_1.POST(api, `/profiles`, { body })\n}", "get profiles() {\r\n return this.create(UserProfileQuery);\r\n }", "static async saveProfile(username, data) {\n let res = await this.request(`users/${username}`, data, \"patch\");\n return res.user;\n }", "function ProfileData() {\r\n}", "function mapStateToProps(state) {\n return {\n user: getUserProfile(state)\n };\n}", "function getProfileData() {\n IN.API.Profile(\"me\").fields(\"firstName\", \"lastName\", \"id\").result(onSuccess).error(onError);\n}", "defaults(user = {}) {\n const gen = this.setup.gen;\n const username = user.username || gen.username();\n return {\n username,\n email: username,\n firstName: gen.firstName(),\n lastName: gen.lastName(),\n isAdmin: false,\n status: 'active',\n projectId: [this.setup.defaults.project.id],\n userRole: 'researcher',\n identityProviderName: 'Cognito Native Pool',\n authenticationProviderId: `https://cognito-idp.${this.setup.defaults.awsRegion}.amazonaws.com/${this.setup.defaults.userPoolId}`,\n ...user,\n };\n }", "function gotProfile(accessToken, refreshToken, profile, done) {\n\t\t//grab profile information for user:\n let dbRowID = String(profile.id);\n let fName = String(profile.name.givenName);\n let lName = String(profile.name.familyName);\n\t\t//check if user is in db, if not place in there:\n const cmdStr = 'INSERT INTO Users(googleid, firstName, lastName) VALUES (?,?,?) ';\n db.run( cmdStr , dbRowID, fName, lName, storeUserCallback)\n //error here has high probability of being user exists in table already:\n function storeUserCallback (err) {\n if (err) {console.log(\"account already in database, moving on\");}\n else {console.log(\"inserted user into db\");}\n //I set googleid as primary key so uniqueness is forced.\n }\n // some commands that may or may not be useful sometime:\n //'UPDATE Users SET seen = seen + 1 WHERE googleid = dbRowID'\n //UPDATE {Table} SET {Column} = {Column} + {Value} WHERE {Condition}\n done(null, profile.id);\n}", "async function findOrCreate(profile) {\r\n let res = await request\r\n .post(reqURL(config.routes.user.findOrCreate))\r\n .withCredentials()\r\n .send({\r\n username: profile.id,\r\n password: profile.password,\r\n provider: profile.provider,\r\n familyName: profile.familyName,\r\n givenName: profile.givenName,\r\n middleName: profile.middleName,\r\n gender: profile.gender,\r\n birthday: profile.birthday,\r\n gravatar: profile.gravatar,\r\n displayPicture: profile.displayPicture,\r\n profileCreatedAt: profile.profileCreatedAt,\r\n emails: profile.emails,\r\n photos: profile.photos\r\n })\r\n .set(\"Content-Type\", \"application/json\")\r\n .set(\"Accept\", \"application/json\")\r\n .auth(\"team\", \"DHKHJ98N-UHG9-K09J-7YHD-8Q7LK98DHGS7\");\r\n log(`findOrCreate:${util.inspect(res.body)}`);\r\n return res.body;\r\n}", "function newUserFunction(nameInput, emailInput, passwordInput) {\n\n var newUser = new Object()\n newUser.name = nameInput\n newUser.email = emailInput\n newUser.password = passwordInput\n\n console.log(newUser)\n return newUser\n}", "function saveNewUser(profile,cb)\n{\n let now = new Date();\n const newUser = new User({\n name: profile.displayName,\n email: profile.emails[0].value,\n googleId: profile.id,\n avatar: profile.photos[0].value,\n coins: 1000,\n role: \"free\",\n joinDate: now,\n lastJoin: now,\n nickname: \"\",\n isNewbe: true,\n });\n newUser.save( (err) => \n {\n if (err) return cb(err);\n return cb(null, newUser);\n }); \n}", "function makeUser(name, age) {\n return {\n name, //same as name: name\n age, //same as age: age\n }\n}", "function updateProfileBasics(userData) {\n $('.name').text(userData['name']);\n $('#email').text(userData['email']);\n buildAsLabels(`#interests`, userData['interests'], 'interests');\n buildAsLabels(`#skills`, userData['skills'], 'skills');\n populateExistingImage('profile', '#profile-picture-main');\n}", "function saveProfileInformation(){\n\tvar name = document.getElementById(\"profileName\").value;\n\tvar age = document.getElementById(\"userAge\").value;\n\tvar phoneNumber = document.getElementById(\"userPhone\").value;\n\tvar mailId = document.getElementById(\"userMail\").value;\n\tvar address = document.getElementById(\"userAddress\").value;\n\tvar profileImg = document.getElementById(\"userImg\").value;\n\tvalidateUserProfile(name, age, phoneNumber, mailId, address, profileImg);\n\tif (profileDataValid) {\n\t\tvar user = new User(name, age, phoneNumber, mailId, address, profileImg);\n\t\tlocalStorage.setItem(\"profileData\", JSON.stringify(user));\n\t}\n\telse{\n\t\talert(\"Error saving Data\");\n\t}\n}", "function generateUserData() {\n return {\n firstName: `${faker.name.firstName()}`,\n lastName: `${faker.name.lastName()}`,\n username: `${faker.internet.userName()}`,\n password: `${faker.internet.password()}`\n };\n }", "function userProfileObject() {\r\n this.userProfile = _userProfile.People; /* use readJsonFile function in people.js in case of fetching JSON from server */\r\n this.default = {\r\n menuEleID: \"\",\r\n contentEleID : \"\"\r\n }\r\n }", "function setUserInfo (request) {\n var url = gravatar.url(request.email, {s: '200', r: 'pg', d: '404'});\n\n var getUserInfo = {\n _id : request._id,\n firstName : request.profile.firstName,\n lastName : request.profile.lastName,\n email : request.email,\n role : request.role,\n username : request.profile.username,\n organization : request.profile.organization,\n country : request.profile.country,\n gravatar : url\n };\n\n return getUserInfo\n}", "createUser(firstName, lastName, email, password) {\n this.setUserId();\n const id = this.getUserId();\n let response;\n const userInfo = {\n id,\n firstName,\n lastName,\n email,\n password,\n token: this.getEncryptedToken(email),\n };\n\n const userData = this.app.readDataFile(userFilePath);\n\n const isUserExist = userData.find(item => item.email === email);\n\n if (!firstName || !lastName || !email || !password) {\n return null;\n }\n\n if (isUserExist) {\n response = false;\n } else {\n // push new user\n userData.push(userInfo);\n this.app.writeDataFile(userFilePath, userData);\n response = userInfo;\n }\n return response;\n }", "function create(opts, callback) {\n\tvar db = opts.db;\n\n\tvar username = opts.username;\n\tvar password = opts.password;\n\tvar email = opts.email;\n\tvar photoUrl = opts.photoUrl;\n\n\tif (!photoUrl) photoUrl = faker.image.avatar();\n\t\n\tvar ts = String.format(\"(NOW() - '{0} seconds'::INTERVAL)\", faker.random.number({min:0, max:864000}));\n\n\tvar statement = \n\t\"DO $$ \\n\" + \n\t\"DECLARE current_id integer;\\n\" + \n\t\"BEGIN\\n\" +\n\tsqlutil.formatInsertStatement('User', \n\t\t['username', 'password', 'email', 'photo_url', 'created_on'], \n\t\t[[username, password, email, photoUrl, {variable: ts}]], false) + \n\t' RETURNING uid INTO current_id;\\n' +\n\n\t\"INSERT INTO \\\"AnalyticsProfile\\\"(\\\"uid\\\", \\\"last_update\\\") VALUES (current_id, NOW());\\n\" +\n\t\"END $$;\";\n\n\t//console.log(statement);\n\n\tdb.query(statement, function(err, result) {\n\t\tif (callback) return callback(err, result);\n\t});\n\n\n}", "function userCreate(firstName, lastName, userName, password, email, type, company, companyUrl) {\n const job = [{ type, company, companyUrl }];\n const userDetails = { firstName, lastName, userName, password, email, job };\n const user = new User(userDetails);\n return user.save();\n}", "function generateUserData() {\n return {\n firstname: faker.name.firstName(),\n lastname: faker.name.lastName(),\n username: `${faker.lorem.word()}${faker.random.number(100)}`,\n email: faker.internet.email(),\n password: faker.internet.password()\n };\n }", "function genUserInfo (userInfo, dbUser, grps, token) {\n\tlet newPayload = {};\n\tlet userData = {};\n\tuserData['name'] = dbUser['userName'];\n userData['nickName'] = dbUser['nickName'];\n userData['gender'] = dbUser['gender'];\n userData['pic'] = dbUser['pic'];\n\tuserData['email'] = dbUser['email'];\n\tuserData['cp'] = userInfo['cp'];\n newPayload['userInfo'] = userData;\n newPayload['services'] = grps;\n newPayload['role'] = dbUser['roleName'];\n newPayload['authToken'] = token;\n newPayload['responseCode'] = '000';\n\tnewPayload['responseMsg'] = 'login success';\n\treturn newPayload;\n}", "function getNewUser () {\n const inputName = document.getElementById('input-name')\n const inputEmail = document.getElementById('input-email')\n const inputAge = document.getElementById('input-age')\n const inputGender = document.getElementById('select-age')\n\n const newUser = {\n name: inputName.value,\n email: inputEmail.value,\n age: inputAge.value,\n gender: inputGender.value\n }\n return newUser\n}", "function userStudent() {\n //Chiedo i dati\n let userName = prompt(\"Inserisci il nome\");\n let userSurname = prompt(\"Inserisci il cognome\");\n let userEta = parseInt(prompt(\"Inserisci l'età\"));\n //Creo oggetto per l'utente\n userInfo = {};\n userInfo.nome = userName;\n userInfo.cognome = userSurname;\n userInfo.eta = userEta;\n}", "function get_user_profile(res, login) {\n\t// For debugging\n\tconsole.log(\"Get Profile of User: \" + login);\n\t\n\tlogin.trim();\n\t// selecting rows\n\toracle.connect(connectData, function(err, connection) {\n\t\tif(err){\n\t\t\tconsole.log(err);\n\t\t}else{\n\t\t\tconnection.execute(\"SELECT userId, passwords, affiliation, givenname, surname, email, to_char(birthday, 'yyyy-mm-dd') as birthday, gender FROM Users WHERE userID='\" + login + \"'\", \n\t\t\t\t\t[], \n\t\t\t\t\tfunction(err, userInfo) {\n\t\t\t\tif ( err ) {\n\t\t\t\t\tconsole.log(err);\n\t\t\t\t\tconnection.close();\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"Got User Info for: \" + login);\n\t\t\t\t\t\n\t\t\t\t\tconnection.execute(\"SELECT area FROM Interest WHERE userID='\" + login + \"'\", \n\t\t\t\t\t\t\t[], \n\t\t\t\t\t\t\tfunction(err, userInterests) {\n\t\t\t\t\t\tif ( err ) {\n\t\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t\t\tconnection.close();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tconsole.log(\"Number of Interests: \" + userInterests.length + \" For User: \" + login);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tconnection.execute(\"SELECT friendID FROM Friend WHERE userID='\" + login + \"'\", \n\t\t\t\t\t\t\t\t\t[], \n\t\t\t\t\t\t\t\t\tfunction(err, userFriends) {\n\t\t\t\t\t\t\t\tif ( err ) {\n\t\t\t\t\t\t\t\t\tconsole.log(err);\n\t\t\t\t\t\t\t\t\tconnection.close();\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tconsole.log(\"Number of Friends: \" + userFriends.length + \" For User: \" + login);\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tconnection.execute(\"SELECT * From (SELECT * FROM ((SELECT Interest.userID FROM (SELECT area FROM Interest Where userID = '\" + login + \"') userInterests, Interest WHERE Interest.userID <> '\" + login + \"' and Interest.area like userInterests.area) MINUS (SELECT friendID FROM Friend Where userID = '\" + login + \"')) ORDER BY dbms_random.value) Where rownum <= 12\", \n\t\t \t\t\t\t\t\t\t\t\t[], \n\t\t \t\t\t\t\t\t\t\t\tfunction(err, peopleWithSameInterests) {\n\t\t \t\t\t\t\t\t\t\tif ( err ) {\n\t\t \t\t\t\t\t\t\t\t\tconsole.log(err);\n\t\t \t\t\t\t\t\t\t\t\tconnection.close();\n\t\t \t\t\t\t\t\t\t\t} else {\n\t\t \t\t\t\t\t\t\t\t\tconnection.close();\n\t\t \t\t\t\t\t\t\t\t\tconsole.log(\"Number of Potential Friends: \" + peopleWithSameInterests.length + \" For User: \" + login);\n\t\t \t\t\t\t\t\t\t\t\toutput_user_profile(res, login, userInfo, userInterests, userFriends, peopleWithSameInterests);\n\t\t \t\t\t\t\t\t\t\t}\n\t\t \t\t\t\t\t\t\t}); // end connection.execute\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}); // end connection.execute\n\t\t\t\t\t\t}\n\t\t\t\t\t}); // end connection.execute\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}); // end connection.execute\n\t\t}\n\t}); // end oracle.connect\n}", "function create_user_from_data(firstName, lastName, userType, course){\n return new User(firstName, lastName, userType, course);\n}", "function gotProfile(accessToken, refreshToken, profile, done) {\n console.log(\"Google profile\", profile);\n // here is a good place to check if user is in DB,\n // and to store him in DB if not already there.\n const dbCheck =\n \"SELECT Google_id FROM user_data WHERE Google_id = \" + profile.id + \"\";\n console.log(\"cheking if user exist\");\n console.log(dbCheck);\n // to accces the user data user req.user. ...\n db.get(dbCheck, dataCallback);\n\n // Always use the callback for database operations and print out any\n // error messages you get.\n // This database stuff is hard to debug, give yourself a fighting chance.\n function dataCallback(err, dbData) {\n if (err) {\n console.log(\"data Selection error\", err);\n } else {\n console.log(\"data selection success\");\n\n if (dbData == undefined) {\n InsertNewUser(profile);\n }\n }\n }\n\n // Second arg to \"done\" will be passed into serializeUser,\n // should be key to get user out of database.\n // temporary! Should be the real unique\n // key for db Row for this user in DB table.\n // Note: cannot be zero, has to be something that evaluates to\n // True.\n let dbRowData = {\n id: profile.id,\n name: profile.name.givenName + \" \" + profile.name.familyName\n };\n done(null, dbRowData);\n}", "async function getProfie() {\n var tagline = await getTagline();\n var country = await getCountry();\n var profile = await getUrl();\n var featured = await getImages();\n res.render('pages/userProfile', {\n username: uname,\n icon: icon,\n tagline: tagline,\n country: country,\n link: profile,\n featured: featured,\n currentUser: currentUser\n });\n }", "updateProfile() {}", "async getUser (req, res) {\n const findOneUserQuery = `\n SELECT avatar, firstname, lastname, email, username, location, bio\n FROM users\n WHERE username = $1\n `;\n\n try {\n\n // A user must be signed in to see edit information\n // Signed in user must also be requesting their own user data.\n if (!req.user || req.user.username !== req.params.username) {\n return res.status(403).send('You\\'re not allowed to edit this profile');\n }\n\n const { rows } = await db.query(findOneUserQuery, [ req.params.username ]);\n const profileUser = rows[0];\n\n // If profile user was not found in database\n if (!profileUser) {\n return res.status(404).send('User not found');\n }\n\n return res.status(200).json({ profileUser });\n } catch (error) {\n return res.status(400).send(error);\n }\n }", "function createUserObject(fName,lName,userDOB){\n return {\n firstName: fName,\n lastName: lName,\n dateOfBirth: userDOB,\n };\n}", "function Profile() {\r\n\tthis.fields = [\r\n\t\t\"LOGIN\", \"EMAIL\", \"NAME\", \"GENDER\", \"BIRTHDAY\", \"CITY\", \r\n \"ICQ\", \"URL\", \"PHOTO\", \"AVATAR\", \"ABOUT\", \"REGISTERED\", \"LAST_VISIT\",\r\n \"TELEGRAM_ID\"\r\n\t];\r\n\tthis.ServicePath = servicesPath + \"profile.service.php\";\r\n\tthis.Template = \"userdata\";\r\n\tthis.ClassName = \"Profile\";\t// Optimize?\r\n}", "function findOrCreate(accessToken, refreshToken, profile, done, conn) {\n loadUser(profile.id, conn, function(user) {\n if (user) {\n console.log(\"user exists with id \" + user.facebook_id);\n user.profile = profile;\n user.access_token = accessToken;\n user.refresh_token = refreshToken\n storeUser(user, conn, function(result) {\n done(null, user);\n });\n } else {\n console.log(\"user with id \" + profile.id + \" does not exist, make new\");\n createUser(accessToken, refreshToken, profile, done, conn);\n }\n });\n}", "function getUserProfile(id) {\n console.log(id);\n let profile = [{\n firstName: 'bran',\n lastName: 'Lee',\n email: 'bl@gmail.com',\n password: '1234',\n country: 'canada',\n birthDate: '10/11/1998',\n description: 'Test',\n post: '3',\n message: '5',\n like: '10',\n imageURL: 'https://randomuser.me/api/portraits/med/men/62.jpg'\n }];\n return profile;\n}", "function addUserToMap(userName){\nusersMap.push(userName);\n}", "function loadProfileCallback(obj) {\n profile = obj;\n window.profile = obj;\n // Filter the emails object to find the user's primary account, which might\n // not always be the first in the array. The filter() method supports IE9+.\n email = obj['emails'].filter(function(v) {\n return v.type === 'account'; // Filter out the primary email\n })[0].value; // get the email from the filtered results, should always be defined.\n var displayName = profile['displayName'];\n displayProfile(profile);\n //Create account in ubm db\n createUBMUser(email, displayName, profile);\n}", "loadProfile() {\n\t\tconst url = this.user.url;\n\t\treturn solid.fetch(url)\n\t\t\t.then(res => Promise.all([res.text(), res.headers.get('Content-Type')]))\n\t\t\t.then(([contents, contentType]) => loadProfile({ url, contents, contentType }))\n\t\t\t.then(profile => {\n\t\t\t\tObject.assign(this.user, profile);\n\t\t\t\tif (profile.accountName)\n\t\t\t\t\tthis.id = profile.accountName;\n\t\t\t\treturn profile;\n\t\t\t});\n\t}", "function createUser({username,email,type}){\n return prisma.user.create({data:{username,email,type}})\n}", "createUser(attributes) {\n return this._db('users').insert(attributes, '*').then(results => {\n //removing the hashed_password for safety\n delete results[0].hashed_password;\n return camelizeKeys(results[0]);\n });\n }", "async function createUser(\n firstName,\n lastName,\n username,\n occupation,\n state,\n city,\n zipcode,\n userId\n) {\n const userInf = new UserInformations({\n firstName,\n lastName,\n username,\n occupation,\n state,\n city,\n zipcode,\n userId,\n });\n const result = await userInf.save();\n console.log(result);\n}", "function createUser(username, password) {\n console.log(\"Create user\", username)\n return {\n \"id\": utils.UUID(),\n \"username\": username,\n \"password\": utils.hashPassword(password),\n \"createdAt\": Date.now()\n }\n}", "static async saveUser(userInfo) {\n const { fullName, username, email, gender, password, role } = userInfo;\n\n // hash password\n const hashedPassword = await bcrypt.hash(\n password,\n parseInt(process.env.SALT, 10)\n );\n const newUser = {\n ...userInfo,\n passkey: hashedPassword,\n };\n const user = (await User.create(newUser)).get({ plain: true });\n return user;\n }", "fetchProfile(context) {\n return new Promise((resolve, reject) => {\n service\n .getUser()\n .then(function(user) {\n if (user == null) {\n context.dispatch('signIn');\n context.commit('setProfile', null);\n return resolve(null);\n } else {\n context.commit('setProfile', user.profile);\n return resolve(user.profile);\n }\n })\n .catch(function(err) {\n context.commit('setError', err);\n return reject(err);\n });\n });\n }", "function generateUserData(){\n return {\n firstName: faker.name.firstName(),\n lastName: faker.name.lastName(),\n username: faker.internet.userName(),\n password: '123123',\n }\n}" ]
[ "0.6732075", "0.6704106", "0.6523785", "0.62657285", "0.61514395", "0.61436176", "0.6122447", "0.6119022", "0.6116389", "0.61005634", "0.60932815", "0.607823", "0.60726297", "0.6060197", "0.6051151", "0.60453403", "0.6027172", "0.6025027", "0.60161436", "0.599851", "0.5998496", "0.59970564", "0.59766054", "0.5963737", "0.5963591", "0.595208", "0.5944366", "0.59417987", "0.59198654", "0.59126306", "0.59041315", "0.5866911", "0.5863075", "0.586268", "0.585602", "0.58339214", "0.582328", "0.58112615", "0.5801692", "0.5798068", "0.57966125", "0.5796279", "0.5774266", "0.57706064", "0.5758225", "0.5749638", "0.5745083", "0.5741623", "0.57352215", "0.57154036", "0.5713888", "0.5695929", "0.5691577", "0.56902885", "0.5683209", "0.5681526", "0.56714314", "0.5669962", "0.5669279", "0.56511503", "0.5639705", "0.563662", "0.5629555", "0.5620225", "0.56182957", "0.56102115", "0.56068105", "0.56066173", "0.560283", "0.5602427", "0.560158", "0.55969924", "0.5593058", "0.5571802", "0.55716866", "0.55716777", "0.55716354", "0.5566533", "0.5564776", "0.5562797", "0.5553437", "0.5546951", "0.5544379", "0.554326", "0.55397356", "0.55377537", "0.55358225", "0.5535471", "0.5529201", "0.552445", "0.5524049", "0.5508349", "0.5499879", "0.54997665", "0.54989564", "0.5496726", "0.5492905", "0.5486706", "0.54831976", "0.5475191" ]
0.70402855
0
VALIDATE FORM FUNCTION Validates form input; ensures that user inputs all necessary information correctly before calculating results. Deploys error messages instructing user to make corrections where necessary. Fires when user clicks submit form.
function validateForm() { return true; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function processForm() {\n // validate elevation\n if ($('#mtnElevation').val() < 4003 || $('#mtnElevation').val() > 6288) {\n $('#alertMsg').html('Elevation must be between 4,003 and 6,288 feet.');\n $('#mtnElevation').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate effort\n if ($('#mtnEffort').val() === '') {\n $('#alertMsg').html('Please select an effort.');\n $('#mtnEffort').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate image\n if ($('#mtnImage').val() === '') {\n $('#alertMsg').html('Please enter an image name.');\n $('#mtnImage').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate lat / lng\n // Note: Can break into Lat and Lgn checks, and place cursor as needed\n var regex = /^([-+]?)([\\d]{1,2})(((\\.)(\\d+)(,)))(\\s*)(([-+]?)([\\d]{1,3})((\\.)(\\d+))?)$/;\n var latLng = `${$('#mtnLat').val()},${$('#mtnLng').val()}`;\n if (! regex.test(latLng)) {\n $('#alertMsg').html('Latitude and Longitude must be numeric.');\n $('#alertMsg').show();\n return false;\n }\n\n // Form is valid\n $('#alertMsg').html('');\n $('#alertMsg').hide();\n\n return true;\n }", "function validateForm() {\n validateFirstName();\n validateLastName();\n validateStreet();\n validateCity();\n validateZipCode();\n}", "function validateForm() {\n\n\tvar valid = true;\n\n\tif (!validateField(\"firstname\"))\n\t\tvalid = false;\n\n\tif (!validateField(\"lastname\"))\n\t\tvalid = false;\n\n\tif (!checkPasswords())\n\t\tvalid = false;\n\n\tif (!checkEmail())\n\t\tvalid = false;\n\n\tif (valid)\n\t\tsubmitForm();\n\n\t// Return false to make sure the HTML doesn't try submitting anything.\n\t// Submission should happen via javascript.\n\treturn false;\n}", "function validateForm() {\n\tvar flag = true;\n\t\n\t// Get the values from the text fields\n\tvar songName = songNameTextField.value;\n\tvar artist = artistTextField.value;\n\tvar composer = composerTextField.value;\n\t\n\t// A regular expression used to test against the values above\n\tvar regExp = /^[A-Za-z0-9\\?\\$'&!\\(\\)\\.\\-\\s]*$/;\n\t\n\t// Make sure the song name is valid\n\tif (songName == \"\" || !regExp.test(songName)) {\n\t\tflag = false;\n\t\talert(\"Please enter a song name. Name can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t// Make sure the artist is valid\n\telse if (artist == \"\" || !regExp.test(artist)) {\n\t\tflag = false;\n\t\talert(\"Please enter an artist. Artist can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t// Make sure the composer is valid\n\telse if (composer == \"\" || !regExp.test(composer)) {\n\t\tflag = false;\n\t\talert(\"Please enter a composer. Composer can include letters, numbers, and the special characters ?!$&'().-\");\n\t}\n\t\n\treturn flag;\n}", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst businessValue = business.value.trim();\n\tconst roleValue = role.value.trim();\n\tconst addressValue = address.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check business\n\tif (businessValue === \"\") {\n\t\tsetErrorFor(business, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(business);\n\t}\n\n\t// Check role\n\tif (roleValue === \"\") {\n\t\tsetErrorFor(role, \"Please select a role\");\n\t} else {\n\t\tsetSuccessFor(role);\n\t}\n\n\t// Check addresss\n\tif (addressValue === \"\") {\n\t\tsetErrorFor(address, \"Please enter a address\");\n\t} else {\n\t\tsetSuccessFor(address);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function validateForm(e) {\n 'use strict';\n\n //Handles window-generated events (i.e. non-user)\n if (typeof e == 'undefined') {\n e = window.event;\n }\n\n //Get form object references\n var firstName = U.$('firstName');\n var lastName = U.$('lastName');\n var userName = U.$('userName');\n var email = U.$('email');\n var phone = U.$('phone');\n var city = U.$('city');\n var state = U.$('state');\n var zip = U.$('zip')\n var terms = U.$('terms');\n\n\n //Flag variable\n var error = false;\n\n //Validate the first name using a regular expression\n if (/^[A-Z \\.\\-']{2,20}$/i.test(firstName.value)) {\n //Everything between / and / is the expression\n //Allows any letter A-Z (case insensitive)\n //Allows spaces, periods, and hyphens\n //Name must be 2-20 characters long\n\n //alert(\"Valid first name\");\n removeErrorMessage('firstName');\n }\n else {\n //alert(\"Invalid first name\");\n addErrorMessage(\n 'firstName',\n 'Invalid/missing first name'\n );\n error = true;\n }\n\n //Validate the last name using a regular expression\n\n //Validate the username using a validation function\n if (validateUsername(userName.value)) {\n removeErrorMessage('userName');\n }\n else {\n addErrorMessage(\n 'userName',\n 'username does not meet criteria'\n );\n error = true;\n }\n\n //Validate the email using a regular expression\n //Validate the phone using a regular expression\n //Validate the city using a regular expression\n //Validate the zip using a regular expression\n\n //Prevent form from resubmitting\n if (error) {\n if (e.preventDefault) {\n e.preventDefault();\n }\n else {\n e.returnValue = false;\n }\n }\n\n return false;\n\n} // End of validateForm() function.", "function validateForm(event) {\n // Prevent the browser from reloading the page when the form is submitted\n event.preventDefault();\n\n // Validate that the name has a value\n const name = document.querySelector(\"#name\");\n const nameValue = name.value.trim();\n const nameError = document.querySelector(\"#nameError\");\n let nameIsValid = false;\n\n if (nameValue) {\n nameError.style.display = \"none\";\n nameIsValid = true;\n } else {\n nameError.style.display = \"block\";\n nameIsValid = false;\n }\n\n // Validate that the answer has a value of at least 10 characters\n const answer = document.querySelector(\"#answer\");\n const answerValue = answer.value.trim();\n const answerError = document.querySelector(\"#answerError\");\n let answerIsValid = false;\n\n if (checkInputLength(answerValue, 10) === true) {\n answerError.style.display = \"none\";\n answerIsValid = true;\n } else {\n answerError.style.display = \"block\";\n answerIsValid = false;\n }\n\n // Validate that the email has a value and a valid format\n const email = document.querySelector(\"#email\");\n const emailValue = email.value.trim();\n const emailError = document.querySelector(\"#emailError\");\n const invalidEmailError = document.querySelector(\"#invalidEmailError\");\n let emailIsValid = false;\n\n if (emailValue) {\n emailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n emailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n if (checkEmailFormat(emailValue) === true) {\n invalidEmailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n invalidEmailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n // Validate that the answer has a value of at least 15 characters\n const address = document.querySelector(\"#address\");\n const addressValue = address.value.trim();\n const addressError = document.querySelector(\"#addressError\");\n addressIsValid = false;\n\n if (checkInputLength(addressValue, 15) === true) {\n addressError.style.display = \"none\";\n addressIsValid = true;\n } else {\n addressError.style.display = \"block\";\n addressIsValid = false;\n }\n\n // Display form submitted message if all fields are valid\n if (\n nameIsValid === true &&\n answerIsValid === true &&\n emailIsValid === true &&\n addressIsValid === true\n ) {\n submitMessage.style.display = \"block\";\n } else {\n submitMessage.style.display = \"none\";\n }\n}", "function processForm(){\t\n\t//set an error message variable (start as an empty string)\n\tvar msg = \"\";\n\t\n\t//validate the name! (call a function to do this)\n\tvar name = checkName();\n\t//check for a return...if it is returned, set error variable to false\n\tif(name == true){\n\t\tmsg\t= false;\n\t}\t\n\t\n\t//validate email!\n\tvar email = checkEmail();\n\t//check for a return...\n\tif(email == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//validate select menus\n\t//this is easier if we use separate functions, because here we only have to check for false (if they have entered something correct, no reason to change it). modifying the original functions to work both on submit and on change would be harder, though certainly possible. something for them to consider in the future.\n\tvar charType = theForm.charType;\n\t\n\tif(charType.options[charType.selectedIndex].value == \"X\"){\n\t\tcharType.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a character.</span>';\n\t\tmsg = false;\n\t}\n\t\n\tvar job = theForm.charJob;\n\t\n\tif(job.options[job.selectedIndex].value == \"X\"){\n\t\tjob.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a job.</span>';\n\t\tmsg = false;\n\t}\n\t\n\t\n\t/*validate checkbox*/\n\tvar spam = checkChecker();\n\tif(spam == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//finally, check for errors\n\tif(msg == false){\n\t\t//return false, normally, but we are always returning false\tfor testing purposes\n\t}else{\n\t\t//submit form\n\t}\n\t//alert(msg);\n\t//prevent form from submitting\n\treturn false;\n}", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst schoolValue = school.value.trim();\n\tconst levelValue = level.value.trim();\n\tconst skillValue = skill.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else if (isNaN(phoneValue)) {\n\t\tsetErrorFor(phone, \"Please enter a valid phone number\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check School\n\tif (schoolValue === \"\") {\n\t\tsetErrorFor(school, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(school);\n\t}\n\n\t// Check Level\n\tif (levelValue === \"\") {\n\t\tsetErrorFor(level, \"Please select a level\");\n\t} else {\n\t\tsetSuccessFor(level);\n\t}\n\n\t// Check LevSkills\n\tif (skillValue === \"\") {\n\t\tsetErrorFor(skill, \"Please enter a skill\");\n\t} else {\n\t\tsetSuccessFor(skill);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password2);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function formIsValid() {\n if (total_loan_box.value === \"\" || isNaN(total_loan_box.value)) {\n speakToUser(\"You must enter a valid decimal number for the <strong>Total Loan Amount</strong>.\");\n focusOnBox(\"total_loan\");\n return false;\n }\n\n if (interest_rate_box.value === \"\" || isNaN(interest_rate_box.value)) {\n speakToUser(\"You must enter a valid decimal number for the <strong>Yearly Interest Rate</strong>.\");\n focusOnBox(\"interest_rate\");\n return false;\n }\n\n if (loan_term_box.value === \"\" || isNaN(loan_term_box.value)) {\n speakToUser(\"You must enter a valid number of years for the <strong>Loan Term</strong>.\");\n focusOnBox(\"loan_term\");\n return false;\n }\n\n return true;\n}", "function formValidate() \n{\n // clear all errors, even if it's the first run\n clearErrors();\n var countErrors=0;\n // Is their first name using english characters and/or punctuation\n if (!nameCheck()) countErrors++;\n // Is their mobile number a valid Australian number\n if (!mobileCheck()) countErrors++;\n // Is credit card number between 14-19 digits\n if (!cardNoCheck()) countErrors++;\n // Is their credit card not yet expired\n if (!expiryCheck()) countErrors++;\n // Have they ordered any tickets\n if (!purchaseCheck()) countErrors++;\n // Block or allow submission depending on number of errors\n console.log(countErrors);\n return (countErrors==0);\n}", "function validateSubmission(form) {\n var alertMsg = \"\"; // Stores the message to display to user indicating which fields are entered incorrectly\n var checkEntry = true; // Is true if all fields are entered correctly, set to false if a field is entered incorrectly\n if (form.name.value == \"\") {\n //checks to see if Name field contains user input\n window.alert(\"No Name entered.\");\n return false;\n }\n if (form.price.value == \"\") {\n //checks to see if Price field contains user input, if not the validate function returns false\n window.alert(\"No Price entered.\");\n return false;\n }\n if (form.long1.value == \"\") {\n //checks to see if Longittude field contains user input, if not the validate function returns false\n window.alert(\"No Longittude entered.\");\n return false;\n }\n if (form.latt1.value == \"\") {\n //checks to see if Lattitude field contains user input, if not the validate function returns false\n window.alert(\"No Lattitude entered.\");\n return false;\n }\n\n if (!validateSpotName(form.name.value)) {\n //checks to see if Name entry is in the appropriate format\n var el = document.getElementsByName(\"name\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Name must be 5 characters long and cannot begin with a space or have consecutive spaces.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"name\")[0].style.backgroundColor = \"white\";\n }\n if (\n !validateDescription(form.description.value) &&\n form.description.value != \"\"\n ) {\n //checks to see if Description entry is in the appropriate format\n var el = document.getElementsByName(\"description\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += \"Description must be less than 300 characters.\\n\"; //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n checkEntry = false;\n } else {\n document.getElementsByName(\"description\")[0].style.backgroundColor =\n \"white\";\n }\n if (!validatePrice(form.price.value)) {\n //checks to see if Price entry is in the appropriate format\n var el = document.getElementsByName(\"price\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Price must contain only digits, a single decimal point and up to 2 digits following the decimal point.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"price\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.long1.value)) {\n //checks to see if Longittude entry is in the appropriate format\n var el = document.getElementsByName(\"long1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Longittude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"long1\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.latt1.value)) {\n //checks to see if Lattitude entry is in the appropriate format\n var el = document.getElementsByName(\"latt1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Lattitude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"latt1\")[0].style.backgroundColor = \"white\";\n }\n if (!checkEntry) {\n //if any of the input fields have an entry in an incorrect format\n window.alert(alertMsg); //displays an error message for each incorrect field to user\n return false; //the validate function returns fa;se\n }\n\n return true; //All input fields contain values in the correct format so the validate function returns true\n}", "function formValidation() {\n //* If validation of email fails, add the warning class to email input and set the display of warning message to inline.\n if (!validation.isEmailValid(email.value)) {\n email.classList.add(\"warning\");\n email.nextElementSibling.style.display = \"inline\";\n }\n //* If validation of name fails, add the warning class to name input and set the display of warning message to inline.\n if (!validation.isNameValid(name.value)) {\n name.classList.add(\"warning\");\n name.nextElementSibling.style.display = \"inline\";\n }\n /*\n * If validation of message fails, add the warning class to message text area and set the display of warning\n * message to inline\n */\n if (!validation.isMessageValid(message.value)) {\n message.classList.add(\"warning\");\n message.nextElementSibling.style.display = \"inline\";\n }\n /*\n *If validation of title fails, add the warning class to title input and set the display of warning\n *message to inline\n */\n\n if (!validation.isTitleValid(title.value)) {\n title.classList.add(\"warning\");\n title.nextElementSibling.style.display = \"inline\";\n }\n if (\n validation.isEmailValid(email.value) &&\n validation.isNameValid(name.value) &&\n validation.isTitleValid(title.valid) &&\n validation.isMessageValid(message.value)\n ) {\n return true;\n } else return false;\n}", "function validateForm(){\n // Set error catcher\n var error = 0;\n // Check name\n if(!validateName('reg_name')){\n document.getElementById('nameError').style.display = \"block\";\n error++;\n }\n // Validate email\n var x =document.getElementById('reg_email').value;\n if(!validateEmail(x)){\n document.getElementById('emailError').style.display = \"block\";\n error++;\n }\n // Validate animal dropdown box\n if(!validateSelect('Occupation')){\n document.getElementById('animalError').style.display = \"block\";\n error++;\n }\n if(!validatePassword('reg_pass')){\n document.getElementById('pass_Error').style.display = \"block\";\n error++;\n }\n // Don't submit form if there are errors\n if(error > 0){\n return false;\n }\n else if(error == 0){\n regfun();\n }\n }", "function formValidation(){\n var result;\n\n result = textValidation(firstName,fName);\n result = textValidation(middleName,mName) && result;\n result = textValidation(sirName,lName) && result;\n result = numberValidation(unitNum,unitNumber) && result;\n result = numberValidation(StreetNum,stNumber) && result;\n result = textValidation(streetName,stName) && result;\n result = textValidation(city,cityName) && result;\n result = postCodeValidation(postCode,pCode) && result;\n result = phoneValidation(phoneNumber,phoNumber) && result;\n result = userNameValidation(userName,uName) && result;\n result = password1Validation(password1,pWord) && result;\n result = password2Validation(password2,pWordC,password1) && result;\n if (result == false){\n alert(\"Submission Failed\")\n }\n else {\n alert(\"Submission was Successful\")\n }\n return result;\n}", "function formValidator() {\n //create object that will save user's input (empty value)\n let feedback = [];\n //create an array that will save error messages (empty)\n let errors = [];\n //check if full name has a value\n if (fn.value !== ``){\n //if it does, save it\n feedback.fname = fn.value; \n }else {\n //if it doesn't, crete the error message and save it\n errors.push(`<p>Invalid Full Name</p>`);\n }\n \n //for email\n if (em.value !== ``){\n feedback.email = em.value;\n //expression.test(String('my-email@test.com').toLowerCase()); \n }else {\n errors.push(`<p>Invalid Email</p>`);\n }\n\n //for message\n if (mes.value !== ``){\n feedback.message = mes.value;\n }else {\n errors.push(`<p>Write a comment</p>`)\n }\n \n //create either feedback or display all errors\n if (errors.length === 0) {\n console.log(feedback);\n }else {\n console.log(errors);\n }\n //close event handler\n}", "function validateForm()\n{\n // errorMessage holds all errors which may occur during validation and is shown in an alert at the end if there are\n // errors\n var errorMessage = \"\";\n // firstOffender is used to find the first error field so that the cursor can be placed there... see bottom of method\n var firstOffender = [];\n // valid is used to return a boolean to the form, if a true return, the form is saved, if false it is not saved\n var valid = true;\n // these 2 variables are used to get a value after comparison with the regexs and used later\n var email = check_email.test(document.userForm.email.value);\n var city = check_city.test(document.userForm.city.value);\n\n // the following if statements simply check if a field is empty, if it is the error \"no field\" is appended to the\n // error message\n if (document.userForm.fname.value == \"\")\n {\n errorMessage += \"no first name\" + \"\\n\";\n valid = false;\n firstOffender.push(\"firstname\");\n }\n if (document.userForm.lname.value == \"\")\n {\n errorMessage += \"no last name\" + \"\\n\";\n valid = false;\n firstOffender.push(\"lastname\");\n }\n if (document.userForm.email.value == \"\")\n {\n errorMessage += \"no email\" + \"\\n\";\n valid = false;\n firstOffender.push(\"emailField\");\n }\n // test regex against entered value, if result does not match the pattern, the if statement will evaluate to true and enter\n else if (!email)\n {\n errorMessage += \"not a valid email\" + \"\\n\";\n valid = false;\n firstOffender.push(\"emailField\");\n }\n if (document.userForm.phone.value == \"\")\n {\n errorMessage += \"no phone number\" + \"\\n\";\n valid = false;\n firstOffender.push(\"phoneNumber\");\n }\n if (document.userForm.city.value == \"\")\n {\n errorMessage += \"no city\" + \"\\n\";\n valid = false;\n firstOffender.push(\"cityField\");\n }\n // test regex against entered value, if result does not match the pattern, the if statement will evaluate to true and enter\n else if (!city)\n {\n errorMessage += \"not a valid city\" + \"\\n\";\n valid = false;\n firstOffender.push(\"cityField\");\n }\n alert(errorMessage);\n var focusError = document.getElementById(firstOffender[0]);\n focusError.focus();\n return valid;\n}", "function validate() {\n\t\t//Invaild entry responces.\n\t\tvar nameConf = \"Please provide your Name.\";\n\t\tvar emailConf = \"Please provide your Email.\";\n\t\tvar phoneConf = \"Please provide a valid Phone Number.\";\n\t\t\n\t\t//Regular Expression validation.\n\t\tvar phoneNumber = /^\\d{10}$/; //validate that the user enters a 10 digit phone number\n\t\n\t if(document.myForm.name.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = nameConf;\n\t document.myForm.name.focus();\n\t return false;\n\t }\n\t \n\t if(document.myForm.email.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = emailConf;\n\t document.myForm.email.focus();\n\t return false;\n\t }\n\t \n\t \tif(document.myForm.phone.value.match(phoneNumber) ) {\n\t document.getElementById(\"valConf\").innerHTML = phoneConf;\n\t document.myForm.phone.focus();\n\t return false;\n\t }\n\t} //form validation to confirm the form isn't empty ", "function formValidator(){\n \n // create object that will save user inputs (empty bucket)\n let feedback = {};\n // create array that will save error messages (empty bucket)\n let errors = [];\n \n // check if full name has a value\n if (fn.value !== \"\"){\n // if it does, save it\n feedback.fname = fn.value;\n } else {\n // if it does not, create the error message (and save it too)\n errors.push(\"<p>Please provide your full name</p>\");\n }\n \n // check if email has a value\n if (em.value !== \"\"){\n // if it does, save it\n feedback.email = em.value;\n } else {\n // if it does not, create the error message (and save it too)\n errors.push(\"<p>Please provide your email</p>\");\n }\n \n // check if message has a value\n // if it does, save it\n // if it does not, create the error message (and save it too)\n \n // create either feedback or display all errors\n \n if (errors.length ===0){\n console.log(feedback);\n }else{\n console.log(errors);\n }\n \n // close your event-handler\n }", "function validateForm() {\n clearPage(); // Removes previous popups\n\n // Alerts the user if they have submitted an input with no text\n if (document.forms[\"inputFood\"][\"food\"].value == \"\") {\n warningAlert.innerHTML = \"Please Provide a Dish\";\n warningAlert.classList.add(\"reveal\");\n return false;\n }\n getFood(document.forms[\"inputFood\"][\"food\"].value);\n}", "function validateForm() {\n\n //this variable will contain all data delivered by the form\n let data = {}\n\n //this variable will contain all the errors, if any where made while filing in the form\n let validationErrors = {}\n\n //let's link the path from which our data var will get the data which is the inputs\n data.firstName = document.querySelector('#firstName')\n data.lastName = document.querySelector('#lastName')\n data.email = document.querySelector('#email')\n data.textbox = document.querySelector('#textbox')\n\n //validation start\n\n //first name validation. if empty, length\n if (!data.firstName.value) {\n console.error('No first name value')\n validationErrors.firstName = 'Please enter your first name'\n\n } else if (!data.firstName.length > 2) {\n console.error('Name value too short')\n validationErrors.firstName = 'Your name is too short, please enter atleast two letters'\n console.info('First Name present')\n }\n\n\n //validate last name. if empty, length\n if (!data.lastName.value) {\n console.error('No Last name value')\n validationErrors.lastName = 'Please enter your first name'\n\n } else if (!data.lastName.length > 2) {\n console.error('Last name value too short')\n validationErrors.lastName = 'Your Last name is too short, please enter atleast two letters'\n console.info('Last Name present')\n }\n\n //validate email\n if (!data.email.value) {\n console.error('no email value')\n validationErrors.email = 'please enter your Email';\n } else {\n console.info('Email present')\n //the email part of the form is not empty, we should still check if the mail contains a valid combination\n\n let emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;\n //test the mail now. if the value is valid or not\n if (!emailRegExp.test(data.email.value)) {\n validationErrors.email = 'Invalid email address'\n }\n }\n\n\n //validate textbox\n if (!data.textbox.value) {\n console.error('no value in textbox')\n validationErrors.textbox = 'please enter a message'\n } else if (!data.textbox.length > 3) {\n console.error('textbox value too short')\n validationErrors.lastName = 'your text is too short!'\n console.info('Last Name present')\n }\n //call the functions. if we have errors we will implement them in the DOM. else the \n\n //check if the errors object has data \n if (Object.keys(validationErrors).length > 0) {\n console.log('error')\n displayErrors(validationErrors, data)\n } else {\n console.log('no errors found');\n sendForm(data)\n }\n\n }", "function validateForm(){\r\n\r\n\tvar fn= document.forms[\"myform\"][\"fname\"].value;\r\n\tvar ln= document.forms[\"myform\"][\"lname\"].value;\r\n\tvar eml= document.forms[\"myform\"][\"email\"].value;\r\n\tvar mbl= document.forms[\"myform\"][\"mobile\"].value;\r\n\tvar trip= document.forms[\"myform\"][\"trip\"].value;\r\n\tvar prsn= document.forms[\"myform\"][\"person\"].value;\r\n\t\r\n\r\n\r\n\tif(fn == \"\"){\r\n\t\talert(\"Please enter First Name\");\r\n\t\treturn false;\r\n\t}\r\n\tif(ln == \"\"){\r\n\t\talert(\"Please enter last Name\");\r\n\t\treturn false;\r\n\t}\r\n\tif(eml == \"\"){\r\n\t\talert(\"Please enter Email-id\");\r\n\t\treturn false;\r\n\t}\r\n\tif(mbl == \"\"){\r\n\t\talert(\"Please enter Mobile Number\");\r\n\t\treturn false;\r\n\t}\r\n\tif(trip == \"\"){\r\n\t\talert(\"Select Your trip\");\r\n\t\treturn false;\r\n\t}\r\n\tif(prsn == \"\"){\r\n\t\talert(\"select persons for trip\");\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}", "function validateForm(event) {\n\n\t// Array to contain all error messages\n\tvar errorMessages = Array();\n\n\t// If Name is empty\n\tif(!contactForm['fName'].value) {\n\t\terrorMessages.push('* Please enter Full Name');\n\t}\n\n\t// If Telephone is empty\n\tif(!contactForm['tel'].value) {\n\t\terrorMessages.push('* Please enter telephone number');\n\t}\n\n\t// If email is empty\n\tif(!contactForm['email'].value) {\n\t\terrorMessages.push('* Please enter Email');\n }\n \n // If message is empty\n\tif(!contactForm['message'].value) {\n\t\terrorMessages.push('* Please enter your message');\n\t}\n\n\t//--Replaced--//\n\n\t//--Replace--//\n\n\t\n // Show error messages\n\tdisplayErrors(errorMessages);\n \n\t// If there are errors\n\tif(errorMessages.length) {\n\t\t// Stop the form from submitting\n\t\treturn false;\n\t} \n \n}", "function validateForm()\n\t\t{\n\t\t\tvar vendorNumber = document.myForm.vendorNo.value;\n\t\t\tvar vName = document.myForm.vendorName.value;\n\t\t\tvar city1 = document.myForm.city.value;\n\t\t\tvar cellNumber = document.myForm.phNumber.value;\t\n\t\t\tvar fax = document.myForm.faxNumber.value;\n\t\t\tvar Postal = document.myForm.postal.value;\t\t\t\n\t\t\tvar streetno1 = document.myForm.streetNumber1.value;\n\t\t\tvar streetname1=document.myForm.streetName1.value;\n\t\t\t\n\t\t\tvar Province=document.myForm.province;\n\t\t\tvar Country=document.myForm.country;\n\t\t\t\t\t\t\n\t\t\tvar message=\"\";\n\t\t\t\n\t\n\t// validates vendor Number\t\t\n\tif(vendorNumber==\"\"||vendorNumber==null)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.vendorNo.focus();\n\t\t\t\t\t\tdocument.myForm.vendorNo.select();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your Vendor Number.\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isNaN(vendorNumber))\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.vendorNo.focus();\n\t\t\t\t\t\tdocument.myForm.vendorNo.select();\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tmessage+=\"Vendor Number must be in numbers.\\n\";\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\t// validates vendor's name\t\t\n\t\t\n\t\tif (vName == \"\"||vName == null)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.vendorName.focus();\n\t\t\t\t\t\tdocument.myForm.vendorName.select();\n\t\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your vendor Name\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isNaN(vName))\n\t\t\t\t{\n\t\t\t\t\tvName=vName.trim();\n\t\t\t\t\tvName=vName.toLowerCase();\n\t\t\t\t\tvName=vName.charAt(0).toUpperCase()+vName.slice(1);\n\t\t\t\t\tvendorName.value=vName;\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.vendorName.focus();\n\t\t\t\t\t\tdocument.myForm.vendorName.select();\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tmessage+=\"vendor Name should not contain numbers\\n\";\n\t\t\t\t}\n\t\t\t\t\n\t\t\t}\n\t// validates street no\t\t\t\n\n\t\t\tif(streetno1==\"\"||streetno1==null)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.streetNumber1.focus();\n\t\t\t\t\t\tdocument.myForm.streetNumber1.select();\n\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your Street Number.\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tif(isNaN(streetno1))\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.streetNumber1.focus();\n\t\t\t\t\t\tdocument.myForm.streetNumber1.select();\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tmessage+=\"Street Number must be in numbers.\\n\";\n\t\t\t\t}\t\t\t\t\t\n\t\t\t}\n\n\t\t// validates street name\n\t\tif(streetname1==\"\"||streetname1==null)\n\t\t{\n\t\t\tif(message==\"\")\n\t\t\t{\n\t\t\t\tdocument.myForm.streetName1.focus();\n\t\t\t\tdocument.myForm.streetName1.select();\n\t\t\t}\n\t\t\t\tmessage+=\"Please enter your street Name.\\n\";\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(isNaN(streetname1))\n\t\t\t\t{\n\t\t\t\t\tstreetname1=streetname1.trim();\n\t\t\t\t\tstreetname1=streetname1.toLowerCase();\n\t\t\t\t\tstreetname1=streetname1.charAt(0).toUpperCase()+streetname1.slice(1);\n\t\t\t\t\tstreetName1.value=streetname1;\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.streetname1.focus();\n\t\t\t\t\t\tdocument.myForm.streetname1.select();\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tmessage+=\"Street Name should not contain numbers\\n\";\n\t\t\t\t}\t\t\t\n\t\t}\n\t\n\t\t\n\t\t// validates city name\t\t\n\t\tif(city1==\"\"||city1==null)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.city.focus();\n\t\t\t\t\tdocument.myForm.city.select();\n\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your City.\\n\";\n\t\t\t}\n\t\tif(city1.length<=3)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.city.focus();\n\t\t\t\t\tdocument.myForm.city.select();\n\t\t\t\t}\n\t\t\t\tmessage+=\"There must be minimum 3 characters in City.\\n\";\n\t\t\t}\n\t\t\telse\n\t\t\t{\t\t\t\t\n\t\t\t\tif(isNaN(city1))\n\t\t\t\t{\n\t\t\t\tcity1=city1.trim();\n\t\t\t\tcity1=city1.toLowerCase();\n\t\t\t\tcity1=city1.charAt(0).toUpperCase()+city1.slice(1);\n\t\t\t\tcity.value=city1;\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.city.focus();\n\t\t\t\t\t\tdocument.myForm.city.select();\n\t\t\t\t\t}\t\t\t\t\t\n\t\t\t\t\tmessage+=\"City should not contain numbers\\n\";\n\t\t\t\t}\t\t\t\t\n\t\t\t}\n\t\t\n\t\t// checks if the country is selected\n\t\tif(Country.value==\"Default\")\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.Country.focus();\n\t\t\t\t}\n\t\t\t\tmessage+=\"Please select your Country.\\n\";\n\t\t\t}\t\t\t\t\n\t\t\n\t\t// checks if the province is selected\n\t\tif(Province.value==\"Default\")\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.province.focus();\n\t\t\t\t}\n\t\t\t\tmessage+=\"Please select your Province.\\n\";\n\t\t\t}\t\t\t\t\n\t\t\n\t\t// validates postal code\n\t\tif(Postal==\"\" || Postal==null)\n\t\t\t{\n\t\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.postal.focus();\n\t\t\t\t\tdocument.myForm.postal.select();\n\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your Postal Code.\\n\";\n\t\t\t}\n\t\telse\n\t\t\t{\n\t\t\t\tif(Postal.length!=6)\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\tdocument.myForm.postal.focus();\n\t\t\t\t\tdocument.myForm.postal.select();\n\t\t\t\t\t}\n\t\t\t\t\tmessage+=\"There must be minimum 6 characters in Postal Code without Spaces.\\n\";\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tvar checkpostal=/^[A-Y][0-9][A-Y][0-9][A-Y][0-9]$/i;\n\t\t\t\t\t\t\n\t\t\t\t\tPostal=Postal.trim();\n\t\t\t\t\tPostal=Postal.toUpperCase();\n\t\t\t\t\t\n\t\t\t\t\tif(Postal.match(checkpostal))\n\t\t\t\t\t{\n\t\t\t\t\t\tpostal.value=Postal;\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t\t{\n\t\t\t\t\t\tdocument.myForm.postal.focus();\n\t\t\t\t\t\tdocument.myForm.postal.select();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tmessage+=\"Please write the Postal Code in correct Format \\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\n\n\t\t// validates cellnumber\n\t\tvar checknumber=/^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;\n\t\t\tif(cellNumber==\"\"||cellNumber==null)\n\t\t\t{\n\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.phNumber.focus();\n\t\t\t\t\n\t\t\t\t}\n\t\t\tmessage+=\"Please enter your Phone number\\n\";\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcellNumber=cellNumber.trim();\n\t\t\t\tif(cellNumber.match(checknumber))\n\t\t\t\t{\n\t\t\t\t\t\tphNumber.value=cellNumber;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\tdocument.myForm.phNumber.focus();\n\t\t\t\t\t\t\tdocument.myForm.phNumber.select();\n\t\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your Phone number in a correct format.\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t// validates fax number\n\t\tvar checknumber=/^\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;\n\t\t\tif(fax==\"\"||fax==null)\n\t\t\t{\n\t\t\tif(message==\"\")\n\t\t\t\t{\n\t\t\t\t\tdocument.myForm.faxNumber.focus();\n\t\t\t\t\n\t\t\t\t}\n\t\t\tmessage+=\"Please enter your Fax number\\n\";\t\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tfax=fax.trim();\n\t\t\t\tif(fax.match(checknumber))\n\t\t\t\t{\n\t\t\t\t\t\tfaxNumber.value=fax;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tif(message==\"\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\tdocument.myForm.faxNumber.focus();\n\t\t\t\t\t\t\tdocument.myForm.faxNumber.select();\n\t\t\t\t\t}\n\t\t\t\tmessage+=\"Please enter your Fax number in a correct format.\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif(message!=\"\")\n\t\t\t\t{\n\t\t\t\t\talert(message);\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t}", "function validate_form() {\n valid = true;\n\n if (document.form.age.value == \"\") {\n alert(\"Please fill in the Age field.\");\n valid = false;\n }\n\n if (document.form.heightFeet.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.weight.value == \"\") {\n alert(\"Please fill in the Weight field.\");\n valid = false;\n }\n\n if (document.form.position.selectedIndex == 0) {\n alert(\"Please fill in the Position field.\");\n valid = false;\n }\n\n if (document.form.playingStyle.selectedIndex == 0) {\n alert(\"Please fill in the Playing Style field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Maximum Price field.\");\n valid = false;\n }\n\n return valid;\n}", "function validateForm(){\n\t\n\tvar boo1 = validateLabPerson();\n\tvar boo2 = validateBioPerson();\n\tvar boo3 = validatePI();\n\tvar boo4 = validateBillTo();\n\tvar boo5 = validateRunType();\n\n\tvar boo6 = validateAllTables();\n//\tvar boo6 = true;\n\n\tvar boo7 = validateDate();\n\tvar boo8 = validateIAccept();\n\n\tvar boo9 = validateConcentrationUnit();\n\tvar boo10 = validateTubesAndLanes();\n\t\n//\talert(\"boo1 = \" + boo1 + \" boo2 = \" + boo2 + \" boo3 = \" + boo3 + \" boo4 = \" + boo4 +\" boo5 = \" + boo5 +\" boo6 = \" + boo6 + \" boo7 = \" + boo7 + \" boo8 = \" + boo8 + \" boo9 = \" + boo9 + \" boo10 = \" + boo10);\n\tif (boo1 && boo2 && boo3 && boo4 && boo5 && boo6 && boo7 && boo8 && boo9 && boo10){\t\n//\tif(validateLabPerson() && validateBioPerson() && validatePI() && validateBillTo() && validateRunType() && validateTable()){\n\t\t//insert fields used to generate csv\n\t\tinsertTableSize();\t\t\t\t\t// insert size of all table - used when generating csv file\n\t\tgenerateOrderNoteID();\t\t\t\t// insert orderNoteID\n\t\taddPI2TubeTag();\t\t\t\t\t// indsæt \"de tre tegn\" (fra PI) i tubetaggen.\n\t\tsetVersion();\t\t\t\t\t\t// insert the version number in the hidden field.\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n\t\n\treturn false;\n}", "function validateForm(event) {\n\n //prevents default event action\n event.preventDefault();\n\n\n// checking if the input value is 1 character or more\n if (checkLength(firstName.value, 0)) {\n firstNameError.style.display = \"none\";\n } else {\n firstNameError.style.display = \"block\";\n }\n// checking if the input value is 3 characters or more\n if (checkLength(lastName.value, 2)) {\n lastNameError.style.display = \"none\";\n } else {\n lastNameError.style.display = \"block\";\n }\n// checking if the input value is a valid email address\n if (validateEmail(email.value)) {\n emailError.style.display = \"none\";\n } else {\n emailError.style.display = \"block\";\n }\n// checking if the input value is 7 characters or more\n if (checkLength(subject.value, 6)) {\n subjectError.style.display = \"none\";\n } else {\n subjectError.style.display = \"block\";\n }\n// checking if the input value is 15 characters or more\n if (checkLength(message.value, 14)) {\n messageError.style.display = \"none\";\n } else {\n messageError.style.display = \"block\";\n }\n}", "function isValidUpdateForm() {\n\tvar name = $(\"#name-update\").val();\n\tvar date = $(\"#date-update\").val();\n\tvar score = $(\"#scores-update\").val();\n\t\n\tvar checkName = isValidName(name);\n\tvar checkDate = isValidDate(date);\n\tvar checkScore = isValidScore(score);\n\t\n\t$(\"#invalid-name-update\").html(\"\");\n\t$(\"#invalid-date-update\").html(\"\");\n\t$(\"#invalid-score-update\").html(\"\");\n\t\n\tif (!checkName || !checkDate || !checkScore) {\n\t\tif (!checkName) {\n\t\t\t$(\"#invalid-name-update\").html(\"Invalid student's name\");\n\t\t}\n\t\tif (!checkDate) {\n\t\t\t$(\"#invalid-date-update\").html(\"Invalid student's date\");\n\t\t}\n\t\tif (!checkScore) {\n\t\t\t$(\"#invalid-score-update\").html(\"Invalid student's score\");\n\t\t}\n\t\treturn false;\n\t}\n\treturn true;\n}", "function formValidation()\n{\n let principalCheck = document.forms[\"mortgageForm\"][\"principalAmount\"].value;\n if (isNaN(principalCheck) == true)\n {\n alert(\"Principal value must be a number\");\n return false;\n }\n else if (principalCheck < 0)\n {\n alert(\"Principal value must be positive\");\n return false;\n }\n let interestCheck = document.forms[\"mortgageForm\"][\"interestRate\"].value\n if (isNaN(interestCheck) == true)\n {\n alert(\"Interest value must be a number\");\n return false;\n }\n else if (interestCheck < 0)\n {\n alert(\"Interest rate must be positive\");\n return false;\n }\n else if (interestCheck > 100)\n {\n alert(\"Interest rate must be below 100%\");\n return false;\n }\n let termCheck = document.forms[\"mortgageForm\"][\"mortgageLength\"].value\n if (isNaN(termCheck) == true)\n {\n alert(\"Term length must be a number\");\n return false;\n }\n else if (termCheck < 5)\n {\n alert(\"Mortgage length must be at least five years\");\n return false;\n }\n else if (termCheck > 50)\n {\n alert(\"Mortgage length cannot be greater than fifty years\");\n return false;\n }\n}", "function validateForm(the_form) {\n\tvalidForm = true;\t\t// assume the form is valid\n\tfirstError = null;\t\t// this will be the first element in the form that in not valid, if any. This var will allow the script to set the focus on that element\n\terrorstring = '';\t\t// a message used for non-W3C DOM browsers \n\t\n\t// should errors trigger a change in td color?\n\t// if the input_error_td form element is present \n\tif (the_form[input_error_td]) {\n\t\tchange_td_color = true;\t\n\t}\n\n\t\n\t// validate required fields\n\t// if there are required fields\n\tif (the_form[input_required_fields]) {\n\t\tvalidateFields_Required(the_form);\n\t}\n\n\t// validate numeric fields\n\t// if there are numeric fields\n\tif (the_form[input_numeric_fields]) {\n\t\tvalidateFields_Numeric(the_form)\n\t}\n\t\n\t// validate numeric range values\n\tvar numeric_range_name = input_numeric_range + '[0]';\t// the format of the first numeric range input name is the value of input_numeric_range plus [0], \"numeric_range[0]\". Remeber, this is a string, not really an array\n\tif (the_form[numeric_range_name]) {\n\t\tvalidateFields_IsInNumericRange(the_form);\n\t}\n\t\n\t\n\t// validate email fields\n\t// if there are email fields\n\tvar email_fields = new Array();\n\tif (the_form[input_email_fields]) {\n\t\t// the form passed can have a hidden field with a comma separated list of email fields to validate\n\t\t// split the value on the commas and pass that array\n\t\temail_fields = the_form[input_email_fields].value.split(',');\n\t\tvalidateFields_Email( the_form, email_fields );\n\t} else if (the_form.email) {\n\t\t// most forms just have one email field to validate. Look for an element named 'email'\n\t\temail_fields[0] = the_form.email.name;\n\t\tvalidateFields_Email( the_form, email_fields );\n\t}\n\t\n\t\n\t\n\t// if the browser is old, just alert a string\n\tif (!W3CDOM_validate_forms) {\n\t\talert(errorstring);\n\t}\n\t/*\n\t// this sets the focus of a form element, causing the cursor to move to the element. It is a bit buggy\n\tif (firstError) {\n\t\t//firstError.focus();\n\t}\n\t*/\n\t\n\t// alert a general message to indicate the form cannot be submitted\n\tif (!validForm) {\n\t\talert(invalid_form_message);\n\t}\n\n\t// return true or false\n\treturn validForm;\n}", "function validateFormInputs() {\n var emailPattern = new RegExp(\n /^((\"[\\w-\\s]+\")|([\\w-]+(?:.[\\w-]+)*)|(\"[\\w-\\s]+\")([\\w-]+(?:.[\\w-]+)*))(@((?:[\\w-]+.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:.[a-z]{2})?)$)|(@\\[?((25[0-5]\\.|2[0-4][0-9]\\.|1[0-9]{2}.|[0-9]{1,2}.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\\]?$)/i\n );\n var phonePattern = new RegExp(\n /^[+]?[(]?[0-9]{3}[)]?[-\\s.]?[0-9]{3}[-\\s.]?[0-9]{4,6}$/im\n );\n // validate name\n if (messageFormState.name === undefined || messageFormState.name === \"\") {\n return \"Please Enter a Valid Name on the Form\";\n } else if (!emailPattern.test(messageFormState.email)) {\n return \"Please Enter a Valid Email on the form\";\n } else if (!phonePattern.test(messageFormState.phone)) {\n return \"Please Enter a Valid Phone Number on the form\";\n }\n return \"\";\n }", "function validateForm() {\n\t\n\tvar error = 0;\n\t$('input').each(function(x,y) {\n\t\tvar val = $(y).val();\n\t\tif(!validate(y.name, val)) {\n\t\t\t$(y).css('border', 'solid 1px red')\n\t\t\terror = 1;\n\t\t} else {\n\t\t\t$(y).css('border', 'solid 1px 888');\n\t\t}\n\t});\n\t\n\t$('textarea').each(function(x,y) {\n\t\tvar val = $(y).val();\n\t\tif(!validate(y.name, val)) {\n\t\t\t$(y).css('border', 'solid 1px red')\n\t\t\terror = 1;\n\t\t} else {\n\t\t\t$(y).css('border', 'solid 1px 888');\n\t\t}\n\t});\n\t\n\tif(error === 1) {\n\t\treturn false;\n\t}\n}", "function validateSubmitResults() {\n\tconsole.log(\"Calling from validator\");\n\tvar validated; \n // Select only the inputs that have a parent with a required class\n var required_fields = $('.required');\n // Check if the required fields are filled in\n \trequired_fields.each(function(){\n \t\t// Determite what type of input it is, and display appropriate alert message\n\t\tvar field, msg_string;\n \tif( $(this).hasClass('checkbox_container') || $(this).hasClass('radio_container') ){\n \t\tfield = $(this).find('input:checked');\n \t\tmsg_string = \"Please select an option\";\n \t}else{\n \t\tfield = $(this).find('input:text, textarea');\n \t\tmsg_string = \"Please fill in the field\";\n \t} \n\t\t// For the checkbox/radio check the lenght of selected inputs,\n\t\t// at least 1 needs to be selected for it to validate \n\t\t// And for the text, check that the value is not an empty string\n \t\tif( (field.length <= 0) || !field.val() ){\n \t\t\tconsole.log(\"Field length: \" + field.length);\n \t\t\t$(this).addClass('alert alert-warning');\n \t\t\tvar msg = addParagraph(msg_string, \"validator-msg text-danger\");\n \t\t\t// Check if there is already an alert message class, \n \t\t\t// so that there wouldn't be duplicates\n\t\t\tif( $(this).find('p.validator-msg').length == 0 ){\n \t$(this).find('.section-title').before(msg);\n }\n validated = false;\n \t\t}\n \t\telse{\n \t\t\t// Remove the alert classes and message\n \t\t\t$(this).find('p.validator-msg').detach();\n $(this).removeClass('alert-warning').removeClass('alert'); \n validated = true;\n \t\t}\n \t\t// Sanitize the inputs values\n \t\tif( validated ){\n \t\t\tvar answer = sanitizeString(field.val());\n \t\t\tfield.val(answer);\n \t\t}\n \t});\n\n\treturn validated;\n}", "function validateForm() {\n let res = true;\n //Valida cada uno de los campos por regex\n for (let key in regexList) {\n if (!evalRegex(key, document.forms[formName][key].value)) {\n setMsg(key, fieldList[key].error);\n res = false;\n } else setMsg(key, '');\n }\n\n //Valida la fecha de contrato\n if (!validateDate()) {\n setMsg('fechaContrato', fieldList['fechaContrato'].error);\n res = false;\n } else setMsg('fechaContrato', '');\n\n //Valida el salario introducido\n if (!validateSalary()) {\n setMsg('salario', fieldList['salario'].error);\n res = false;\n } else setMsg('salario', '');\n\n //Valida que la contraseña y la confirmacion sean iguales\n if (document.forms[formName]['passwordReply'].value != document.forms[formName]['password'].value) {\n setMsg('passwordReply', fieldList['passwordReply'].error);\n res = false;\n } else setMsg('passwordReply', '');\n\n //Valida si el usuario ya esta registrado\n if (validateUser(document.forms[formName]['usuario'].value)) {\n setMsg('usuario', 'El usuario ya ha sido registrado');\n res = false;\n }\n\n return res;\n}", "function validateForm() {\n isFormValid = true;\n\n validateName();\n validateEmail();\n validateDemand();\n validateOptions();\n\n if (isFormValid) {\n submit.disabled = false;\n } else {\n submit.disabled = true;\n\n }\n}", "function formValidate(form) {\n function camelCase(string) {\n string = string||'';\n string = string.replace(/\\(|\\)/,'').split(/-|\\s/);\n var out = [];\n for (var i = 0;i<string.length;i++) {\n if (i<1) {\n out.push(string[i].toLowerCase());\n } else {\n out.push(string[i][0].toUpperCase() + string[i].substr(1,string[i].length).toLowerCase());\n }\n }\n return out.join('');\n }\n\n function nullBool(value) {\n return (value);\n }\n\n function getGroup(el) {\n return {\n container: el.closest('.form-validate-group'),\n label: $('[for=\"' + el.attr('id') + '\"]'),\n prompt: el.closest('.form-validate-group').find('.form-validate-prompt')\n }\n }\n\n function isValid(el) {\n function getType() {\n var attr = camelCase(el.attr('id')).toLowerCase();\n var tag = (el.attr('type') === 'checkbox') ? 'checkbox' : el[0].tagName.toLowerCase();\n function type() {\n var _type = 'text';\n if (attr.match(/zip(code|)/)) {\n _type = 'zipCode';\n } else if (attr.match(/zippostal/)) {\n _type = 'zipPostal';\n } else if (attr.match(/(confirm|)(new|old|current|)password/)) {\n _type = 'password'\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)email/)) {\n _type = 'email';\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)(phone)(number|)/)) {\n _type = 'phone';\n } else if (attr.match(/merchantid/)) {\n _type = 'merchantId';\n } else if (attr.match(/marketplaceid/)) {\n _type = 'marketplaceId';\n } else if (attr.match(/number/)) {\n _type = 'number';\n }\n return _type;\n }\n if (tag === 'input' || tag === 'textarea') {\n return type();\n } else {\n return tag;\n }\n } // Get Type\n var string = el.val()||'';\n var exe = {\n text: function () {\n return (string.length > 0);\n },\n password: function () {\n return (string.length > 6 && nullBool(string.match(/^[\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)a-zA-Z0-9_-]+$/)));\n },\n zipCode: function () {\n return (nullBool(string.match(/^[0-9]{5}$/)));\n },\n zipPostal: function () {\n return (nullBool(string.match(/^([0-9]{5}|[a-zA-Z][0-9][a-zA-Z](\\s|)[0-9][a-zA-Z][0-9])$/)));\n },\n email: function () {\n return (nullBool(string.match(/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\\.([a-z]{2}|[a-z]{3})/)));\n },\n merchantId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n return ((match) && (match[0].length > 9 && match[0].length < 22));\n },\n marketplaceId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n var length = {'United States of America':13}[region()];\n return ((match) && (match[0].length === length));\n },\n select: function () {\n return (el[0].selectedIndex > 0);\n },\n checkbox: function () {\n return el[0].checked;\n },\n phone: function () {\n return (nullBool(string.replace(/\\s|\\(|\\)|\\-/g,'').match(/^([0-9]{7}|[0-9]{10})$/)));\n },\n number: function () {\n return nullBool(string.match(/^[0-9\\.\\,]+$/));\n }\n }\n return exe[getType()]();\n }; // contentsValid\n\n return {\n confirm: function (el) {\n\n function condition(el) {\n var bool = dingo.get(el).find('form-validate').condition||false;\n if (bool && el.val().length > 0) {\n return el;\n } else {\n return false;\n }\n }\n\n function dependency(el) {\n // Needs to use recursion to climb the dependency tree to determine whether or not\n // the element is dependent on anything\n var dep = $('#' + dingo.get(el).find('form-validate').dependency);\n if (dep.size() > 0) {\n return dep;\n } else {\n return false;\n }\n }\n\n function confirm(el) {\n var match = $('#' + dingo.get(el).find('form-validate').confirm);\n if (match.size()) {\n return match;\n } else {\n return false;\n }\n }\n\n function normal(el) {\n var check = dingo.get(el).find('form-validate');\n var out = true;\n var attr = ['condition','dependency','confirm'];\n $.each(attr,function (i,k) {\n if (typeof check[k] === 'string' || check[k]) {\n out = false;\n }\n });\n return out;\n }\n\n function validate(el) {\n var group = getGroup(el);\n function exe(el,bool) {\n if (bool) {\n el.removeClass('_invalid');\n group.label.addClass('_fulfilled');\n animate(group.prompt).end();\n group.prompt.removeClass('_active');\n } else {\n el.addClass('_invalid');\n group.label.removeClass('_fulfilled');\n }\n }\n return {\n condition: function () {\n exe(el,isValid(el));\n },\n dependency: function (match) {\n if (normal(match) || condition(match)) {\n exe(el,isValid(el));\n }\n },\n confirm: function (match) {\n if (el.val() === match.val()) {\n exe(el,true);\n } else {\n exe(el,false);\n }\n },\n normal: function () {\n exe(el,isValid(el));\n }\n }\n }\n\n if (condition(el)) {\n validate(el).condition();\n } else if (dependency(el)) {\n validate(el).dependency(dependency(el));\n } else if (confirm(el)) {\n validate(el).confirm(confirm(el));\n } else if (normal(el)) {\n validate(el).normal();\n }\n },\n get: function () {\n return form.find('[data-dingo*=\"form-validate\"]').not('[data-dingo*=\"form-validate_submit\"]');\n },\n init: function (base, confirm) {\n if (el.size() > 0) {\n parameters.bool = bool;\n formValidate(el).fufilled();\n return formValidate(el);\n } else {\n return false;\n }\n },\n is: function () {\n return (form.find('.form-validate').size() < 1);\n },\n check: function () {\n var el;\n formValidate(form).get().each(function () {\n formValidate(form).confirm($(this));\n });\n return form.find('._invalid');\n },\n submit: function (event) {\n var out = true;\n var requiredField = formValidate(form).check();\n if (requiredField.size() > 0) {\n requiredField.each(function () {\n var group = getGroup($(this));\n group.prompt.addClass('_active');\n group.prompt.css('top',group.container.outerHeight() + 'px');\n if (typeof animate === 'function') {\n animate(group.prompt).start();\n }\n })\n if (requiredField.eq(0).closest('[class*=\"modal\"]').size() < 1) {\n if (typeof animate === 'function') {\n if (!dingo.isMobile()) { \n animate(requiredField.eq(0)).scroll(); \n }\n }\n requiredField.eq(0).focus();\n }\n out = false;\n }\n return out;\n }\n }\n}", "function MM_validateForm() { //v4.0\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;\n for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n';\n } else if (test!='R') { num = parseFloat(val);\n if (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\n if (test.indexOf('inRange') != -1) { p=test.indexOf(':');\n min=test.substring(8,p); max=test.substring(p+1);\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\n } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\n } if (errors) alert('The following error(s) occurred:\\n'+errors);\n document.MM_returnValue = (errors == '');\n}", "function validateForm() {\n var formValid = checkValidity($('form'))\n $('.form-control').removeClass('border-danger text-danger');\n\n $('.form-control').each(function() {\n let inputValid = checkValidity($(this))\n if ( ($(this).prop('required') && ($(this).val().length == 0 || $(this).val() == \" \")) // test for blank while required\n || ($(this).hasClass('check-url') && !validateURL($(this).val())) // test for check URL\n ) {\n inputValid = false;\n formValid = false;\n }\n\n // Test for BCH address\n if ($(this).hasClass('check-bch-address')) {\n if (bchaddr.isValidAddress($(this).val())) {\n if (bchaddr.isLegacyAddress($(this).val())) {\n // isLegacyAddress throws an error if it is not given a valid BCH address\n // this explains the nested if\n inputValid = false;\n formValid = false;\n }\n } else {\n inputValid = false;\n formValid = false;\n }\n }\n\n let showError = $(this).parent().find(\".show-error-on-validation\")\n\n // After all validation\n if (!inputValid) {\n \n $(this).addClass('border-danger text-danger');\n \n if (showError.length) {\n showError.removeClass(\"d-none\")\n }\n\n } else {\n if (showError.length) {\n showError.addClass(\"d-none\")\n }\n }\n });\n\n // Submit if everything is valid\n if (formValid) {\n return true\n } else {\n $(\"#error\").removeClass(\"d-none\");\n $(\"#error\").text(\"Some fields are incorrect.\")\n return false\n }\n}", "function validateForm(event) {\n // Prevent default form actions\n event.preventDefault();\n\n // Check full name\n if (checkLength(fullName.value, 2)) {\n fullNameError.style.display = \"none\";\n } else {\n fullNameError.style.display = \"block\";\n }\n\n // Check e-mail\n if (validateEmail(email.value)) {\n emailError.style.display = \"none\";\n } else {\n emailError.style.display = \"block\";\n }\n\n // Check password\n if (checkLength(password.value, 8)) {\n passwordError.style.display = \"none\";\n } else {\n passwordError.style.display = \"block\";\n }\n}", "function formValidation() {\n\t\t// Check for empty fields\n\t\tif ( contactName.val() == \"\" || contactEmail.val() == \"\" || validateEmail(contactEmail.val()) != true || contactMessage.val() == \"\" ) {\n\t\t\t// Check for ever field if empty -> apply border\n\t\t\tif ( contactName.val() == \"\" ) { contactName.addClass(\"form__invalid__border\"); } else { contactName.removeClass(\"form__invalid__border\"); }\n\t\t\tif ( contactEmail.val() == \"\" ) { contactEmail.addClass(\"form__invalid__border\"); } else { \n\t\t\t\tif ( validateEmail(contactEmail.val()) ) {\n\t\t\t\t\tcontactEmail.removeClass(\"form__invalid__border\"); \n\t\t\t\t}\n\t\t\t}\n\t\t\tif ( contactMessage.val() == \"\" ) { contactMessage.addClass(\"form__invalid__border\"); } else { contactMessage.removeClass(\"form__invalid__border\"); } \n\t\t} \n\t\t// If fields aren't empty and email valid\n\t\telse {\n\t\t\t// Remove all validation borders\n\t\t\tcontactName.add(contactEmail).add(contactMessage).removeClass(\"form__invalid__border\");\n\t\t\n\t\t\treturn true;\n\t\t}\n\t}", "function validateForm(e) {\n\nvalidation(firstName, nameRegex, e, \"please enter your first name\", \"please enter a valid first name\");\nvalidation(lastName, nameRegex, e, \"please enter your last name\", \"please enter a valid last name\");\nvalidation(phoneNumber, phoneNumberRegex, e, \"please enter your phone number\", \"please enter a valid phone number\");\nvalidation(email, emailRegex, e, \"please enter your email address\", \"please enter a valid email address\");\nvalidation(password ,passwordRegex, e, \"please enter your password\", \"Your password should have a minimum of 6 characte, 1 capital letter, 1 special character eg @ and 1 number\");\nvalidation(confirmPassword,passwordRegex, e, \"please confirm your password\", \"Your password should have a minimum of 6 characters, 1 capital letter, 1 special character eg @ and 1 number\");\nvalidatePassword(password,confirmPassword,e)\nreturn true;\n\n}", "function validateSubmit() {\n var alertStr = \"\";\n // regex checks and empty value checks on required inputs\n if (parkingName !== null && parkingName.value.length === 0)\n alertStr += \"Name is a required input\\n\";\n if (lat !== null && lat.value.length === 0)\n alertStr += \"Latitude is a required input\\n\";\n else if (lat !== null && !decimalRegex.test(lat.value))\n alertStr += \"Latitude is an invalid number\\n\";\n if (lon !== null && lon.value.length === 0)\n alertStr += \"Longitude is a required input\\n\";\n else if (lon !== null && !decimalRegex.test(lon.value))\n alertStr += \"Longitude is an invalid number\\n\";\n\n // any errors send an alert\n if (alertStr !== \"\")\n alert(alertStr);\n else\n window.location.href = \"/index.php\";\n}", "function validateForm() {\r\n var newTitle = document.forms[\"validForm\"][\"btitle\"].value;\r\n var newOwner = document.forms[\"validForm\"][\"bowner\"].value;\r\n var newContent = document.forms[\"validForm\"][\"bcontent\"].value;\r\n var newPublisher = document.forms[\"validForm\"][\"bpublisher\"].value;\r\n if (newTitle == \"\") {\r\n alert(\"Title must be filled out\");\r\n return false;\r\n } else if (newOwner == \"\") {\r\n alert(\"Name Must be filled out\");\r\n return false;\r\n } else if (newContent == \"\") {\r\n alert(\"Content Must be filled out\");\r\n return false;\r\n } else if (newPublisher == \"\") {\r\n alert(\"Publisher Name Must be filled out\");\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "function validateForm() {\n var validated = true;\n $(\".has-error\").removeClass(\"has-error\");\n\n if (!is_text_area_disabled) {\n if (txt_description.val() === \"\") {\n txt_description.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"Please fill in the description field.\");\n validated = false;\n }\n }\n\n if (input_email.val() === \"\") {\n input_email.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"Please fill in the e-mail field.\");\n validated = false;\n }\n if (!isEmail(input_email.val())) {\n input_email.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"Please input a valid email.\");\n validated = false;\n }\n if (input_email.val().length > 100) {\n input_username.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"The email must be less than 100 characters.\");\n validated = false;\n }\n\n if (input_username.val() === \"\") {\n input_username.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"Please fill in the username field.\");\n validated = false;\n }\n if (input_username.val().length > 50) {\n input_username.closest(\".form-group\").addClass(\"has-error\");\n error.fadeIn();\n error.find('.message').text(\"The username must be less than 50 characters.\");\n validated = false;\n } \n\n if (validated) {\n error.hide();\n error.find('.message').text(\"\");\n } else {\n error.fadeIn();\n $(\"html, body\").animate({ scrollTop: 0 }, \"slow\");\n }\n\n return validated;\n}", "function initiateFormValidation() {\n var $form = $(\"#\" + formID);\n $form.submit(function(e) {\n \t// remove all error stylings\n\t\t$(\".\" + errorClass).removeClass(errorClass);\n\t\t$(\".\" + errorMsgClass).css('display', 'none');\n\n\t\t// get user input\n \tvar distanceInput = getInput(distanceName).val();\n \tvar address1Input = getInput(address1Name).val();\n\n \t// show errors if there are any\n if ((distanceInput.length === 0) || isNaN(distanceInput) || (parseInt(distanceInput) <= 0)){\n \te.preventDefault();\n \tshowError(distanceName);\n }\n if (address1Input.length == 0){\n \te.preventDefault();\t\n \tshowError(address1Name);\n }\n });\n}", "function validateForm()\n{\n // Get values from required fields so that I can make sure they are there\n var make = $(\"#make\").val();\n var model = $(\"#model\").val();\n var year = $(\"#year\").val();\n\n // If make, model, or year are empty, return false so the form does not submit\n if(make == \"\")\n {\n $(\"#make\").css({border: \"3px solid red\"}); // Use this to make the box red\n alert(\"You must provide a make\"); // Use this to let user know what went wrong\n return false; // Return false so the form does not submit\n }\n if(model == \"\")\n {\n $(\"#model\").css({border: \"3px solid red\"});\n alert(\"You must provide a model\");\n return false;\n }\n if(year == \"\")\n {\n $(\"#year\").css({border: \"3px solid red\"});\n alert(\"You must provide a year\");\n return false;\n }\n\n // Otherwise, return true so the form does submit\n return true;\n}", "function CheckInputs(){\n //get values from inputs and gets rid of spaces\n const emailValue = email.value.trim();\n const subjectValue = subject.value.trim();\n const messageValue = message.value.trim();\n\n //used to check if form is valid. if by then end it doesnt equlat three then return false\n var score = 0;\n\n //CHECK EMAIL\n //checks if email is empty\n if(emailValue ===''){\n SetErrorFor(email,'Email can not be blank');\n }\n //checks if email is correct form\n else if(!IsEmail(emailValue)){\n SetErrorFor(email,'Email is not valid');\n }\n\n else{\n SetSuccessFor(email);\n score+=1;\n }\n\n //CHECK SUBJECT\n //checks if subject is empty\n if(subjectValue ===''){\n SetErrorFor(subject,'Subject can not be blank');\n }\n else{\n SetSuccessFor(subject);\n score+=1;\n }\n\n //CHECK MESSAGE\n //checks if subject is empty\n if(messageValue ===''){\n SetErrorFor(message,'Message can not be blank');\n }\n else{\n SetSuccessFor(message);\n score+=1;\n }\n\n if(score===3){\n return true;\n }\n\n else{\n return false;\n }\n\n \n}", "function validateForm(event)\n{\n\tevent.preventDefault();\n\n\t//save the selection of the form to a variable\n\tvar form = document.querySelector('form');\n\t//save the selection of the required fields to an array\n\tvar fields = form.querySelectorAll('.required');\n\n\t//set a default value that will be used in an if statement\n\tvar valid = true;\n\n\t//check each box that has the required tag\n\tfor(var i = 0; i < fields.length; i++)\n\t{\n\t\t//check that the field has a value\n\t\t//if it does not\n\t\tif(!fields[i].value)\n\t\t{\n\t\t\t//valid is false\n\t\t\tvalid = false;\n\t\t}\n\t}\n\n\t//if valid is true by the end\n\t//each box should have a value\n\tif(valid == true)\n\t{\n\t\t//remove our disabled class from the button\n\t\tbtn.removeAttribute('class');\n\t\t//set the disabled property to false\n\t\tbtn.disabled = false;\n\t}\n}", "function validateForm() {\r\n\tif((validateUsername()) && (validatePass()) && (validateRepPass()) && (validateAddress1())&& (validateAddress2()) && (validateZipCode() == true) && (validateCity()) && (validateLast()) && (validateFirst())&& (validatePhone()) && (validateEmail())) \r\n\t{\r\n\t\treturn true;\r\n\t}\r\n\telse\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n}", "function validateForm() {\n // Retrieving the values of form elements \n var dept_num = document.contactForm.dept_num.value;\n var dept_name = document.contactForm.dept_name.value;\n var dept_leader = document.contactForm.dept_leader.value;\n\t// Defining error variables with a default value\n var deptnumErr = deptnameErr = deptleaderErr = true;\n // Validate name\n if(dept_num == \"\") {\n printError(\"deptnumErr\", \"Please enter Depertment Number\");\n } else {\n printError(\"deptnumErr\", \"\");\n deptnumErr = false;\n }\n // Validate email address\n if(dept_name == \"\") {\n printError(\"deptnameErr\", \"Please enter Depertment Name\");\n } else {\n printError(\"deptnameErr\", \"\");\n deptnameErr = false;\n }\n // Validate mobile number\n if(dept_leader == \"\") {\n printError(\"deptleaderErr\", \"Please enter Depertment Leader\");\n } else {\n printError(\"deptleaderErr\", \"\");\n deptleaderErr = false;\n }\n\n \n // Prevent the form from being submitted if there are any errors\n if((deptnumErr || deptleaderErr || deptnameErr ) == true) {\n return false;\n } else {\n // Creating a string from input data for preview\n var dataPreview = \"You've entered the following details: \\n\" +\n \"Depertment Number: \" + dept_num + \"\\n\" +\n \"Depertment Name: \" + dept_name + \"\\n\" +\n \"Depertment Leader: \" + dept_leader + \"\\n\";\n // Display input data in a dialog box before submitting the form\n alert(dataPreview);\n }\n}", "function validateForm(e) {\n 'use strict';\n\n if (typeof e == 'undefined') {\n //This is a browser window-generated event\n e = window.event;\n }\n\n //Get form references:\n var firstName = U.$('firstName');\n var lastName;\n var email;\n var phone;\n var city;\n var state;\n var zip;\n var terms; //We'll populate these later\n\n //error flag:\n var error = false;\n\n //Validate the first name using a\n //regular expression:\n if (/^[A-Z \\.\\-']{2,20}$/i.test(firstName.value)) {\n // Everything between / and / is the expression\n //Any letter A-Z (case insensitive) is valid\n //Spaces, periods, and hyphens are valid\n //name must be 2 - 20 characters long\n\n //First name matches the expression\n //and is valid\n //alert(\"Valid first name\");\n removeErrorMessage('firstName');\n }\n else {\n //alert(\"Invalid first name\");\n addErrorMessage('firstName',\n 'Invalid/missing first name');\n error = true;\n }\n\n if (error) {\n if (e.preventDefault) {\n e.preventDefault();\n }\n else {\n e.returnValue = false;\n }\n }\n\n return false;\n} // End of validateForm() function.", "function formValidation() {\n var email = document.getElementById('email').value;\n var firstname = document.getElementById('firstname').value;\n var lastname = document.getElementById('lastname').value;\n var phone = document.getElementById('phone').value;\n var address = document.getElementById('address').value;\n var postcode = document.getElementById('postcode').value;\n\n // nest all supporting functions, if all true then send thank you alert\n if (email_validation(email)) {\n if (firstname_validation(firstname)) {\n if (lastname_validation(lastname)) {\n if (phone_validation(phone)) {\n if (address_validation(address)) {\n if (postcode_validation(postcode)) {\n alert('Thank you for submitting the form.');\n document.getElementById(\"edit_account\").submit();\n }\n }\n }\n }\n }\n }\n\n}", "function validate(event) {\n event.preventDefault()\n removeErrorMessage()\n removeValidMessage()\n\n validForm = true\n validateName()\n validateCarYear()\n validateCarMake()\n validateCarModel()\n validateStartDate()\n validateDays()\n validateCard()\n validateCvv()\n validateExpiration()\n\n showValidMessage()\n}", "function validateForm() {\n // Retrieving the values of form elements\n var firstname = document.insertion.fname.value;\n var email = document.insertion.email.value;\n var adress = document.insertion.adress.value;\n var phonenumber = document.insertion.ph_number.value;\n var lastname = document.insertion.lname.value;\n \n \n // Defining error variables with a default value\n var firstnameErr = (emailErr = adressErr = true);\n \n // Validate firstname\n if (firstname == \"\") {\n printError(\"firstnameErr\", \"Please enter your first name\");\n document.getElementById(\"fname\").style.borderColor = \"red\";\n } else {\n var regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(firstname) === false) {\n printError(\n \"firstnameErr\",\n \"Please enter a valid first name with min. 3 characters.\"\n );\n document.getElementById(\"fname\").style.borderColor = \"red\";\n } else {\n printError(\"firstnameErr\", \"\");\n document.getElementById(\"fname\").style.borderColor = \"green\";\n firstnameErr = false;\n }\n }\n \n // Validate last name\n if (lastname == \"\") {\n printError(\"lastnameErr\", \"Please enter your last name\");\n document.getElementById(\"lname\").style.borderColor = \"red\";\n } else {\n var regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(lastname) === false) {\n printError(\n \"lastnameErr\",\n \"Please enter a valid last name min. 3 characters.\"\n );\n document.getElementById(\"lname\").style.borderColor = \"red\";\n } else {\n printError(\"lastnameErr\", \"\");\n document.getElementById(\"lname\").style.borderColor = \"green\";\n lastnameErr = false;\n }\n }\n \n // Validate adress\n if (adress == \"\") {\n printError(\n \"adressErr\",\n \"Please enter your adress\"\n );\n document.getElementById(\"adress\").style.borderColor = \"red\";\n } else {\n var regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(adress) === false) {\n printError(\"adressErr\", \"Please enter a valid adress.\");\n document.getElementById(\"adress\").style.borderColor = \"red\";\n\n } else {\n printError(\"adressErr\", \"\");\n document.getElementById(\"adress\").style.borderColor = \"green\";\n adressErr = false;\n }\n }\n\n // Validate phone number\n if (phonenumber == \"\") {\n printError(\n \"ph_numberErr\",\n \"Please enter your phone number\"\n );\n document.getElementById(\"ph_number\").style.borderColor = \"red\";\n } else {\n var regex = /^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\\s\\./0-9]*$/;\n if (regex.test(phonenumber) === false) {\n printError(\"ph_numberErr\", \"Please enter a valid phone number.\");\n document.getElementById(\"ph_number\").style.borderColor = \"red\";\n } else {\n printError(\"ph_numberErr\", \"\");\n document.getElementById(\"ph_number\").style.borderColor = \"green\";\n ph_numberErr = false;\n }\n }\n\n // Validate email address\n if (email == \"\") {\n printError(\"emailErr\", \"Please enter your email address\");\n document.getElementById(\"email\").style.borderColor = \"red\";\n } else {\n // Regular expression for basic email validation\n var regex = /^\\S+@\\S+\\.\\S+$/;\n if (regex.test(email) === false) {\n printError(\"emailErr\", \"Please enter a valid email address ex: maxmustermann@email.com\");\n document.getElementById(\"email\").style.borderColor = \"red\";\n } else {\n printError(\"emailErr\", \"\");\n document.getElementById(\"email\").style.borderColor = \"green\";\n emailErr = false;\n }\n }\n var g = document.getElementById(\"gender\");\n var gender = g.value;\n \n // Prevent the form from being submitted if there are any errors\n if ((firstnameErr || emailErr || adressErr || lastnameErr || ph_numberErr) == true) {\n return false;\n } \n //else {\n // // Creating a string from input data for preview\n // var dataPreview =\n // \"Data entered! \\n\" +\n // \"first name: \" +\n // firstname + \"\\n\" +\n // \"last name: \" +\n // lastname +\n // \"\\n\" +\n // \"adress : \" +\n // adress +\n // \"\\n\";\n // \"Email Address: \" + email + \"\\n\"+\n // \"phone number: \" +\n // phonenumber +\n // \"\\n\" +\n // \"email adress : \" +\n // email +\"\\n\" +\n // \"Gender : \" +\n // gender ;\n \n \n \n // // Display input data in a dialog box before submitting the form\n // alert(dataPreview);\n // }\n }", "function validateForm() {\n\n\tvar emaildMandatory = \"\";\n\tvar passwordMandatory = \"\";\n\tvar countryMandatory = \"\";\n\tvar lScoreMandatory = \"\";\n\tvar sScoreMandatory = \"\";\n\tvar wScoreMandatory = \"\";\n\tvar rScoreMandatory = \"\";\n\tvar genderMandatory = \"\";\n\tvar lDateMandatory = \"\";\n\tvar dobMandatory = \"\";\n\tvar proMandatory = \"\"\n\tvar credentialMandatory = \"\"\n\tvar isFormValid = true;\n\tvar crsScoreMandatory = \"\";\n\n\tif (String(document.getElementById(\"email\").value).length == 0) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory = \"*Email is Mandatory\";\n\t\tisFormValid = false;\n\t} else if (!validateEmail(document.getElementById(\"email\").value)) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory += \"*Entered Email is invalid\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'green');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t}\n\n\tif (!validateGender()) {\n\t\tgenderMandatory += \"*Gender is Mandatory\";\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'red');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'green');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t}\n\n\tif (!validateCountry()) {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'red');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t\tcountryMandatory += \"*Country is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'green');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t}\n\n\tif (!validateCRS()) {\n\t\tif ($('#calButton').is(':visible')) {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*You should calculate the CRS Score. Please click 'Calculate' button\";\n\t\t\t$(\"#calButton\").click(function() {\n\t\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t\t$(\"#crs\").css('border-right-color', 'green');\n\t\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\t\tcrsScoreMandatory = \"\";\n\t\t\t})\n\t\t} else {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*Make sure proper IELTS score is provided.\";\n\t\t}\n\t\tisFormValid = false;\n\t}\n\n\tif (!validateCredential()) {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'red');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t\tcredentialMandatory += \"*Educational Credential is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'green');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLScore()) {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'red');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t\tlScoreMandatory += \"*Listening Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'green');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateRScore()) {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'red');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t\trScoreMandatory += \"*Reading Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'green');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateWScore()) {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'red');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t\twScoreMandatory += \"*Writing Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'green');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateSScore()) {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'red');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t\tsScoreMandatory += \"*Speaking Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'green');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateDob()) {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'red');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t\tdobMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'green');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLDate()) {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'red');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t\tlDateMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'green');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t}\n\n\tif (!validateProvince()) {\n\t\tproMandatory += \"*Please select atleast one province\";\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'red');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'green');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t}\n\n\tif (isFormValid) {\n\t\tshowSuccess();\n\t}\n\n\tdocument.getElementById('emailinvalid').innerHTML = emaildMandatory;\n\tdocument.getElementById('dobinvalid').innerHTML = dobMandatory;\n\tdocument.getElementById('cocinvalid').innerHTML = countryMandatory;\n\tdocument.getElementById('lscoreinvalid').innerHTML = lScoreMandatory;\n\tdocument.getElementById('sscoreinvalid').innerHTML = sScoreMandatory;\n\tdocument.getElementById('wscoreinvalid').innerHTML = wScoreMandatory;\n\tdocument.getElementById('rscoreinvalid').innerHTML = rScoreMandatory;\n\tdocument.getElementById('ldateinvalid').innerHTML = lDateMandatory;\n\tdocument.getElementById('provinceinvalid').innerHTML = proMandatory;\n\tdocument.getElementById('genderinvalid').innerHTML = genderMandatory;\n\tdocument.getElementById('eduinvalid').innerHTML = credentialMandatory;\n\tdocument.getElementById('crsinvalid').innerHTML = crsScoreMandatory;\n}", "function validateEdit(){\n\t\n\t//check to see if the user left the name field blank\n\tif (document.getElementById(\"e_name\").value == null || document.getElementById(\"e_name\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"e_nameerror\").innerHTML= \"*name not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"e_name\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the user left the surname field blank\n\tif (document.getElementById(\"e_surname\").value == null || document.getElementById(\"e_surname\").value == \"\"){\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"e_snameerror\").innerHTML= \"*surname not filled in\";\n\t\t\n\t\t//changes to the fields properties to highlight the incorrect field\n\t\tformAtt(\"e_surname\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t//if the users submission returns no false checks, then tell the even handler to execute the onSubmit command\n\treturn true;\n}", "function MM_validateForm() {\r\n if (document.getElementById){\r\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;\r\n for (i=0; i<(args.length-2); i+=3) { \r\n\t\t\ttest=args[i+2]; val=document.getElementById(args[i]);\r\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\r\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\r\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n'; \r\n\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (test!='R') { num = parseFloat(val);\r\n\t\t\t\t\t\tif (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\r\n\t\t\t\t\t\tif (test.indexOf('inRange') != -1) { p=test.indexOf(':');\r\n min=test.substring(8,p); max=test.substring(p+1);\r\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\r\n\t\t\t\t\t} \r\n\t\t\t\t} \r\n\t\t\t} \r\n\t\t\telse if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\r\n } \r\n\t\tif (errors) alert('The following error(s) occurred:\\n'+errors);\r\n document.MM_returnValue = (errors == '');\r\n\t}\r\n}", "function validateForm(form) {\n\n var form = document.getElementById('edit-form');\n\tclearNotice();\n\n\tif (form.name.value.trim().length == 0) {\n\t\taddError('Please enter name.');\n\t}\n\n\tif (form.emailAddress.value.trim().length == 0) {\n\t\taddError('Please enter email.');\n\t}\n\n\tif (form.name.value.trim().length != 0 && isNotValidName(form.name.value)) {\n\t\taddError('Please enter valid name.');\n\t}\n\n\tif (form.emailAddress.value.trim().length != 0 && isNotValidEmail(form.emailAddress.value)) {\n\t\taddError('Please enter valid email.');\n\t}\n\n\tif (hasErrorNotice()) {\n\t\tdisplayNotice();\n\t\treturn false;\n\t}\n\n\tdisableButton();\n\tform.submit();\n\treturn true;\n}", "function formValidation(user_name, last_Name, user_email, user_password, user_confirm_password){ \n var user_name = getInputVal(\"firstName\");\n var last_Name = getInputVal(\"userLastName\");\n var user_email = getInputVal(\"userEmail\"); \n var user_password = getInputVal(\"user_Password\");\n var user_confirm_password = getInputVal(\"user_Confirm_Password\"); \n\n if(user_name) {\n document.getElementById(\"firstNameError\").innerHTML = \"\"; \n }\n if(last_Name) {\n document.getElementById(\"firstLastError\").innerHTML = \"\"; \n }\n if(user_email) {\n document.getElementById(\"firstEmailError\").innerHTML = \"\"; \n }\n if(user_password) {\n document.getElementById(\"password_Error\").innerHTML = \"\"; \n }\n if(user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\"; \n }\n else if(user_password != user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\";\n }\n }", "function formSubmit(){\r\n // find all the input field\r\n // if the field's value is null give a thief warning and set the errorCount's value isn't 0\r\n var inputs = document.getElementsByTagName(\"input\");\r\n for(var i = 0; i < inputs.length; i += 1){\r\n var onblur = inputs[i].getAttribute(\"onblur\");\r\n if(onblur != null){\r\n if(inputs[i].value == \"\" || inputs[i].value == null){\r\n var errorType = onblur.split(\",\")[1].substring(2, onblur.split(\",\")[1].lastIndexOf(\")\") - 1);\r\n var configId = 0;\r\n for(var j = 0; j < validateConfig.length; j += 1){\r\n if(errorType == validateConfig[j].name){\r\n configId = j;\r\n }\r\n }\r\n var warning = inputs[i].parentNode.nextElementSibling || inputs[i].parentNode.nextSibling;\r\n var borderStyle = errorStyle[0];\r\n inputs[i].style.border = borderStyle.style;\r\n warning.innerHTML = validateConfig[configId].message;\r\n warning.style.color = \"red\";\r\n errorCount =+ 1;\r\n }\r\n }\r\n }\r\n \r\n if(errorCount > 0){\r\n var thief = document.getElementById(\"thief_warning\");\r\n thief.style.color = \"red\";\r\n thief.innerHTML = \"You must finish all the field...\";\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "function validate() {\n\t\t\n\t\tvar fname = $(\"#fname\").val();\n\t\tvar lname = $(\"#lname\").val();\n\t\t\n\t\tvar question = $(\"#resizable\").val();\n\t\tvar date = $(\"#datepicker\").val();\n\t\t\n\t\tif(fname == \"\") {\n\t\t\talert(\"Please enter first name\");\n\t\t}\n\t\t\n\t\telse if(lname == \"\") {\n\t\t\talert(\"Please enter last name\");\n\t\t}\n\t\t\n\t\telse if(question == \"\") {\n\t\t\talert(\"Please enter a question\");\n\t\t}\n\t\t\n\t\telse if(date == \"\") {\n\t\t\t\talert(\"Please select a date\");\n\t\t}\n\t\t\n\t\telse {\n\t\t\talert(\"Submitted\");\n\t\t}\n\t}", "function validateForm()\n{\n // Set textarea value to VTBE contents\n if ( typeof(finalizeEditors) == \"function\" )\n {\n finalizeEditors();\n }\n\n var ismath = window.api ? true : false; // True if webeq is there\n\n /* Transform equations place holders into html before validation */\n if ( ismath )\n {\n api.setHtml();\n }\n\n if ( skipValidation )\n {\n return true;\n }\n\n /* Validate form */\n var valid = formCheckList.check();\n var i;\n\n /*Check for invalid answers if any present */\n var invalidAnswersArray = [];\n var invAns = window.invalidAnswers;\n if ( typeof( invAns) == 'object' && invAns.length > 0 )\n {\n for ( i = 0; i < invAns.length; ++i )\n {\n invalidAnswersArray.push( invAns[i] );\n }\n }\n invAns = window.invalidAnswersTmp;\n if ( typeof(invAns) == 'object' && invAns.length > 0 )\n {\n for ( i = 0; i < invAns.length; ++i )\n {\n invalidAnswersArray.push( invAns[i] );\n }\n }\n var stringArg = '';\n if ( invalidAnswersArray.length > 0 )\n {\n invalidAnswersArray.sort(numericalArraySortAscending);\n var lastIndex = invalidAnswersArray.length - 1;\n for ( var x = 0; x < invalidAnswersArray.length; x++ )\n {\n stringArg += invalidAnswersArray[x];\n if ( x < lastIndex )\n {\n if ( ( (x+1) % 10 ) === 0 )\n {\n stringArg += \",\\n\";\n }\n else\n {\n stringArg += \",\";\n }\n }\n }\n }\n if ( stringArg !== '' && valid )\n {\n var msgKey;\n if ( !assessment.backtrackProhibited )\n {\n msgKey = 'assessment.incomplete.confirm';\n }\n else\n {\n msgKey = 'assessment.incomplete.confirm.backtrackProhibited';\n }\n if (assessment.isSurvey)\n {\n msgKey = msgKey + \".survey\";\n }\n\n if ( !confirm( JS_RESOURCES.getFormattedString( msgKey, [stringArg] ) ) )\n {\n valid = false; // User decided not to submit\n }\n else\n {\n assessment.userReallyWantsToSubmit = true;\n }\n\n window.invalidAnswersTmp = []; // Clearing up\n }\n\n /* Go back to placeholders if validation failed (valid == false) */\n if ( ismath && !valid )\n {\n api.setMathmlBoxes();\n }\n\n return valid;\n}", "function validateOnSubmit() {\n\n var elem;\n\n var errs=0;\n\n // execute all element validations in reverse order, so focus gets\n\n // set to the first one in error.\n\n if (!validateTelnr (document.forms.demo.telnr, 'inf_telnr', true)) errs += 1; \n\n if (!validateAge (document.forms.demo.age, 'inf_age', false)) errs += 1; \n\n if (!validateEmail (document.forms.demo.email, 'inf_email', true)) errs += 1; \n\n if (!validatePresent(document.forms.demo.from, 'inf_from')) errs += 1; \n\n\n\n if (errs>1) alert('There are fields which need correction before sending');\n\n if (errs==1) alert('There is a field which needs correction before sending');\n\n\n\n return (errs==0);\n\n }", "function MM_validateForm_Site() { //v4.0\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm_Site.arguments;\n\t\n for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n';\n } else if (test!='R') { num = parseFloat(val);\n if (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\n if (test.indexOf('inRange') != -1) { p=test.indexOf(':');\n min=test.substring(8,p); max=test.substring(p+1);\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\n } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\n\n\t}\n\t\n\t //extra validation\n\t errors += validate_state();\n\t errors += validate_lat();\n\t errors += validate_lon();\n\t errors += validate_elevation();\n\t \n\tif (errors) alert('The following error(s) occurred:\\n'+errors);\n document.MM_returnValue = (errors == '');\n}", "function validateForm() {\n\t\tvar fieldsWithIllegalValues = $('.illegalValue');\n\t\tif (fieldsWithIllegalValues.length > 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\tkenyaui.clearFormErrors('htmlform');\n\n\t\tvar ary = $(\".autoCompleteHidden\");\n\t\t$.each(ary, function(index, value) {\n\t\t\tif (value.value == \"ERROR\"){\n\t\t\t\tvar id = value.id;\n\t\t\t\tid = id.substring(0, id.length - 4);\n\t\t\t\t$(\"#\" + id).focus();\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\n\t\tvar hasBeforeSubmitErrors = false;\n\n\t\tfor (var i = 0; i < beforeSubmit.length; i++){\n\t\t\tif (beforeSubmit[i]() === false) {\n\t\t\t\thasBeforeSubmitErrors = true;\n\t\t\t}\n\t\t}\n\n\t\treturn !hasBeforeSubmitErrors;\n\t}", "function validateForm() {\n let usernameErr = false;\n let passwordErr = false;\n let emailErr = false;\n let returnValue = true;\n\n if (usernameInput.value.length <= 3) {\n usernameInput.value = '';\n usernameInput.placeholder = \"Must be 4 or more digits\";\n usernameInput.classList.add('red-border');\n usernameErr = true;\n }\n\n if (passwordInput.value.length <= 5) {\n passwordInput.value = '';\n passwordInput.placeholder = \"Must be 6 or more digits\";\n passwordInput.classList.add('red-border');\n passwordErr = true;\n }\n\n if (!regex.test(emailInput.value)) {\n emailInput.value = '';\n emailInput.placeholder = \"Enter a valid email address\";\n emailInput.classList.add('red-border');\n emailErr = true;\n }\n\n if (emailErr || passwordErr || usernameErr) {\n const alertPanel = document.querySelector('#registration-alert');\n alertPanel.classList.remove('hidden');\n returnValue = false;\n }\n\n return returnValue;\n}", "function ValidaForm() {\n if ($('#txtTitulo').val() == '') {\n showErrorMessage('El Título es obligatorio');\n return false;\n }\n if ($('#dpFechaEvento').val() == '') {\n showErrorMessage('La Fecha de publicación es obligatoria');\n return false;\n }\n if ($('#txtEstablecimiento').val() == '') {\n showErrorMessage('El Establecimiento es obligatorio');\n return false;\n }\n if ($('#txtDireccion').val() == '') {\n showErrorMessage('La Dirección es obligatoria');\n return false;\n }\n if ($('#txtPrecio').val() == '') {\n showErrorMessage('El Precio es obligatorio');\n return false;\n }\n return true;\n}", "function validation(form) {\n function isEmail(email) {\n return /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(\n email\n );\n }\n\n function isPostCode(postal) {\n if (\n /^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(\n postal\n ) ||\n /^\\d{5}$|^\\d{5}-\\d{4}$/.test(postal)\n )\n return true;\n else return false;\n }\n\n function isPhone(phone) {\n if (/^\\d{10}$/.test(phone)) return true;\n else return false;\n }\n\n function isPassword(password) {\n // Input Password and Submit [7 to 15 characters which contain only characters, numeric digits, underscore and first character must be a letter]</h2\n if (/^[A-Za-z]\\w{7,14}$/.test(password)) {\n return true;\n } else {\n return false;\n }\n }\n\n let isError = false;\n let password = '';\n\n validationFields.forEach((field) => {\n const isRequired =\n [\n 'firstName',\n 'LastName',\n 'email',\n 'address',\n 'postalCode',\n 'password',\n 'conPassword',\n ].indexOf(field) != -1;\n\n if (isRequired) {\n const item = document.querySelector('#' + field);\n\n if (item) {\n const value = item.value.trim();\n if (value === '') {\n setErrorFor(item, field + ' cannot be blank!');\n isError = true;\n } else if (field === 'email' && !isEmail(value)) {\n setErrorFor(item, 'Invalid Email Address!');\n isError = true;\n } else if (field === 'postalCode' && !isPostCode(value)) {\n setErrorFor(item, 'Invalid Postal Code!');\n isError = true;\n } else if (field === 'phone' && !isPhone(value)) {\n setErrorFor(item, 'Invalid Phone Number!');\n isError = true;\n } else if (field === 'password' && isPassword(value)) {\n setSuccessFor(item);\n password = value;\n } else if (field === 'password' && !isPassword(value)) {\n setErrorFor(\n item,\n ' Minimum 7 and Maximum 15 characters, numeric digits, underscore and first character must be a letter!'\n );\n isError = true;\n password = '';\n } else if (field === 'conPassword' && password !== value) {\n setErrorFor(item, 'Confirmation Password Not Match!');\n isError = true;\n } else {\n setSuccessFor(item);\n }\n }\n }\n });\n\n return isError === false;\n}", "function validateForm(event) {\n\n //Forhindrer at siden lastes inn på nytt når jeg sender in formen (skjema)\n event.preventDefault();\n console.log(\"The form was submitted\");\n\n //Finner 'firstName' med ID og 'firstNameError'\n const firstName = document.querySelector(\"#firstName\");\n const firstNameError = document.querySelector(\"#firstNameError\");\n\n //Sjekker med funksjon 'checkInputLenght' at 'firstName' verdien er mer en (2) ( på funksjonen neste)\n if (checkInputLength(firstName.value) === true) {\n firstNameError.style.display = \"none\"; //gjemmer feilmeldingen\n } else {\n firstNameError.style.display = \"block\"; //viser feilmeldingen om funksjonen returnerer 'false'\n }\n}", "function validation(){\n\n\n var first_name = document.getElementById(\"first-name\").value.trim()\n var last_name = document.getElementById(\"last-name\").value.trim()\n var email = document.getElementById(\"email\").value.trim() \n var phone = document.getElementById(\"phone\").value.trim()\n var error_text = document.getElementById(\"error-id\")\n var display\n\n\n //conditional statements and decision making \n if (first_name.length < 3){\n display = \"Enter a valid first name\"\n error_text.innerHTML = display\n return false\n }\n\n if (email.indexOf(\"@\") == -1 || email.indexOf(\"@\") == 0 || email.length < 7){\n display = \"Enter a valid email address\"\n error_text.innerHTML = display\n return false\n }\n\n if (last_name.length < 3){\n display = \"Enter a valid last name\"\n error_text.innerHTML = display\n return false\n }\n\n if (phone.length < 9 || phone.length > 15 || isNaN(phone)){\n display = \"Enter a valid phone number\"\n error_text.innerHTML = display\n return false\n }\n\nalert(\"Form successfully submitted\")\nreturn true \n\n}", "function formValidation(){\n //If-else statement for every item I want to check:\n submitButton.on(\"click\", function(event){\n if(name.val() === ''){\n event.preventDefault();\n $('#name-invalid').html('<p>*You must enter a name.</p>');\n $(window).scrollTop(0);\n name.addClass(\"invalid-field\");\n } else {\n $('#name-invalid').html(''); \n name.removeClass(\"invalid-field\");\n };\n if(emailField.val().match(emailRegex) === null){\n event.preventDefault();\n $('#email-invalid').html('<p>*You must enter a valid email address.</p>');\n $(window).scrollTop(0);\n emailField.addClass(\"invalid-field\");\n } else {\n $('#email-invalid').html(''); \n emailField.removeClass(\"invalid-field\");\n };\n if (totalCost === 0) {\n event.preventDefault();\n $('#activities-invalid').html('<p>*You must choose at least one activity.</p>');\n $(window).scrollTop(0);\n } else {\n $('#activities-invalid').html(''); \n };\n if(paymentField.val() === 'select_method') {\n event.preventDefault();\n $('#payment-invalid').html('<p>*You must select a payment method.</p>');\n $(window).scrollTop(0);\n paymentField.addClass(\"invalid-field\");\n } else {\n $('#payment-invalid').html(''); \n paymentField.removeClass(\"invalid-field\");\n };\n if(paymentField.val() === 'credit card') {\n if(creditCardNumberField.val().match(creditCardRegex) === null){\n event.preventDefault();\n $('#cc-num-invalid').html('<p>*You must enter a valid credit card number.</p>');\n $(window).scrollTop(0);\n creditCardNumberField.addClass(\"invalid-field\");\n } else {\n $('#cc-num-invalid').html(''); \n creditCardNumberField.removeClass(\"invalid-field\");\n };\n if(zipField.val().match(zipCodeRegex) === null){\n event.preventDefault();\n $('#zip-invalid').html('<p>*You must enter a valid 5-digit zip code.</p>');\n $(window).scrollTop(0);\n zipField.addClass(\"invalid-field\");\n } else {\n $('#zip-invalid').html(''); \n zipField.removeClass(\"invalid-field\");\n };\n if(cvvField.val().match(cvvRegex) === null){\n event.preventDefault();\n $('#cvv-invalid').html('<p>*You must enter a valid 3-digit CVV.</p>');\n $(window).scrollTop(0);\n cvvField.addClass(\"invalid-field\");\n } else {\n $('#cvv-invalid').html(''); \n cvvField.removeClass(\"invalid-field\");\n };\n };\n });\n}", "function validateForm()\n {\n var firstname=document.forms[\"UserForm\"][\"field_first_name\"].value;\n var birthdate=document.forms[\"UserForm\"][\"field_birthdate\"].value;\n var email=document.forms[\"UserForm\"][\"mail\"].value;\n var phone=document.forms[\"UserForm\"][\"field_mobile\"].value;\n\t\t\t var pass=document.forms[\"UserForm\"][\"pass\"].value;\n\t\t\t var pass2=document.forms[\"UserForm\"][\"passconfirm\"].value;\n\n if (firstname==null || firstname==\"\")\n\t\t\t \n {\n\t\t\t document.getElementById('fn_validation').innerHTML=\"this is invalid name\";\n return false;\n\t\t\t \n }\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('fn_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t if (birthdate==null || birthdate==\"\" || !(validatebirthdate(birthdate)))\n\t\t\t{\n\t\t\t document.getElementById('birth_validation').innerHTML=\"this is invalid date\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('birth_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (email==null || email==\"\" || validateEmail(email)==false)\n\t\t\t{\n\t\t\t document.getElementById('email_validation').innerHTML=\"this is invalid email\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('email_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (!(validateMobileNum(phone)))\n\t\t\t{\n\t\t\t document.getElementById('phone_validation').innerHTML=\"this is invalid mobile number\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('phone_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (pass==null || pass==\"\" || pass.length < 6)\n\t\t\t{\n\t\t\t document.getElementById('pass_validation').innerHTML=\"this is invalid password\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('pass_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (pass2!= pass )\n\t\t\t{\n\t\t\t document.getElementById('pass2_validation').innerHTML=\"this is invalid password\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('pass2_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t\n\t\t\t\n }", "function validateForm() {\n // Retrieving the values of form elements \n let name = document.contactForm.name.value;\n let age = document.contactForm.age.value;\n let email = document.contactForm.email.value;\n let mobile = document.contactForm.mobile.value;\n\n // Defining error letiables with a default value\n let nameErr = emailErr = mobileErr = ageErr = true;\n\n // Validate name\n if (name == \"\") {\n printError(\"nameErr\", \"Please enter your name\");\n } else {\n let regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(name) === false) {\n printError(\"nameErr\", \"Please enter a valid name\");\n } else {\n printError(\"nameErr\", \"\");\n nameErr = false;\n }\n }\n // Validate age number\n if (age == \"\") {\n printError(\"ageErr\", \"Please enter your age\");\n } else {\n let regex = /^[1-9]/;\n if (regex.test(age) === false) {\n printError(\"mobileErr\", \"Please enter a valid 10 digit mobile number\");\n } else {\n printError(\"mobileErr\", \"\");\n ageErr = false;\n }\n }\n\n // Validate email address\n if (email == \"\") {\n printError(\"emailErr\", \"Please enter your email address\");\n } else {\n // Regular expression for basic email validation\n let regex = /^\\S+@\\S+\\.\\S+$/;\n if (regex.test(email) === false) {\n printError(\"emailErr\", \"Please enter a valid email address\");\n } else {\n printError(\"emailErr\", \"\");\n emailErr = false;\n }\n }\n\n // Validate mobile number\n if (mobile == \"\") {\n printError(\"mobileErr\", \"Please enter your mobile number\");\n } else {\n let regex = /^[1-9]\\d{9}$/;\n if (regex.test(mobile) === false) {\n printError(\"mobileErr\", \"Please enter a valid 10 digit mobile number\");\n } else {\n printError(\"mobileErr\", \"\");\n mobileErr = false;\n }\n }\n // Prevent the form from being submitted if there are any errors\n if ((nameErr || emailErr || mobileErr || ageErr) == true) {\n return false;\n }\n let arr = [name, age, email, mobile]\n store(arr);\n\n}", "function validate_form(){\n if (is_form_valid(form)) {\n sendForm()\n }else {\n let $el = form.find(\".input:invalid\").first().parent()\n focus_step($el)\n }\n }", "function validateForm(){\n if (!nameRegex.test($(\"#name\").val())){\n toggleError(true, $(\"#nameError\"), $(\"label[for=name]\"), errorMessages.name);\n $(\"#name\").addClass(\"errorInput\");\n } else {\n toggleError(false, $(\"#nameError\"));\n $(\"#name\").removeClass(\"errorInput\");\n }\n// Trigger warning\n $(\"#mail\").trigger(\"keyup\");\n\n if ($(\"#design option\").first().prop(\"selected\")){\n toggleError(true, $(\"#designError\"), $(\".shirt-box\"), errorMessages.design);\n $(\"#design\").addClass(\"errorInput\");\n } else {\n toggleError(false, $(\"#designError\"));\n $(\"#design\").removeClass(\"errorInput\");\n }\n\n if ($(\".activities input:checked\").length == 0){\n toggleError(true, $(\"#activityError\"), $(\".activities label\").first(), errorMessages.activities);\n } else {\n toggleError(false, $(\"#activityError\"));\n }\n\n if ($(\"option[value='credit card']\").prop(\"selected\")){\n ccErrorEvaluation ();\n\n if (!zipRegex.test($(\"#zip\").val())){\n toggleError(true, $(\"#zipCodeError\"), $(\".credit-card\"), errorMessages.zipCode);\n $(\"#zip\").addClass(\"errorInput\");\n } else {\n toggleError(false, $(\"#zipCodeError\"));\n $(\"#zip\").removeClass(\"errorInput\");\n }\n\n if (!cvvRegex.test($(\"#cvv\").val())){\n toggleError(true, $(\"#cvvError\"), $(\".credit-card\"), errorMessages.cvv);\n $(\"#cvv\").addClass(\"errorInput\");\n } else {\n toggleError(false, $(\"#cvvError\"));\n $(\"#cvv\").removeClass(\"errorInput\");\n }\n }\n}", "function validateForm() {\n\t\n\tvar messageString = \"\"; // Start with blank error message\n\tvar tableViewRows = $.tableView.data[0].rows;\n\t\n\tfor (var i = 0; i < tableViewRows.length; ++i) {\n\t\t\n\t\tvar fieldObject = tableViewRows[i].fieldObject;\n\t\tvar value = getFieldValue(tableViewRows[i]);\n\t\t\n\t\tif (fieldObject.field_type == 'Checkbox') {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t// Checks if the field is blank and/or required\n\t\tif (value == \"\" || value == null) {\n\t\t\tif (fieldObject.required == \"No\") {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" is a required field.\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// -------------- Text ----------------\n \t\tif (fieldObject.field_type == 'Text') {\n \t\t\t// Do Nothing\n \t\t\t\n \t\t// -------------- Checkbox ----------------\n \t\t} else if (fieldObject.field_type == 'Checkbox') { \n \t\t\t// Do Nothing\t\n \t\t\n \t\t\n \t\t// ------------ Integer ----------------\n \t\t} else if (fieldObject.field_type == 'Integer') { \n\t\t\t// Is number? And is integer?\n\t\t\tif (Number(value) > 0 && value % 1 == 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be an integer.\\n\";\n\t\t\t}\n\t\t\n\t\t\n\t\t// ------------ Decimal ----------------\n\t\t} else if (fieldObject.field_type == 'Decimal') { \n\t\t // Is number?\n\t\t\tif (Number(value) > 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be a number.\\n\";\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t// ---------- Calculated ------------\n\t\t} else if (fieldObject.field_type == 'Calculated') { \n\t\t\n\t\t\n\t\t// -------------- Incremental Text ----------------\n\t\t} else if (fieldObject.field_type == 'Incremental Text') { \n\t\t\n\t\t\n\t\t// -------------- Date ----------------\n\t\t} else if (fieldObject.field_type == 'Date') { \n\t\t\n\t\t\n\t\t// -------------- Time ----------------\n\t\t} else if (fieldObject.field_type == 'Time') { \n\t\t\t\n\t\t\t\n\t\t// -------------- Date-Time ----------------\n\t\t} else if (fieldObject.field_type == 'Date-Time') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Message') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Location') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Photo') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Recording') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Button Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Structural Attitude') { \n\t\t\n\t\t} else { \n\t\t\t\n\t\t}\n\t\t//------------------------------------------------------------------------------------------------------------------------------------------\n\t}\n\treturn messageString;\n}", "function validateForm() {\n // select the email and message fields\n let emailCheck = document.forms[\"contact-us\"][\"email\"].value;\n let messageCheck = document.forms[\"contact-us\"][\"message\"].value;\n \n // define a regex for a valid email address\n let emailFormat = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;\n\n // if the email field is empty, display an error\n if (emailCheck == \"\") {\n let errorP = document.querySelector(\"#verify>p\");\n errorP.innerHTML = \"Please include an email address.\";\n errorP.style.border = \"2px red solid\";\n return false;\n }\n // if the email address is invalid, display error\n else if (!emailCheck.match(emailFormat)) {\n let errorP = document.querySelector(\"#verify>p\");\n errorP.innerHTML = `$Your email address is not valid.`;\n errorP.style.border = \"2px red solid\";\n return false;\n }\n // if the message field is empty, display error\n else if (messageCheck == \"\") {\n let errorP = document.querySelector(\"#verify>p\");\n errorP.innerHTML = \"You must include a message.\";\n errorP.style.border = \"2px red solid\";\n return false;\n }\n // if all input is valid, clear any previous error messages\n else {\n let errorP = document.querySelector(\"#verify>p\");\n errorP.innerHTML = \"\";\n errorP.style.border = \"none\";\n }\n return true;\n}", "function validateForm() {\n var name = document.forms[\"myForm\"][\"name\"].value;\n var definition = document.forms[\"myForm\"][\"definition\"].value;\n var price = document.forms[\"myForm\"][\"price\"].value;\n var quantity = document.forms[\"myForm\"][\"quantity\"].value;\n var isavailable = document.forms[\"myForm\"][\"isavailable\"].value;\n\n var status = false;\n\n if(definition == \"\"){\n document.getElementById(\"valdefinition\").innerHTML = \"must be filled out\";\n status = false;\n }else {\n document.getElementById(\"valdefinition\").innerHTML = \"\";\n status = true;\n }\n\n if (name == \"\"){\n document.getElementById(\"valname\").innerHTML = \"must be filled out\";\n status = false;\n }else {\n document.getElementById(\"valname\").innerHTML = \"\";\n status = true;\n }\n\n if(price == \"\"){\n document.getElementById(\"valprice\").innerHTML = \"must be filled out\";\n status =false;\n }else {\n document.getElementById(\"valprice\").innerHTML = \"\";\n status = true;\n }\n\n if(quantity == \"\"){\n document.getElementById(\"valquantity\").innerHTML = \"must be filled out\";\n status =false;\n }else {\n document.getElementById(\"valquantity\").innerHTML = \"\";\n status = true;\n }\n\n if(isavailable == \"\"){\n document.getElementById(\"valisavailable\").innerHTML = \"must be filled out\";\n status = false;\n }else {\n document.getElementById(\"valisavailable\").innerHTML = \"\";\n status = true;\n }\n\n return status;\n}", "function validateForm() {\r\n // Retrieving the values of form elements \r\n var fname = document.searchForm.fname.value;\r\n var lname = document.searchForm.lname.value; \r\n var email = document.searchForm.email.value; \r\n \r\n\t// Defining error variables with a default value\r\n var fnameErr = emailErr = lnameErr = true;\r\n \r\n if(fname == \"\" && lname == \"\" && email == \"\") {\r\n printError(\"nameErr\", \"Please enter names or email\");\r\n } \r\n if(fname != \"\" && lname == \"\") {\r\n printError(\"nameErr\", \"Please enter both names\");\r\n } \r\n if(fname == \"\" && lname != \"\") {\r\n printError(\"nameErr\", \"Please enter both names\");\r\n } \r\n\r\n if(fname != \"\" && lname != \"\") {\r\n fnameErr = false;\r\n lnameErr = false;\r\n if(email == \"\")\r\n emailErr = false;\r\n } \r\n \r\n // Validate email address\r\n if (email != \"\") {\r\n // Regular expression for basic email validation\r\n var regex = /^\\S+@\\S+\\.\\S+$/;\r\n if (regex.test(email) === false) {\r\n printError(\"emailErr\", \"Please enter a valid email address\");\r\n } else {\r\n printError(\"emailErr\", \"\");\r\n emailErr = false;\r\n }\r\n\r\n if(fname == \"\" && lname == \"\") {\r\n fnameErr = false;\r\n lnameErr = false;\r\n } else if(fname != \"\" && lname == \"\"){\r\n fnameErr = true;\r\n lnameErr = true;\r\n printError(\"nameErr\", \"Please enter both names\");\r\n } else if(fname == \"\" && lname != \"\"){\r\n fnameErr = true;\r\n lnameErr = true;\r\n printError(\"nameErr\", \"Please enter both names\");\r\n } \r\n }\r\n \r\n // Prevent the form from being submitted if there are any errors\r\n if((fnameErr || emailErr || lnameErr) == true) {\r\n return false;\r\n } else {\r\n // Creating a string from input data for preview\r\n var dataPreview = \"You've entered the following details: \\n\" +\r\n \"first Name: \" + fname + \"\\n\" +\r\n \"last name: \" + lname + \"\\n\" +\r\n \"Email: \" + email + \"\\n\";\r\n \r\n // Display input data in a dialog box before submitting the form\r\n alert(dataPreview);\r\n }\r\n}", "function validateForm(){\n\n // Here, four variables are created and values obtained from form are stored in each of them accordingly.\n var name = document.forms[\"messageBox\"][\"name\"].value;\n var email = document.forms[\"messageBox\"][\"email\"].value;\n var subject = document.forms[\"messageBox\"][\"subject\"].value;\n var message = document.forms[\"messageBox\"][\"message\"].value;\n\n // This line of code is executed when all the fields are left empty.\n if(name == \"\" && email == \"\" && subject == \"\" && message == \"\"){\n alert(\"Form is empty, please complete the form.\");\n }\n\n // This line of code is executed when the name field is left empty.\n else if(name == \"\"){\n alert(\"Field for name is empty, please enter your name.\");\n }\n\n // This line of code is executed when email field is left empty.\n else if(email == \"\"){\n alert(\"E-mail address hasn't beed filled, please enter your e-mail address.\");\n }\n \n // This line of code is executed when subject field is left empty.\n else if(subject == \"\"){\n alert(\"The subject of message is empty, please enter appropriate subject.\");\n }\n\n // This line of code is executed when the message field is left empty.\n else if(message == \"\"){\n alert(\"No message is written, please write what you want to say.\");\n }\n\n // This line of code is executed when all the fields are filled.\n else{\n alert(\"Thankyou for the message \" + name + \" , your message would be considered.\");\n }\n \n}", "function validate(){\r\n validateFirstName();\r\n validateSubnames();\r\n validateDni();\r\n validateTelephone ();\r\n validateDate();\r\n validateEmail();\r\n if(validateFirstName() && validateSubnames() && validateDni() && validateTelephone() &&\r\n validateDate() && validateEmail()){\r\n alert(\"DATOS ENVIADOS CORRECTAMENTE\");\r\n form.submit(); \r\n }\r\n\r\n}", "function supplierFrmValidation()\n\t{\n\t\t\n\t\tif(document.getElementById(\"txtName\").value == \"\")\n\t\t{\n\t\t\t alert(\"Please enter supplier name\");\n\t\t\t document.getElementById(\"txtName\").focus();\n\t\t\t return false;\n\t\t}\n\t\tif(Validate(document.getElementById(\"txtName\").value,\"[^A-Za-z0-9\\\\ ]\") == true)\n\t\t{\n\t\t\t\talert(\"Please enter valid supplier name\");\n\t\t\t\tdocument.getElementById(\"txtName\").focus();\n\t\t\t\treturn false;\n\t\t}\n\t\tif(document.getElementById(\"txtAddress\").value == \"\")\n\t\t{\n\t\t\t alert(\"Please enter supplier address\");\n\t\t\t document.getElementById(\"txtAddress\").focus();\n\t\t\t return false;\n\t\t}\n\t\tif(document.getElementById(\"txtTelephone\").value == \"\")\n\t\t{\n\t\t\t alert(\"please enter telephone number\");\n\t\t\t document.getElementById(\"txtTelephone\").focus();\n\t\t\t return false;\n\t\t}\n\t\tif(checkInternationalPhone(document.getElementById(\"txtTelephone\").value) == false)\n\t\t{\n\t\t\talert(\"Please enter a valid phone number\");\n\t\t\t document.getElementById(\"txtTelephone\").focus();\n\t\t\t return false;\n\t\t}\n\t\tif(document.getElementById(\"txtEmail\").value == \"\")\n\t\t{\n\t\t\t alert(\"Please enter email address\");\n\t\t\t document.getElementById(\"txtEmail\").focus();\n\t\t\t return false;\n\t\t}\n\t\tif(Validate(document.getElementById(\"txtEmail\").value,\"^[A-Za-z][A-Za-z0-9_\\\\.]*@[A-Za-z]*\\\\.[A-Za-z0-9]\") == false)\n\t\t{\n\t\t\t\talert(\"Please enter valid email address\");\n\t\t\t\tdocument.getElementById(\"txtEmail\").focus();\n\t\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t\t\n\t\n\t}", "function validateForm() {\n // Retrieving the values of form elements \n var name = document.contactForm.name.value;\n var email = document.contactForm.email.value;\n var mobile = document.contactForm.mobile.value;\n var country = document.contactForm.country.value;\n var gender = document.contactForm.gender.value;\n\n // Defining error variables with a default value\n var nameErr = emailErr = mobileErr = countryErr = genderErr = true;\n\n // Validate name\n if (name == \"\") {\n printError(\"nameErr\", \"Por Favor Ingrese su nombre \");\n } else {\n var regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(name) === false) {\n printError(\"nameErr\", \"Por Favor Ingresa un nombre valido\");\n } else {\n printError(\"nameErr\", \"\");\n nameErr = false;\n }\n }\n\n // Validate email address\n if (email == \"\") {\n printError(\"emailErr\", \"Por Favor Ingrese Su Correo\");\n } else {\n // Regular expression for basic email validation\n var regex = /^\\S+@\\S+\\.\\S+$/;\n if (regex.test(email) === false) {\n printError(\"emailErr\", \"Por Favor Ingrese un Correo Valido\");\n } else {\n printError(\"emailErr\", \"\");\n emailErr = false;\n }\n }\n\n // Validate mobile number\n if (mobile == \"\") {\n printError(\"mobileErr\", \"Por Favor Ingrese Su Numero Telefonico\");\n } else {\n var regex = /^[1-9]\\d{9}$/;\n if (regex.test(mobile) === false) {\n printError(\"mobileErr\", \"Por favor Ingrese un Numero Valido(+569)12345678\");\n } else {\n printError(\"mobileErr\", \"\");\n mobileErr = false;\n }\n }\n\n // Validate country\n if (country == \"seleccionar\") {\n printError(\"countryErr\", \"Por Favor Ingrese Su Region\");\n } else {\n printError(\"countryErr\", \"\");\n countryErr = false;\n }\n\n // Validate gender\n if (gender == \"\") {\n printError(\"genderErr\", \"Por Favor Ingrese Su Genero\");\n } else {\n printError(\"genderErr\", \"\");\n genderErr = false;\n }\n\n // Prevent the form from being submitted if there are any errors\n if ((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {\n return false;\n } else {\n // Creating a string from input data for preview\n var dataPreview = \"Tu Has Ingresado los siguientes Datos: \\n\" +\n \"Nombre Completo: \" + name + \"\\n\" +\n \"Correo: \" + email + \"\\n\" +\n \"Telefono: \" + mobile + \"\\n\" +\n \"Region: \" + country + \"\\n\" +\n \"Genero: \" + gender + \"\\n\";\n }\n // Display input data in a dialog box before submitting the form\n alert(dataPreview);\n}", "function validateForm() {\n var state = document.forms[\"user-form\"][\"estado\"].value;\n var city = document.forms[\"user-form\"][\"cidade\"].value;\n var zip = document.forms[\"user-form\"][\"cep\"].value;\n var regex_landline = /^\\(?([0-9]{2})\\)? ([0-9]{4})[-. ]?([0-9]{4})$/;\n var regex_cellular = /^\\(?([0-9]{2})\\)? ([0-9]{1})? ([0-9]{4})[-. ]?([0-9]{4})$/;\n\n var valueString = $(\"#telephone\").val();\n if (!regex_landline.test(valueString) && !regex_cellular.test(valueString)) {\n alert(\"enter contact in format (NN) N NNNN-NNNN or (NN) NNNN-NNNN\");\n return false;\n }\n var regex_zip = /^([0-9]{5})[-. ]?([0-9]{3})$/;\n // console.log('zip code', $('.zip-field').val());\n\n if (state === \"\") {\n alert(\"State must be filled out\");\n return false;\n } else if (city === \"\") {\n alert(\"City must be filled out\");\n return false;\n } else if (zip === \"\") {\n alert(\"Zipcode must be filled out\");\n return false;\n } else if (!(regex_zip.test($(\".zip-field\").val()))) {\n alert(\"Zipcode must be filled out in correct format\");\n return false;\n } else {\n return true;\n }\n }", "function validateForm() {\r\n\t\t// Old Password validation\r\n\t\tif ((document.getElementById('oldPassword').value).trim() == \"\") {\r\n\t\t\tdocument.getElementById(\"oldPasswordError\").innerHTML = \"*Mandatory Field\";\r\n\t\t\treturn false;\r\n\t\t} else {\r\n\t\t\tdocument.getElementById(\"oldPasswordError\").innerHTML = \"\";\r\n\t\t\tdocument.formPasswordChange.oldPassword.focus();\r\n\t\t}\r\n\r\n\t\t// New Password1 validation\r\n\t\tif ((document.getElementById('newPassword1').value).trim() == \"\") {\r\n\t\t\tdocument.getElementById(\"newPassword1Error\").innerHTML = \"*Mandatory Field\";\r\n\t\t\treturn false;\r\n\t\t} else {\r\n\t\t\tdocument.getElementById(\"newPassword1Error\").innerHTML = \"\";\r\n\t\t\tdocument.formPasswordChange.newPassword1.focus();\r\n\t\t}\r\n\r\n\t\t// New Password2 validation\r\n\t\tif ((document.getElementById('newPassword2').value).trim() == \"\") {\r\n\t\t\tdocument.getElementById(\"newPassword2Error\").innerHTML = \"*Mandatory Field\";\r\n\t\t\treturn false;\r\n\t\t} else {\r\n\t\t\tdocument.getElementById(\"newPassword2Error\").innerHTML = \"\";\r\n\t\t\tdocument.formPasswordChange.newPassword2.focus();\r\n\t\t}\r\n\r\n\t\tif (p1 != p2) {\r\n\t\t\tdocument.getElementById(\"newPassword2Error\").innerHTML = \" *Password Mismatches\";\r\n\t\t\treturn false;\r\n\t\t} else {\r\n\t\t\tdocument.getElementById(\"newPassword2Error\").innerHTML = \"\";\r\n\t\t}\r\n\r\n\t}", "validate(event) {\n\t\tevent.preventDefault();\n\n\t\tlet valid = true;\n\n\t\tconst form = document.forms['form'];\n\t\tconst formNodes = Array.prototype.slice.call(form.childNodes);\n\t\tvalid = this.props.schema.fields.every(field => {\n\t\t\tconst input = formNodes.find(node => node.id === field.id);\n\n\t\t\t// Check field is answered if mandatory\n\t\t\tif (!field.optional || typeof field.optional === 'object') {\n\t\t\t\tlet optional;\n\n\t\t\t\t// Check type of 'optional' field.\n\t\t\t\tif (typeof field.optional === 'object') {\n\n\t\t\t\t\t// Resolve condition in 'optional' object.\n\t\t\t\t\tconst dependentOn = formNodes.find(node => node.id === field.optional.dependentOn);\n\t\t\t\t\tconst dependentOnValue = this.getValue(dependentOn, field.type);\n\n\t\t\t\t\t// Try and find a value in schema 'values' object that matches a value\n\t\t\t\t\t// given in 'dependentOn' input.\n\t\t\t\t\t// Otherwise, use the default value provided.\n\t\t\t\t\tconst value = field.optional.values.find(val => dependentOnValue in val);\n\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\toptional = value[dependentOnValue];\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptional = field.optional.default;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t// Else 'optional' field is just a boolean value.\n\t\t\t\t\toptional = field.optional;\n\t\t\t\t}\n\n\t\t\t\t// If not optional, make sure input is answered.\n\t\t\t\tif (!optional) {\n\t\t\t\t\treturn Boolean(this.getValue(input, field.type));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn field.validations.every(validation => {\n\t\t\t\tif (validation.containsChar) {\n\t\t\t\t\t// Ensure input value has the specified char.\n\t\t\t\t\treturn this.getValue(input, field.type).trim().includes(validation.containsChar);\n\n\t\t\t\t} else if (validation.dateGreaterThan) {\n\t\t\t\t\t// Ensure difference between today and given date is larger than specified interval.\n\t\t\t\t\tconst value = this.getValue(input, field.type);\n\n\t\t\t\t\tlet diff = Date.now() - new Date(value).getTime();\n\n\t\t\t\t\t// Convert from milliseconds to the unit given in schema.\n\t\t\t\t\tswitch(validation.dateGreaterThan.unit) {\n\t\t\t\t\t\tcase \"seconds\":\n\t\t\t\t\t\t\tdiff = diff / 1000;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"minutes\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"hours\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"days\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"years\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24 / 365;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\treturn diff > validation.dateGreaterThan.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\t// If all checks pass, submit the form. Otherwise alert the user.\n\t\tif (valid) {\n\t\t\tthis.submit();\n\t\t} else {\n\t\t\talert(\"Form is not valid. Please make sure all inputs have been correctly answered.\");\n\t\t}\n\n\t}", "function checkForm() {\n let isValid = true;\n let errors_messages = [];\n\n // Check all input\n document.querySelectorAll(\"#signup_form input\").forEach(input => {\n if (!input.value) {\n errors_messages.push(input.name + \"is missing.\");\n isValid = false;\n }\n })\n\n // Check all select\n document.querySelectorAll(\"#signup_form select\").forEach(select => {\n if (!select.value) {\n errors_messages.push(select.name + \"is missing.\");\n isValid = false;\n }\n })\n\n // Check if the password and the re password are the same\n if (passwordInput.current.value !== repasswordInput.current.value) {\n errors_messages.push(\"Password and Re-password are not the same.\");\n isValid = false;\n }\n\n // Check if the user is 18 years or older\n if (!checkAge(document.querySelector(\"input[id=birthdate]\"))) {\n errors_messages.push(\"You must be at least 18 years old.\");\n isValid = false;\n }\n\n // Show all information about the form\n if (!isValid) {\n let html_return = \"<ul>\";\n errors_messages.forEach(error => {\n html_return += \"<li>\" + error + \"</li>\"\n })\n html_return += \"</ul>\";\n\n UIkit.notification({\n message: html_return,\n status: 'danger',\n pos: 'top-right',\n timeout: 5000\n });\n }\n\n return isValid;\n }", "function validate() {\n\n if( document.myForm.fName.value === \"\" ) {\n alert( \"Please provide your first name!\" );\n document.myForm.fName.focus();\n return false;\n }\n if( document.myForm.sName.value === \"\" ) {\n alert( \"Please provide your surname!\" );\n document.myForm.sName.focus() ;\n return false;\n }\n if( document.myForm.email.value === \"\" ) {\n alert( \"Please provide your email or phone number!\" );\n document.myForm.email.focus() ;\n return false;\n }\n return( true );\n }", "function validateSignUp() {\n \n\t//check to see if the username field is empty\n if (document.getElementById(\"name\").value == null || document.getElementById(\"name\").value == \"\") {\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"fnameerror\").innerHTML= \"*first name not filled in\";\n\t\t\n\t\t//calling a function that changes the fields attributes to highlight the error\n\t\tformAtt(\"name\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the password field is empty\n\tif (document.getElementById(\"surname\").value == null || document.getElementById(\"surname\").value == \"\") {\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"snameerror\").innerHTML= \"*surname not filled in\";\n\t\t\n\t\t//calling a function that changes the fields attributes to highlight the error\n\t\tformAtt(\"surname\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t\n\t//check to see if the age field is empty\n\tif (document.getElementById(\"age\").value == null || document.getElementById(\"age\").value == \"\") {\n\t\t\n\t\t//finding the error element to insert a warning message to screen\n\t\tdocument.getElementById(\"ageerror\").innerHTML= \"*age not selected\";\n\t\t\n\t\t//calling a function that changes the fields attributes to highlight the error\n\t\tformAtt(\"age\");\n\t\t\n\t\t//telling the event handler not to execute the onSubmit command\n return false;\n }\n\t//if the users submission returns no false checks, then tell the even handler to execute the onSubmit command\t\t\n\treturn true;\n\t\n}", "function validateForm() {\n\tvar formatted_address = document.forms[\"myForm\"][\"formatted_address\"].value;\n\tvar regeUpperCase=\"[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]\";\n\tvar regexLowerCase=\"[abceghjklmnprstvxy][0-9][abceghjklmnprstvwxyz] ?[0-9][abceghjklmnprstvwxyz][0-9]\";\n\n\t\n\tif (!formatted_address) {\n\t\tdocument.getElementById('formatted_address11111s').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\tdocument.getElementById('geocomplete').focus();\n\t\treturn false;\n\t}else if(!(formatted_address.match(regeUpperCase) || formatted_address.match(regexLowerCase)) ){\n\t\tdocument.getElementById('formatted_address11111s').innerHTML = \"<span style='color:red'>*Please Enter Proper Address.</span>\";\n\t\tdocument.getElementById('geocomplete').focus();\t\n\t\treturn false;\n\t}else {\n\t\tdocument.getElementById(\"formatted_address11111s\").innerHTML = \"\";\n\t}\n\n\tvar refivalue = document.forms[\"myForm\"][\"refivalue\"].value;\n\tif (!refivalue) {\n\t\tdocument.getElementById('input_101').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\tdocument.getElementById('refivalueID').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_101\").innerHTML = \"\";\n\t}\n\t/**\n\t * need to change here\n\t * \n\t */\n\t\n\n\tvar additionalFunds = document.forms[\"myForm\"][\"additionalFunds\"].value;\n\tif (!additionalFunds) {\n\t\tdocument.getElementById('widget_settings_46').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\tdocument.getElementById('additionalFundsID').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"widget_settings_46\").innerHTML = \"\";\n\t}\n\tif(parseInt(refivalue) < parseInt(additionalFunds)){\n\t\talert(\"coming\")\n\t\tdocument.getElementById('not_be_greater_than_property').innerHTML = \"<span style='color:red'>*Property value cannot be less than Additional Amount.</span>\";\n\t\t\n\t\treturn false;\n\t}else{\n\t\tdocument.getElementById('not_be_greater_than_property').innerHTML = \"\";\n\t}\n\tvar buyProperty = document.forms[\"myForm\"][\"buyProperty\"].value;\n\tvar payOffDebt = document.forms[\"myForm\"][\"payOffDebt\"].value;\n\tvar buyInvestment = document.forms[\"myForm\"][\"buyInvestment\"].value;\n\tvar buyVehicle = document.forms[\"myForm\"][\"buyVehicle\"].value;\n\tvar renovate = document.forms[\"myForm\"][\"renovate\"].value;\n\tvar refurnish = document.forms[\"myForm\"][\"refurnish\"].value;\n\tvar vacation = document.forms[\"myForm\"][\"vacation\"].value;\n\tvar recVehicle = document.forms[\"myForm\"][\"recVehicle\"].value;\n\tvar other = document.forms[\"myForm\"][\"other\"].value;\n\tvar retVal = true;\n\n\tif (buyProperty == 'false' && payOffDebt == 'false'\n\t\t\t&& buyInvestment == 'false' && buyVehicle == 'false'\n\t\t\t&& renovate == 'false' && refurnish == 'false'\n\t\t\t&& vacation == 'false' && recVehicle == 'false' && other == 'false') {\n\n\t\tconsole.log(\"after inside bank Account -->\");\n\n\t\tdocument.getElementById('widget_settings_27').innerHTML = \"<span style='color:red'>*This field is Required , Atleast Select one of them.</span>\";\n\t\tretVal = false;\n\t} else {\n\n\t\tdocument.getElementById(\"widget_settings_27\").innerHTML = \"\";\n\t}\n\n\tvar living4Financing = document.forms[\"myForm\"][\"living4Financing\"].value;\n\tif (!living4Financing) {\n\t\tdocument.getElementById('input_203').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_203\").innerHTML = \"\";\n\t}\n\n\tif (living4Financing == \"Renter\" || living4Financing == \"OwnerAndRenter\") {\n\t\tvar rentalAmount = document.forms[\"myForm\"][\"rentalAmount\"].value;\n\t\tif (!rentalAmount) {\n\t\t\tdocument.getElementById('input_39').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\t\tdocument.getElementById('input_394').focus();\n\t\t\tretVal = false;\n\t\t} else {\n\t\t\tdocument.getElementById(\"input_39\").innerHTML = \"\";\n\t\t}\n\t}\n\n\treturn retVal;\n}", "function validateForm() {\n var errorMessage = \"\";\n var fname = document.forms[\"accountForm\"][\"fname\"].value;\n if (fname == \"\") {\n errorMessage += \"First Name is a required field \\n\" ;\n }\n\n var lname = document.forms[\"accountForm\"][\"lname\"].value;\n if (lname == \"\") {\n errorMessage += \"Last Name is a required field \\n\";\n }\n\n var phone = document.forms[\"accountForm\"][\"phone\"].value;\n if (phone == \"\") {\n errorMessage += \"Phone is a required field \\n\";\n }\n\n var email = document.forms[\"accountForm\"][\"email\"].value;\n if (email == \"\") {\n errorMessage += \"Email is a required field\";\n }\n\n // if there is an error, return false and show the alert\n if (errorMessage != \"\") {\n alert(errorMessage);\n return false;\n }\n}", "function formValidation(){\n var errorString = \"\";\n\n var u = usernameValidation();\n var p = passwordValidation();\n var e = emailValidation();\n var d = dateOfBirthValidation();\n\n if(!u) errorString += 'username validation: ' + u + \"\\n\";\n if(!p) errorString += \"password validation: \" + p + \"\\n\";\n if(!e) errorString += \"email validation: \" + e + \"\\n\";\n if(!d) errorString += \"dob validation: \" + d + \"\\n\";\n\n\n if(errorString != \"\") alert(errorString);\n return u && p && e && d;\n}", "function formHasErrors()\n{\n\tvar errorFlag = false;\n //validating all of the text fields to confirm the have options\n\tfor(let i = 0; i < requireTextFields.length; i++){\n\t\tvar textField = document.getElementById(requireTextFields[i])\n\t\t\n\t\tif(!hasInput(textField)){\n\t\t\t//display correct error message\n\t\t\tdocument.getElementById(requireTextFields[i] + \"_error\").style.display = \"inline\";\n document.getElementById(requireTextFields[i]).style.border = \"0.75px red solid\";\n \n\t\t\terrorFlag = true;\n\t\t} else {\n\t\t\t\n\t\t\t//after user enters the correct info this hides the border and error message\n\t\t\tdocument.getElementById(requireTextFields[i] + \"_error\").style.display = \"none\";\n\t\t\tdocument.getElementById(requireTextFields[i]).style.border = \"1px solid #e5e5e5;\";\n\t\t}\n\t}\n\treturn errorFlag;\n}", "function validateForm()\n{\n return true;\n}", "function validateForm()\n{\n return true;\n}", "function isValidForm() {\n var mainTextValid = isValidRequiredTextAreaField(\"main_text\");\n var articleKeywordCategoryValid = isValidRequiredField(\"article_keyword_category\");\n var articleKeywordsValid = isValidRequiredKeywordsField(\"article_keywords\");\n var originalSourceURLValid = isValidUrlField(\"original_source_url\");\n return isValidPartialForm() && mainTextValid && articleKeywordCategoryValid && articleKeywordsValid && originalSourceURLValid;\n}", "function validateform()\n{\n var passingFlag = true;\n var form = document.forms['estimateform'];\n\n name = form.name.value;\n email = form.email.value;\n phone = form.phone.value;\n subject = form.subject.value;\n message = form.message.value;\n\n if (name == \"\")\n {\n alert(\"Please enter a valid name\")\n passingFlag = false;\n } else if (email == \"\" || !email.includes('@'))\n {\n alert(\"Please enter a valid email\")\n passingFlag = false;\n } else if (phone == \"\" || !phone.match(/^\\d+$/))\n {\n alert(\"Please enter a valid phone number with only numerical digits. \\n Ex: 48022228888\")\n passingFlag = false;\n } else if (subject == \"\")\n {\n alert(\"Please enter a subject\")\n passingFlag = false;\n } else if (message = \"\")\n {\n alert(\"Please enter a message\")\n passingFlag = false;\n }\n return passingFlag;\n}", "function ValidateForm() {\r\n\tvar regex;\r\n\r\n\t// Validate name.\r\n\tvar name = $('#name').val();\r\n\tvar namemessage = $('#namemessage');\r\n\tif (name.length != 0) {\r\n\t\tnamemessage.innerHTML\r\n\t\t= 'Valid!';\r\n\t\tnamemessage.setAttribute('class', 'green');\r\n\t}\r\n\telse {\r\n\t\tnamemessage.innerHTML = 'Not Valid, it should not be blank!';\r\n\t\tnamemessage.setAttribute('class', 'red');\r\n\t}\r\n\r\n\t// Validate age.\r\n\tvar age = document.getElementById('age').value;\r\n\tvar agemessage = document.getElementById('agemessage');;\r\n\tif (isNumeric(age)) {\r\n\t\tagemessage.innerHTML = 'Valid!';\r\n\t\tagemessage.setAttribute('class', 'green');\r\n\t}\r\n\telse {\r\n\t\tagemessage.innerHTML = 'Not Valid!';\r\n\t\tagemessage.setAttribute('class', 'red');\r\n\t}\r\n}", "function checkForm() {\n document.getElementById(\"contactform\").onsubmit = function() {\n var allowsubmit = true;\n\n //fetch all the input values from the form and store in variables\n\n var firstName = document.getElementById(\"fname\").value;\n var lastName = document.getElementById(\"lname\").value;\n var title = getValue(\"title\");\n var healthAuth = document.getElementById(\"HAN\").value;\n var email = document.getElementById(\"email\").value;\n var telNumber = document.getElementById(\"tnumber\").value;\n\n var errorContainer = []; //array to contain the various error messages that may arise\n\n //prepare regular expressions to be used in validation\n var firstNameRegEx = /^[A-Za-z]{2,}$/;\n var lastNameRegEx = /^[-A-Za-z]{2,}$/;\n var healthAuthRegEx = /ZHA\\d{6}$/;\n var emailRegEx = /^[\\w\\.\\-]+@([\\w\\-]+\\.)+[a-zA-Z]+$/;\n var telNumberRegEx = /020\\d{8}$| /;\n\n //validate user input \n if (firstName === \"\" || firstName === \"e.g. John\" || !firstNameRegEx.test(firstName)) {\n errorContainer.push(\"fnameErr\");\n allowsubmit = false;\n } else {\n document.getElementById(\"fnameErr\").style.display = \"none\";\n }\n if (lastName === \"\" || lastName === \"e.g. Doe\" || !lastNameRegEx.test(lastName)) {\n errorContainer.push(\"lnameErr\");\n allowsubmit = false;\n } else {\n document.getElementById(\"lnameErr\").style.display = \"none\";\n }\n if (healthAuth === \"\" || healthAuth === \"e.g. ZHA346783\" || !healthAuthRegEx.test(healthAuth)) {\n errorContainer.push(\"HANErr\");\n allowsubmit = false;\n } else {\n document.getElementById(\"HANErr\").style.display = \"none\";\n }\n if (email === \"\" || email === \"e.g. johndoe@email.com\" || !emailRegEx.test(email)) {\n errorContainer.push(\"emailErr\");\n allowsubmit = false;\n } else {\n document.getElementById(\"emailErr\").style.display = \"none\";\n }\n\n if (telNumber === \"\" || telNumber === \"Optional\") {\n document.getElementById(\"tnumberErr\").style.display = \"none\";\n } else {\n if (!telNumberRegEx.test(telNumber)) {\n errorContainer.push(\"tnumberErr\");\n allowsubmit = false;\n }\n }\n\n if (allowsubmit) {\n alert(\"Thank you for submitting your details. A member of HAD Team will be in contact with you.\");\n } else {\n for (var i = 0; i < errorContainer.length; i++) {\n displayError(errorContainer[i]);\n }\n }\n return allowsubmit;\n };\n}", "function validateAndSubmit() {\r\n var isValid = false;\r\n isValid = validateForm();\r\n if (isValid == true) {\r\n disableButtons() // make sure you can only press the submit button once\r\n document.getElementById('evaluationForm').submit();\r\n }\r\n }" ]
[ "0.74749106", "0.74646735", "0.74002945", "0.73236877", "0.7248498", "0.72438556", "0.72245204", "0.7194632", "0.7169855", "0.7137599", "0.71145856", "0.71109533", "0.7103105", "0.706405", "0.704097", "0.7020283", "0.70136404", "0.6997217", "0.69936943", "0.6988188", "0.6980348", "0.69554174", "0.6942357", "0.69394267", "0.69393915", "0.6936282", "0.6935985", "0.6929887", "0.6926583", "0.69224775", "0.69168806", "0.68812263", "0.6871798", "0.68704563", "0.68514943", "0.68503004", "0.6843319", "0.68351585", "0.68243116", "0.68125844", "0.68031114", "0.67844373", "0.6772299", "0.6771994", "0.67673486", "0.6765952", "0.6764724", "0.6746391", "0.6735239", "0.6728426", "0.6724707", "0.671324", "0.67080617", "0.6703911", "0.6699424", "0.66882306", "0.66825956", "0.6682537", "0.66684437", "0.6667356", "0.6663794", "0.6658248", "0.66451925", "0.6637305", "0.663549", "0.66311175", "0.6631082", "0.66307014", "0.662804", "0.66246146", "0.66214883", "0.66211766", "0.6610776", "0.6605799", "0.66019213", "0.65992564", "0.65935725", "0.65915716", "0.6591466", "0.658843", "0.65684766", "0.65647626", "0.655977", "0.6558946", "0.6557228", "0.655558", "0.6553866", "0.6550113", "0.6541993", "0.65403914", "0.6535806", "0.65310115", "0.65296066", "0.65289617", "0.65289617", "0.65266466", "0.6526598", "0.65253496", "0.6521053", "0.6520524" ]
0.66912913
55
validateForm() SUB FUNCTIONS CALCULATE RESULTS FUNCTION Calculates results; takes user information from form input, and calculates the user's BMR and TDEE. Uses the appropriate formulas/modifiers based on gender and activity level. Fires when user clicks submit form, and inputs are determined valid based on validateForm().
function calculateResults() { return; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function calculate() {\n\t\t\tlet age = document.getElementById(\"inputAge\").value;\n let sex = document.getElementById(\"selectSex\").value;\n let pregnantOrLactating = document.getElementById(\"selectPregnantLactating\").value;\n\t\t\tlet height = document.getElementById(\"inputHeight\").value;\n let weight = document.getElementById(\"inputWeight\").value;\n let lifestyle = document.getElementById(\"selectLifestyle\").value;\n\n //Inicializing activity coeficient (which depend of user's sex) and required calories (which depends of user's age, height, weight, sex, pregnant or lactating and activity)\n let activity = 0;\n let reqCalories = 0; \n\n //Checking if the form is filled\n\t\t\tif (age === \"\" || sex === \"\") {\n\t\t\t\tdocument.getElementById(\"messageFillIn2\").innerHTML = \"Please fill in the required fields.\";\n }\n \n else if ((height === \"\" || weight === \"\") || lifestyle === \"\") {\n\t\t\t\tdocument.getElementById(\"messageFillIn2\").innerHTML = \"Please fill in the required fields.\";\n }\n\n else if (age < 18) {\n document.getElementById(\"messageFillIn2\").innerHTML = \"This app is not for users under 18 years\"; \n }\n\n //If the form is filled, calculate\n else { \n scrollTo(0,0); \n document.getElementById(\"divPersonalInfo\").style.display = \"none\";\n document.getElementById(\"divDailyRequirement\").style.display = \"block\";\n\n //Calculating calories and daily nutrient requirements\n if (sex === \"male\") {\n //Calculating activity coeficient and required daily calories\n switch (lifestyle) {\n case \"sedentary\":\n activity = 1;\n break;\n case \"littleActive\":\n activity = 1.11;\n break;\n case \"active\":\n activity = 1.25;\n break;\n case \"veryActive\":\n activity = 1.48;\n break;\n }\n\n reqCalories = 662 - (9.53 * age) + activity * ( (15.91 * weight) + (539.6 * height / 100) );\n\n //Asigning age specific nutrient requirements for male users\n if (18 <= age <= 30) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq18\"];\n }\n else if (31 <= age <= 50) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq31\"];\n }\n else if (51 <= age <= 70) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq51\"];\n }\n else if (age >= 71) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq71\"];\n }\n }\n\n else if (sex === \"female\") {\n //Calculating activity coeficient and required daily calories\n switch (lifestyle) {\n case \"sedentary\":\n activity = 1;\n break;\n case \"littleActive\":\n activity = 1.12;\n break;\n case \"active\":\n activity = 1.27;\n break;\n case \"veryActive\":\n activity = 1.45;\n break;\n }\n\n reqCalories = 354 - (6.91 * age) + activity * ( (9.36 * weight) + (726 * height / 100) );\n \n //Calculating calories & nutrient requirements when the user is pregnant or lactating\n if (pregnantOrLactating !== \"\") {\n switch (pregnantOrLactating) {\n case \"pregnant2\":\n reqCalories += 340;\n break;\n case \"pregnant3\":\n reqCalories += 452;\n break;\n case \"lactating1\":\n reqCalories += 330;\n break;\n case \"lactating2\":\n reqCalories += 400;\n break;\n }\n\n switch (pregnantOrLactating) {\n case \"pregnant1\":\n case \"pregnant2\":\n case \"pregnant3\":\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femalePregnant\"];\n break;\n case \"lactating1\":\n case \"lactating2\":\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleLactating\"];\n break;\n }\n }\n else {\n //Asigning age specific nutrient requirements for female users\n if (18 <= age <= 30) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq18\"];\n }\n else if (31 <= age <= 50) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq31\"];\n }\n else if (51 <= age <= 70) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq51\"];\n }\n else if (age >= 71) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq71\"];\n }\n } \n }\n\n //Adding calories property to user's object with nutrient requrements\n userNutReq[\"reqCalories\"] = reqCalories.toFixed(0);\n \n //Filling the table \"Daily Requirement\"\n let tableReq = document.getElementById(\"tableDailyRequirement\");\n let cellReqId = \"\";\n\n for (let rowIndex = 0; rowIndex < tableReq.rows.length; rowIndex++) {\n if (rowIndex == 6 || rowIndex == 19) {\n }\n else {\n cellReqId = tableReq.rows.item(rowIndex).cells[1].id;\n tableReq.rows.item(rowIndex).cells[1].innerHTML = userNutReq[cellReqId];\n }\n }\n }\n \n\t\t}", "function displayResults () {\n if(validateForm()) {\n // If all inputs are valid, create a user profile to calculate results\n const user = createUserProfile();\n\n // TDEE Results\n document.getElementById(\"tdee-results\").innerHTML = \"Your TDEE: results\";\n\n // BMR Results\n document.getElementById(\"bmr-results\").innerHTML = \"Your BMR: results\";\n\n // Input Results\n var inputResults = \"\";\n inputResults += \"Showing results for a \"; \n inputResults += user.get(\"activity\") + \" \" + user.get(\"age\") + \" year old \" + user.get(\"gender\") + \" who is \" + user.get(\"feet\") + \" feet \" + user.get(\"inches\") + \" inch(es) tall and weighs \" + user.get(\"weight\") + \" pounds.\"; \n document.getElementById(\"input-results\").innerHTML = inputResults;\n } else {\n document.getElementById(\"error-message\").innerHTML = \"Error\";\n }\n\n return;\n}", "function calculateForm() {\n setFields();\n\n if (formIsValid()) {\n var loan_amount, interest, monthly_interest, years, months,\n payment, paid, interest_paid;\n\n loan_amount = total_loan_box.value;\n interest = interest_rate_box.value;\n\n if (interest >= 1) interest = interest / 100;\n\n monthly_interest = interest / 12;\n years = loan_term_box.value;\n months = years * 12;\n\n number_payments_box.value = months;\n\n payment = Math.floor((loan_amount * monthly_interest) / (1 - Math.pow((1 + monthly_interest), (-1 * months))) * 100) / 100;\n payment_amount_box.value = payment.toFixed(2);\n\n paid = payment * months;\n total_paid_box.value = paid.toFixed(2);\n\n interest_paid = paid - loan_amount;\n interest_paid_box.value = interest_paid.toFixed(2);\n\n return true;\n }\n\n focus_box.select();\n return false;\n}", "function calculate() {\n if (validateInputs()) {\n if ($age.val() > 110) {\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Invalid Age</span>\");\n } else if (($weight.val() > 600 && imperial) || ($weight.val() > 270 && !imperial)) {\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Invalid Weight</span>\");\n } else if (imperial) { // calculation if imperial units\n if ($heightInputIn.val() > 12) {\n inchesConvert();\n }\n var BMR = Math.round(calculateBMR());\n var TDEE = Math.round(calculateBMR() * 1.2);\n var BMI = calculateBMI();\n $calcResultsBox.removeClass(\"hidden\").html(\n \"To lose \" + $slider.slider(\"value\") + \" lb per week, you would need to eat \" + Math.round((TDEE - 500 * $slider.slider(\"value\"))) + \"* kcal per day (not including exercise).<br/><br/>BMR: \" + BMR + \" kcal<br/>TDEE: \" + TDEE + \" kcal<br/>BMI: \" + BMI + \"</td><br/><br/>* Eating less than 1200 kcal daily is not recommended.\");\n } else {\n // calculation if metric units\n var BMR = Math.round(calculateBMR());\n var TDEE = Math.round(calculateBMR() * 1.2);\n var BMI = calculateBMI();\n $calcResultsBox.removeClass(\"hidden\").html(\n \"To lose \" + $slider.slider(\"value\") + \" kg per week, you would need to eat \" + Math.round((TDEE - 1102 * $slider.slider(\"value\"))) + \"* kcal per day (not including exercise).<br/><br/>BMR: \" + BMR + \" kcal<br/>TDEE: \" + TDEE + \" kcal<br/>BMI: \" + BMI + \"</td><br/><br/>* Eating less than 1200 kcal daily is not recommended.\");\n }\n } else\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Please fill in all fields.</span>\");\n }", "function calculateResults() {\n //UI vars\n const height = document.querySelector('#height').value;\n const weight = document.querySelector('#weight').value;\n const age = document.querySelector('#age').value;\n const sex = document.querySelector('#sex').value;\n const activity = document.querySelector('#activity').value;\n\n //Output vars\n const dailyCalorieRequirements = document.querySelector('#dailyCalorie');\n const daliyProteinIntake = document.querySelector('#dailyProtein');\n const dailyCarbsIntake = document.querySelector('#dailyCarbs');\n const dailyFatIntake = document.querySelector('#dailyFat');\n\n //calculating basal metabolic rate\n const bmr = ((10 * weight) + (6.25 * height) - (5 * age)) + parseFloat(sex);\n \n if (isFinite(bmr)) {\n let dailyCalorie = bmr * parseFloat(activity);\n dailyCalorieRequirements.value = Math.round(dailyCalorie);\n daliyProteinIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 25, 'p');\n dailyCarbsIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 35, 'c');\n dailyFatIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 40, 'f');\n displayResults();\n hideLoading();\n displayMacrosRatioChart();\n } else {\n showError('Please check your numbers');\n }\n}", "function processForm() {\n // validate elevation\n if ($('#mtnElevation').val() < 4003 || $('#mtnElevation').val() > 6288) {\n $('#alertMsg').html('Elevation must be between 4,003 and 6,288 feet.');\n $('#mtnElevation').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate effort\n if ($('#mtnEffort').val() === '') {\n $('#alertMsg').html('Please select an effort.');\n $('#mtnEffort').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate image\n if ($('#mtnImage').val() === '') {\n $('#alertMsg').html('Please enter an image name.');\n $('#mtnImage').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate lat / lng\n // Note: Can break into Lat and Lgn checks, and place cursor as needed\n var regex = /^([-+]?)([\\d]{1,2})(((\\.)(\\d+)(,)))(\\s*)(([-+]?)([\\d]{1,3})((\\.)(\\d+))?)$/;\n var latLng = `${$('#mtnLat').val()},${$('#mtnLng').val()}`;\n if (! regex.test(latLng)) {\n $('#alertMsg').html('Latitude and Longitude must be numeric.');\n $('#alertMsg').show();\n return false;\n }\n\n // Form is valid\n $('#alertMsg').html('');\n $('#alertMsg').hide();\n\n return true;\n }", "function CalculateResults()\r\n {\r\n var inputsAllValid;\r\n\r\n // Fetch all input values from the on-screen form.\r\n\r\n inputsAllValid = FetchInputValues();\r\n\r\n // If the fetched input values are all valid...\r\n\r\n if (inputsAllValid)\r\n {\r\n // Do the natural gas pressure loss calculation.\r\n\r\n DoCalculation();\r\n\r\n // Display the results of the calculation.\r\n\r\n DisplayResults();\r\n }\r\n }", "function formValidation()\n{\n let principalCheck = document.forms[\"mortgageForm\"][\"principalAmount\"].value;\n if (isNaN(principalCheck) == true)\n {\n alert(\"Principal value must be a number\");\n return false;\n }\n else if (principalCheck < 0)\n {\n alert(\"Principal value must be positive\");\n return false;\n }\n let interestCheck = document.forms[\"mortgageForm\"][\"interestRate\"].value\n if (isNaN(interestCheck) == true)\n {\n alert(\"Interest value must be a number\");\n return false;\n }\n else if (interestCheck < 0)\n {\n alert(\"Interest rate must be positive\");\n return false;\n }\n else if (interestCheck > 100)\n {\n alert(\"Interest rate must be below 100%\");\n return false;\n }\n let termCheck = document.forms[\"mortgageForm\"][\"mortgageLength\"].value\n if (isNaN(termCheck) == true)\n {\n alert(\"Term length must be a number\");\n return false;\n }\n else if (termCheck < 5)\n {\n alert(\"Mortgage length must be at least five years\");\n return false;\n }\n else if (termCheck > 50)\n {\n alert(\"Mortgage length cannot be greater than fifty years\");\n return false;\n }\n}", "function processForm() {\n //getting all the cookies numbers of different types from the form //after the form is being submitted\n var small = document.getElementById('treatSmall').value;\n \n var medium = document.getElementById('treatMedium').value;\n \n var large = document.getElementById('treatLarge').value;\n \n \n //to calculate the happiness score\n //to convert string to integer used parseInt\n var happinessScore = (parseInt(1*small) + parseInt(2*medium) + parseInt(3*large));\n console.log(happinessScore);\n \n //now, if the one or more of cookies numbers is not entered or is //not an number print error message\n // if all are good, then give the result for Barley's mood.\n if(!small || !medium || !large || isNaN(small) || isNaN(medium) ||isNaN(large)){\n document.getElementById(\"error\").innerHTML = \"Please enter all valid postive intgers.\";\n }else if(happinessScore < 10) {\n document.getElementById(\"result\").innerHTML = \"sad\";\n }\n else{\n document.getElementById(\"result\").innerHTML = \"happy\";\n }\n return false;\n }", "function validateForm(regForm) {\n\t\tvar username = document.getElementById('inputname');\n\t\tvar password = document.getElementById('inputPassword');\n\t\tvar fname = document.getElementById('inputfname');\n\t\tvar lname = document.getElementById('inputlname');\n\t\tvar propic = document.getElementById('inputpropic');\n\t\tvar gender = document.getElementById('inputradio');\n\t\tvar dob = document.getElementById('day');\n\t\tvar month = document.getElementById('mon');\n\t\tvar year = document.getElementById('year');\t\t\t\n\t\tvar hobby1 = regForm.painting;\n\t\tvar hobby2 = document.getElementById('optionsRadios2');\n\t\tvar hobby3 = document.getElementById('optionsRadios3');\n\t\tvar hobby4 = document.getElementById('optionsRadios4');\n\t\tvar hobby5 = document.getElementById('optionsRadios5');\n\t\tvar hobby6 = document.getElementById('optionsRadios6');\n\t\tvar country = document.getElementById('inputcountry');\n\t\tvar phnum = document.getElementById('inputPhone');\n\n\t\tvar extension=propic.value.split('.').pop('.');\n\n\t\tvar phone_pattern = /^(\\+)(\\d{2})(\\s)(\\({1})(\\d{3})(\\){1})(\\-{1})(\\d{3}-)(\\d{4})$/;\n\n\t\tif(username.value==null || username.value==\"\") {\n\t\t\t\tusrname_validation(username);\n\t\t\t}\n\t\t\telse if(password.value==null || password.value==\"\") {\n\t\t\t\tpwd_validation(password);\n\t\t\t}\n\t\t\telse if(fname.value==null || fname.value==\"\") {\n\t\t\t\tfname_validation(fname);\n\t\t\t}\t\t\t\t\t\n\t\t\telse if(lname.value==null || lname.value==\"\") {\n\t\t\t\tlname_validation(lname);\n\t\t\t}\n\t\t\telse if(propic.value==null || propic.value==\"\") {\n\t\t\t\tpropic_validation(propic);\n\t\t\t}\n\t\t\telse if(extension != \"jpg\" && extension != \"png\" && extension != \"gif\") {\n\t\t\t\tpropic_validation(propic);\n\t\t\t}\n\t\t\telse if(dob.value==\"sel\") {\n\t\t\t\tdob_validation(dob);\t\n\t\t\t}\n\t\t\telse if(month.value==\"sel\") {\n\t\t\t\tdob_validation(month);\n\t\t\t}\t\n\t\t\telse if(year.value==\"sel\") {\n\t\t\t\tdob_validation(year);\t\t\t\t \n\t\t\t}\n\t\t\t\n\t\t\telse if(hobby1.checked==false) {\n\t\t\t\thobby_validation(hobby1);\n\t\t\t}\n\t\t\telse if(country.selectedIndex<0) {\n\t\t\t\tcountry_validation(country);\n\t\t\t}\n\t\t\telse if(phnum.value==null || phnum.value==\"\") {\n\t\t\t\tphone_validation(phnum);\t\n\t\t\t}\n\t\t\telse if(!(phnum.value.match(phone_pattern))) {\n\t\t\t\tphone_validation(phnum);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdocument.getElementById('alertmessage').style.display=\"block\";\n\t\t\t}\n\t\t\t\t\t\n\t\t\t\nreturn false;\n}", "function validateForm() {\n validateFirstName();\n validateLastName();\n validateStreet();\n validateCity();\n validateZipCode();\n}", "function btnCalculator() {\n const txtMonthlyPaymentEl = document.getElementById('txtMonthlyPayment');\n const txtYearlyRateEl = document.getElementById('txtYearlyRate');\n const listNumOfYearsEl = document.getElementById('listNumOfYears');\n const errorLogEl = document.getElementById('errorLog');\n const futureValueEl = document.getElementById('futureValue');\n\n // Determine form values provided by user\n const monthlyPayment = txtMonthlyPaymentEl ? txtMonthlyPaymentEl.value : 0;\n const rate = txtYearlyRateEl ? txtYearlyRateEl.value : 0;\n const years = listNumOfYearsEl ? listNumOfYearsEl.value : 0;\n\n // --- Form Validation ---\n\n const monthlyPaymentValidator = new Validator('Monthly Payment', monthlyPayment);\n monthlyPaymentValidator.addRequiredField();\n monthlyPaymentValidator.addRequiredFloatField();\n monthlyPaymentValidator.addFloatMinField(100);\n\n const rateValidator = new Validator('Interest Rate', rate);\n rateValidator.addRequiredField();\n rateValidator.addRequiredFloatField();\n rateValidator.addFloatMaxField(100);\n\n const errorLog = [];\n const monthlyPaymentValidation = monthlyPaymentValidator.validate();\n const rateValidation = rateValidator.validate();\n\n // --- Render Results ---\n\n if (monthlyPaymentValidation && rateValidation) {\n // Send future value calculation to client display\n errorLogEl.innerHTML = '';\n const futureValue = FinanceCalculator.calculateFutureValue(monthlyPayment, rate, years);\n if (futureValueEl) futureValueEl.innerHTML = FinanceCalculator.convertToCurrency(futureValue);\n } else {\n // Send error messages to client display\n if (futureValueEl) futureValueEl.innerHTML = '';\n if (!monthlyPaymentValidation) {\n for (const message of monthlyPaymentValidator.messages) {\n errorLog.push(message);\n }\n }\n if (!rateValidation) {\n for (const message of rateValidator.messages) {\n errorLog.push(message);\n }\n }\n let errorLogMessage = '<ul>';\n for (const msg of errorLog) {\n errorLogMessage += `<li>${msg}</li>`;\n }\n errorLogMessage += '</ul>';\n errorLogEl.innerHTML = errorLogMessage;\n }\n}", "function validateForm(){\n\t\n\tvar boo1 = validateLabPerson();\n\tvar boo2 = validateBioPerson();\n\tvar boo3 = validatePI();\n\tvar boo4 = validateBillTo();\n\tvar boo5 = validateRunType();\n\n\tvar boo6 = validateAllTables();\n//\tvar boo6 = true;\n\n\tvar boo7 = validateDate();\n\tvar boo8 = validateIAccept();\n\n\tvar boo9 = validateConcentrationUnit();\n\tvar boo10 = validateTubesAndLanes();\n\t\n//\talert(\"boo1 = \" + boo1 + \" boo2 = \" + boo2 + \" boo3 = \" + boo3 + \" boo4 = \" + boo4 +\" boo5 = \" + boo5 +\" boo6 = \" + boo6 + \" boo7 = \" + boo7 + \" boo8 = \" + boo8 + \" boo9 = \" + boo9 + \" boo10 = \" + boo10);\n\tif (boo1 && boo2 && boo3 && boo4 && boo5 && boo6 && boo7 && boo8 && boo9 && boo10){\t\n//\tif(validateLabPerson() && validateBioPerson() && validatePI() && validateBillTo() && validateRunType() && validateTable()){\n\t\t//insert fields used to generate csv\n\t\tinsertTableSize();\t\t\t\t\t// insert size of all table - used when generating csv file\n\t\tgenerateOrderNoteID();\t\t\t\t// insert orderNoteID\n\t\taddPI2TubeTag();\t\t\t\t\t// indsæt \"de tre tegn\" (fra PI) i tubetaggen.\n\t\tsetVersion();\t\t\t\t\t\t// insert the version number in the hidden field.\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n\t\n\treturn false;\n}", "function processForm(){\t\n\t//set an error message variable (start as an empty string)\n\tvar msg = \"\";\n\t\n\t//validate the name! (call a function to do this)\n\tvar name = checkName();\n\t//check for a return...if it is returned, set error variable to false\n\tif(name == true){\n\t\tmsg\t= false;\n\t}\t\n\t\n\t//validate email!\n\tvar email = checkEmail();\n\t//check for a return...\n\tif(email == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//validate select menus\n\t//this is easier if we use separate functions, because here we only have to check for false (if they have entered something correct, no reason to change it). modifying the original functions to work both on submit and on change would be harder, though certainly possible. something for them to consider in the future.\n\tvar charType = theForm.charType;\n\t\n\tif(charType.options[charType.selectedIndex].value == \"X\"){\n\t\tcharType.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a character.</span>';\n\t\tmsg = false;\n\t}\n\t\n\tvar job = theForm.charJob;\n\t\n\tif(job.options[job.selectedIndex].value == \"X\"){\n\t\tjob.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a job.</span>';\n\t\tmsg = false;\n\t}\n\t\n\t\n\t/*validate checkbox*/\n\tvar spam = checkChecker();\n\tif(spam == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//finally, check for errors\n\tif(msg == false){\n\t\t//return false, normally, but we are always returning false\tfor testing purposes\n\t}else{\n\t\t//submit form\n\t}\n\t//alert(msg);\n\t//prevent form from submitting\n\treturn false;\n}", "function validateForm() {\n\n\tvar emaildMandatory = \"\";\n\tvar passwordMandatory = \"\";\n\tvar countryMandatory = \"\";\n\tvar lScoreMandatory = \"\";\n\tvar sScoreMandatory = \"\";\n\tvar wScoreMandatory = \"\";\n\tvar rScoreMandatory = \"\";\n\tvar genderMandatory = \"\";\n\tvar lDateMandatory = \"\";\n\tvar dobMandatory = \"\";\n\tvar proMandatory = \"\"\n\tvar credentialMandatory = \"\"\n\tvar isFormValid = true;\n\tvar crsScoreMandatory = \"\";\n\n\tif (String(document.getElementById(\"email\").value).length == 0) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory = \"*Email is Mandatory\";\n\t\tisFormValid = false;\n\t} else if (!validateEmail(document.getElementById(\"email\").value)) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory += \"*Entered Email is invalid\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'green');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t}\n\n\tif (!validateGender()) {\n\t\tgenderMandatory += \"*Gender is Mandatory\";\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'red');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'green');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t}\n\n\tif (!validateCountry()) {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'red');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t\tcountryMandatory += \"*Country is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'green');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t}\n\n\tif (!validateCRS()) {\n\t\tif ($('#calButton').is(':visible')) {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*You should calculate the CRS Score. Please click 'Calculate' button\";\n\t\t\t$(\"#calButton\").click(function() {\n\t\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t\t$(\"#crs\").css('border-right-color', 'green');\n\t\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\t\tcrsScoreMandatory = \"\";\n\t\t\t})\n\t\t} else {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*Make sure proper IELTS score is provided.\";\n\t\t}\n\t\tisFormValid = false;\n\t}\n\n\tif (!validateCredential()) {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'red');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t\tcredentialMandatory += \"*Educational Credential is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'green');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLScore()) {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'red');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t\tlScoreMandatory += \"*Listening Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'green');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateRScore()) {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'red');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t\trScoreMandatory += \"*Reading Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'green');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateWScore()) {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'red');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t\twScoreMandatory += \"*Writing Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'green');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateSScore()) {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'red');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t\tsScoreMandatory += \"*Speaking Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'green');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateDob()) {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'red');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t\tdobMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'green');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLDate()) {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'red');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t\tlDateMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'green');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t}\n\n\tif (!validateProvince()) {\n\t\tproMandatory += \"*Please select atleast one province\";\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'red');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'green');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t}\n\n\tif (isFormValid) {\n\t\tshowSuccess();\n\t}\n\n\tdocument.getElementById('emailinvalid').innerHTML = emaildMandatory;\n\tdocument.getElementById('dobinvalid').innerHTML = dobMandatory;\n\tdocument.getElementById('cocinvalid').innerHTML = countryMandatory;\n\tdocument.getElementById('lscoreinvalid').innerHTML = lScoreMandatory;\n\tdocument.getElementById('sscoreinvalid').innerHTML = sScoreMandatory;\n\tdocument.getElementById('wscoreinvalid').innerHTML = wScoreMandatory;\n\tdocument.getElementById('rscoreinvalid').innerHTML = rScoreMandatory;\n\tdocument.getElementById('ldateinvalid').innerHTML = lDateMandatory;\n\tdocument.getElementById('provinceinvalid').innerHTML = proMandatory;\n\tdocument.getElementById('genderinvalid').innerHTML = genderMandatory;\n\tdocument.getElementById('eduinvalid').innerHTML = credentialMandatory;\n\tdocument.getElementById('crsinvalid').innerHTML = crsScoreMandatory;\n}", "function getFormValuesAndDisplayResults() {\n\tgetFormValues();\n\tlet monthlyPayment = calcMonthlyPayment(principle, loanYears, interest);\n\tdocument.getElementById(\"calc-monthly-payment\").innerHTML = monthlyPayment;\n}", "function getFormValues(form) \r\n{\r\n\t//initialize vars\r\n\tvar locationOption = \"\";\r\n\tvar groupOption = \"\";\r\n var metricOption = \"\";\r\n var yearOption = \"\";\r\n var gpaOption = \"\";\r\n var mathOption = \"\";\r\n var verbalOption = \"\";\r\n var genderOption = \"\";\r\n \r\n //for each element in the form...\r\n for (var i = 0; i < form.elements.length; i++ ) {\r\n \t\r\n \t//get which location the user has selected\r\n \tif (form.elements[i].name == \"Location\") {\r\n \tlocationOption += form.elements[i].value;\r\n }\r\n \t\r\n \t//get which \"group\" button is checked\r\n if (form.elements[i].name == \"groups\") {\r\n if (form.elements[i].checked == true) {\r\n groupOption += form.elements[i].value;\r\n }\r\n }\r\n \r\n //and which \"metric\" button is checked\r\n if (form.elements[i].name == \"metrics\") {\r\n if (form.elements[i].checked == true) {\r\n metricOption += form.elements[i].value;\r\n }\r\n }\r\n \r\n //get the metric drop-down-menu values\r\n if (form.elements[i].name == \"gpaSelector\") {\r\n \tgpaOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"satMathSelector\") {\r\n \tmathOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"satVerbalSelector\") {\r\n \tverbalOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"genderSelector\") {\r\n \tgenderOption += form.elements[i].value;\r\n }\r\n \r\n //and which \"year\" button is checked\r\n if (form.elements[i].name == \"years\") {\r\n if (form.elements[i].checked == true) {\r\n yearOption += form.elements[i].value;\r\n }\r\n }\r\n }\r\n \r\n //update globals\r\n selectedLocation = locationOption;\r\n selectedGroup = groupOption;\r\n selectedMetric = metricOption;\r\n selectedYear = yearOption;\r\n selectedGPA = gpaOption;\r\n\tselectedMath = mathOption;\r\n\tselectedVerbal = verbalOption;\r\n\tselectedGender = genderOption;\r\n\t\r\n\t//we only care about the drop-down associated with the selected metric\r\n\tswitch(selectedMetric)\r\n\t{\r\n\t\tcase \"None\":\r\n\t\t\timportantMetric = \"None\";\r\n\t\t\tbreak;\r\n\t\tcase \"GPA\":\r\n\t\t\timportantMetric = selectedGPA;\r\n\t\t\tbreak;\r\n\t\tcase \"SAT Math\":\r\n\t\t\timportantMetric = selectedMath;\r\n\t\t\tbreak;\r\n\t\tcase \"SAT Verbal\":\r\n\t\t\timportantMetric = selectedVerbal;\r\n\t\t\tbreak;\r\n\t\tcase \"Male / Female\":\r\n\t\t\timportantMetric = selectedGender;\r\n\t\t\tbreak;\r\n\t\tcase \"Visited\":\r\n\t\t\timportantMetric = \"Visited\";\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\timportantMetric = \"ERROR\";\r\n\t}\r\n \r\n //create associative array\r\n\tvar optionSettings = {};\r\n\toptionSettings['location'] = selectedLocation;\r\n\toptionSettings['group'] = selectedGroup;\r\n\toptionSettings['metric'] = selectedMetric;\r\n\toptionSettings['year'] = selectedYear;\r\n\toptionSettings['dropVal'] = importantMetric;\r\n\t\r\n\treturn optionSettings; \r\n}//end getValues", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst schoolValue = school.value.trim();\n\tconst levelValue = level.value.trim();\n\tconst skillValue = skill.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else if (isNaN(phoneValue)) {\n\t\tsetErrorFor(phone, \"Please enter a valid phone number\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check School\n\tif (schoolValue === \"\") {\n\t\tsetErrorFor(school, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(school);\n\t}\n\n\t// Check Level\n\tif (levelValue === \"\") {\n\t\tsetErrorFor(level, \"Please select a level\");\n\t} else {\n\t\tsetSuccessFor(level);\n\t}\n\n\t// Check LevSkills\n\tif (skillValue === \"\") {\n\t\tsetErrorFor(skill, \"Please enter a skill\");\n\t} else {\n\t\tsetSuccessFor(skill);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password2);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function validate(){\n\nvar errMsg = \"\"; /* stores the error message */\nvar result = true; /* assumes no errors */\n\n/*get values from the form*/\n\nvar fName = document.getElementById(\"fname\").value;\nvar lName = document.getElementById(\"lname\").value;\nvar dob = document.getElementById(\"dob\").value;\nvar streetAddr = document.getElementById(\"streetaddr\").value;\nvar suburb = document.getElementById(\"suburb\").value;\nvar postcode = document.getElementById(\"postcode\").value;\nvar phoneNo = document.getElementById(\"phnno\").value;\nvar state = document.getElementById(\"state\").value;\nvar otherSkill = document.getElementById(\"skill\").value;\nvar email = document.getElementById(\"emailid\").value;\nvar skill = document.getElementById(\"skill\").value;\n\n/*get status from the form*/\n\nvar microsoftOffice = document.getElementById(\"microsoftoffice\").checked;\nvar touchTyping = document.getElementById(\"touchtyping\").checked;\nvar documentationSkill = document.getElementById(\"documentationskill\").checked;\nvar web = document.getElementById(\"web\").checked;\nvar dotNet = document.getElementById(\"dotnet\").checked;\nvar java = document.getElementById(\"java\").checked;\nvar otherSkills = document.getElementById(\"otherskills\").checked;\n\n/*store value in the variable*/\nvar letter = /^[A-Za-z]+$/;\nvar number = /^[0-9]+$/;\nvar date = dob.split(\"/\");\n\n/*Validate first name */\n\nif(fName.match(letter)){ /*for alphabet*/\nif((fName.length) <= 15){ /*for length*/\n}else{\nerrMsg =errMsg.concat(\"First Name Should not contain more than 15 characters!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"First Name Should contain only alphabets!\\n\");\nresult = false;\n}\n\n/*Validate Second name*/\n\nif(lName.match(letter)){ /*for alphabet*/\nif((lName.length) <= 25){ /*for length*/\n}else{\nerrMsg =errMsg.concat(\"Last Name Should not contain more than 25 characters!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"Last Name Should contain only alphabets!\\n\");\nresult = false;\n}\n\n/*Validate date*/\n\n\tif(date[0] <=31 && date[0] >= 1 && date[1] >= 1 && date[1] <= 12 && date[2] >= 1 && date[2] <= 2014 ){\t\t\n\t}else{errMsg +=\"Wrong date.\\n\";\n\t\tresult = false;}\n\t\t\n/*Validate Adders*/\n\nif((streetAddr.length) > 50){ /*for length*/\nerrMsg =errMsg.concat(\"Street Address should not contain for than 50 characters.\\n\");\nresult = false;\n}\n\nif((suburb.length) > 25){ /*for length*/\nerrMsg =errMsg.concat(\"Suburb/Town Address should not contain for than 25 characters.\\n\");\nresult = false;\n}\n\nif(postcode.match(letter)){ /*for letter*/\nerrMsg = errMsg.concat(\"postcode must be integer.\\n\");\nresult = false;\n\n}\n\nif((postcode.length) != 4){ /*for length*/\nerrMsg = errMsg.concat(\"postcode should contain exactly 4 characters .\\n\");\nresult = false;\n}\n\n/*Now validate state and postcode depending upon the first digit entered in postcode*/\n\nif(state == \"vic\"){\nif(postcode[0] == 3 || postcode[0] == 8){\n}else\n{errMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;}\n}\n\n\nif(state == \"nsw\"){\nif(postcode[0] == 1 || postcode == 2){\n}else{\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\n\nif(state == \"qld\"){\nif(postcode[0] == 4 || postcode[0] == 9){\n}else{\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\nif(state == \"nt\" || state == \"act\"){\nif(postcode[0] != 0){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\nif(state == \"wa\"){\nif(postcode[0] != 6){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nif(state == \"sa\"){\nif(postcode[0] != 5){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nif(state == \"tas\"){\nif(postcode[0] != 7){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nemailFormat = /^[A-Za-z]+@[A-Za-z]+.[A-Za-z]+$/;\nif(email.match(!(emailFormat))){\nerrMsg = errMsg.concat(\"Wrong email!\\n\");\nresult = false;\n}\n\n\nif(phoneNo.match(number)){\nif((phoneNo.length) == 10){\n}else{\nerrMsg =errMsg.concat(\"Phone Number Should contain 10 digits!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"Phone No should not contain alphabets!\\n\");\nresult = false;\n}\n\nif(!microsoftOffice && !touchTyping && !documentationSkill && !web && !dotNet && !java && !otherSkills)\n{\nerrMsg = errMsg.concat(\"At-least select 1 skill!\\n\");\nresult = false;\n}\n\nif(otherSkills == true){\nif(skill.trim().length < 1 ){\nerrMsg = errMsg.concat(\"Please type other skills possessed by you in text area\\n\");\nresult = false;\n\n}\n}\n\n/*if conditions not matched then execute this */\n\nif (result == false){\nalert(errMsg);\n}\n\nreturn result;\n}", "function computeBMI() {\r\n clearAll(true);\r\n\r\n // obtain user inputs\r\n var height = Number(document.getElementById(\"height\").value);\r\n var weight = Number(document.getElementById(\"weight\").value);\r\n var unittype = document.getElementById(\"unittype\").selectedIndex;\r\n\r\n if (height === 0 || isNaN(height) || weight === 0 || isNaN(weight)) {\r\n setAlertVisible(\"error-bmi-output\", ERROR_CLASS, true);\r\n document.getElementById(\"error-bmi-output\").innerHTML = errorString;\r\n } else { // convert\r\n // Perform calculation\r\n var BMI = calculateBMI(height, weight, unittype);\r\n\r\n // Display result of calculation\r\n var result = \" Your BMI index are <strong>\" + BMI + \"</strong>.\";\r\n var warning = true;\r\n if (BMI < BMI_LOWINDEX)\r\n result = \"<strong>Underweight!!</strong>\" + result + \" C'mon, McDonald is near by then.\";\r\n else if (BMI >= BMI_LOWINDEX && BMI <= BMI_HIGHINDEX) {\r\n warning = false;\r\n result = \"<strong>Normal!</strong>\" + result + \" Good exercises!\";\r\n }\r\n else // BMI > 25\r\n result = \"<strong>Overweight!!!</strong>\" + result + \" Recreation center welcome you !!\";\r\n\r\n // if we need to show warning so we show alert with warning, otherwise we show success message.\r\n if (warning) {\r\n setAlertVisible(\"warning-bmi-output\", WARNING_CLASS, true);\r\n document.getElementById(\"warning-bmi-output\").innerHTML = result;\r\n } else {\r\n setAlertVisible(\"normal-bmi-output\", SUCCESS_CLASS, true);\r\n document.getElementById(\"normal-bmi-output\").innerHTML = result;\r\n }\r\n }\r\n}", "function formValidation(){\n var result;\n\n result = textValidation(firstName,fName);\n result = textValidation(middleName,mName) && result;\n result = textValidation(sirName,lName) && result;\n result = numberValidation(unitNum,unitNumber) && result;\n result = numberValidation(StreetNum,stNumber) && result;\n result = textValidation(streetName,stName) && result;\n result = textValidation(city,cityName) && result;\n result = postCodeValidation(postCode,pCode) && result;\n result = phoneValidation(phoneNumber,phoNumber) && result;\n result = userNameValidation(userName,uName) && result;\n result = password1Validation(password1,pWord) && result;\n result = password2Validation(password2,pWordC,password1) && result;\n if (result == false){\n alert(\"Submission Failed\")\n }\n else {\n alert(\"Submission was Successful\")\n }\n return result;\n}", "function validateForm() {\n let errMsgs = [];\n let highAge = highestTeamAge();\n let lowAge = lowestTeamAge();\n let maleCheck = maleTeamMembers();\n let femaleCheck = femaleTeamMembers();\n let emailReg = /^(\\D)+(\\w)*((\\.(\\w)+)?)+@(\\D)+(\\w)*((\\.(\\D)+(\\w)*)+)?(\\.)[a-z]{2,}$/;\n let phoneReg = /^\\d{3}-\\d{3}-\\d{4}/;\n let ageReg = /^(0|(\\+)?[1-9]{1}[0-9]{0,8}|(\\+)?[1-3]{1}[0-9]{1,9}|(\\+)?[4]{1}([0-1]{1}[0-9]{8}|[2]{1}([0-8]{1}[0-9]{7}|[9]{1}([0-3]{1}[0-9]{6}|[4]{1}([0-8]{1}[0-9]{5}|[9]{1}([0-5]{1}[0-9]{4}|[6]{1}([0-6]{1}[0-9]{3}|[7]{1}([0-1]{1}[0-9]{2}|[2]{1}([0-8]{1}[0-9]{1}|[9]{1}[0-5]{1})))))))))$/;\n\n if ($(\"#teamName\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Team Name is REQUIRED\";\n }\n if ($(\"#teamType\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Team Craft Type is REQUIRED\";\n }\n if ($(\"#managerName\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Manager Name is REQUIRED\";\n }\n if ($(\"#managerPhone\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Manager Phone Number is REQUIRED\";\n }\n if ($(\"#managerEmail\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Manager Email Address is REQUIRED\";\n }\n if ($(\"#maxTeamMembers\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Maximum Number of Team Members is REQUIRED\";\n }\n if ($(\"#minMemberAge\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Minimum Member Age is REQUIRED\";\n }\n if ($(\"#maxMemberAge\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Maximum Member Age is REQUIRED\";\n }\n if ($(\"#teamGender\").val().trim() == \"\") {\n errMsgs[errMsgs.length] = \"Team Gender is REQUIRED\";\n }\n if (($(\"#teamType\").val() != \"Knitting\") && ($(\"#teamType\").val() != \"Crocheting\")) {\n errMsgs[errMsgs.length] = \"Team Type should be Knitting or Crocheting\";\n }\n if (emailReg.test($(\"#managerEmail\").val()) == false) {\n errMsgs[errMsgs.length] = \"Manager Email needs to be the correct format!\";\n }\n if (phoneReg.test($(\"#managerPhone\").val()) == false) {\n errMsgs[errMsgs.length] = \"Manager Phone Number needs to be the correct format!\";\n }\n if (ageReg.test($(\"#maxTeamMembers\").val()) == false) {\n errMsgs[errMsgs.length] = \"Maximum Number of Team Members needs to be an integer!\";\n }\n if (Number($(\"#maxTeamMembers\").val()) < Number($(\"#memberCnt\").text())) {\n errMsgs[errMsgs.length] = \"Team size too small based on current roster!\";\n }\n if (ageReg.test($(\"#minMemberAge\").val()) == false) {\n errMsgs[errMsgs.length] = \"Minimum Member Age needs to be an integer!\";\n }\n if (ageReg.test($(\"#maxMemberAge\").val()) == false) {\n errMsgs[errMsgs.length] = \"Maximum Member Age needs to be an integer!\";\n }\n if ($(\"#minMemberAge\").val() > lowAge) {\n errMsgs[errMsgs.length] = \"Minimum age is greater than current member on team!\";\n }\n if ($(\"#maxMemberAge\").val() < highAge) {\n errMsgs[errMsgs.length] = \"Maximum age is less than current member on team!\";\n }\n if (($(\"#teamGender\").val() != \"Male\") && ($(\"#teamGender\").val() != \"Female\") && ($(\"#teamGender\").val() != \"Any\")) {\n errMsgs[errMsgs.length] = \"Team Gender should be Male, Female, or Any\";\n }\n if (($(\"#teamGender\").val() == \"Male\") && (femaleCheck == \"Female\")) {\n errMsgs[errMsgs.length] = \"There is a Female member on the team.\";\n }\n if (($(\"#teamGender\").val() == \"Female\") && (maleCheck == \"Male\")) {\n errMsgs[errMsgs.length] = \"There is a Male member on the team.\";\n }\n return errMsgs;\n } // end of validateForm function", "function validateForm(event) {\n \n let name = document.querySelector(\"#name\").value;\n let email = document.querySelector(\"#email\").value;\n let phone = document.querySelector(\"#phone\").value;\n let subject = document.querySelector(\"#subject\").value;\n let message = document.querySelector(\"#message\").value;\n let radios = document.getElementsByName('gender');\n \n if(!validateName(name)){\n alert(\"Unesite vase ime.\");\n \n return false;\n }\n \n \n if(!validateEmail(email)){\n alert(\"Unesite validan email.\");\n \n return false;\n }\n \n if(!validatePhone(phone)){\n alert(\"Unesite broj telefona.\");\n \n return false;\n }\n \n if(!validateSubject(subject)){\n alert(\"Unesite temu.\");\n \n return false;\n }\n \n if(!validateMessage(message)){\n alert(\"Unesite poruku.\");\n \n return false;\n }\n \n if(!validateMessageLength(message)){\n alert(\"Poruka mora sadrzati bar 30 karaktera\");\n \n return false;\n }\n\n let gender;\n\n for (let i = 0, length = radios.length; i < length; i++){\n if (radios[i].checked){\n gender = radios[i].value;\n \n break;\n }\n }\n\n if(gender == undefined){\n gender = \"Left empty.\";\n } \n\n let date = getTodaysDate();\n\n alert(\"Ime: \" + name + \"\\nE-mail: \" + email + \"\\nTelefon: \" + phone + \"\\nTema: \" + subject + \"\\nPol: \" + gender + \"\\nPoruka: \" + message);\n \n return true;\n }", "function validateFormAndCalculatePl() {\n addCommas(\"rp-annual-input\");\n addCommas(\"rp-annual-save-input\");\n addCommas(\"rp-month-input\");\n addCommas(\"rp-expense-input\");\n }", "function validateForm() {\n var usergender = document.getElementsByName(\"gender\");\n var userdate = document.getElementById(\"date\");\n var usermonth = document.getElementById(\"month\");\n var useryear = document.getElementById(\"year\");\n var formValid = false;\n var i = 0;\n\n if (userdate.value == \"\" || userdate.value == null) {\n // alert(\"Please Input date\");\n document.getElementById(\"error\").innerHTML = \"Day is Empty\"\n document.getElementById(\"error\").style.color = \"red\"\n userdate.style.border = \"2px solid red\"\n return false;\n } else {\n\n if (!isNaN(userdate.value)) {\n if (userdate.value <= 0 || userdate.value > 31) {\n document.getElementById(\"error\").innerHTML = \"Invalid day\"\n document.getElementById(\"error\").style.color = \"red\"\n userdate.style.border = \"2px solid red\"\n return false;\n } else {\n\n userdate.style.border = \"2px solid green\"\n date = parseInt(userdate.value);\n }\n } else {\n document.getElementById(\"error\").innerHTML = \"Day must be a number\"\n document.getElementById(\"error\").style.color = \"red\"\n userdate.style.border = \"2px solid red\"\n return false;\n }\n }\n\n\n\n if (usermonth.value == \"\" || usermonth.value == null) {\n document.getElementById(\"error\").innerHTML = \"Month is Empty\"\n document.getElementById(\"error\").style.color = \"red\"\n usermonth.style.border = \"2px solid red\"\n return false;\n } else {\n if (!isNaN(usermonth.value)) {\n if (usermonth.value <= 0 || usermonth.value > 12) {\n document.getElementById(\"error\").innerHTML = \"Invalid month\"\n document.getElementById(\"error\").style.color = \"red\"\n usermonth.style.border = \"2px solid red\"\n return false;\n } else {\n usermonth.style.border = \"2px solid green\"\n month = parseInt(usermonth.value);\n }\n } else {\n document.getElementById(\"error\").innerHTML = \"Month must be a number\"\n document.getElementById(\"error\").style.color = \"red\"\n usermonth.style.border = \"2px solid red\"\n return false;\n }\n }\n\n\n if (useryear.value == \"\" || useryear.value == null) {\n document.getElementById(\"error\").innerHTML = \"Year is Empty\"\n document.getElementById(\"error\").style.color = \"red\"\n useryear.style.border = \"2px solid red\"\n return false;\n } else {\n useryear.style.border = \"\";\n if (!isNaN(useryear.value)) {\n if (useryear.value.length != 4) {\n document.getElementById(\"error\").innerHTML = \"Invalid year\"\n document.getElementById(\"error\").style.color = \"red\"\n useryear.style.border = \"2px solid red\"\n return false;\n } else {\n document.getElementById(\"error\").innerHTML = \"\"\n useryear.style.border = \"2px solid green\"\n year = parseInt(useryear.value);\n }\n } else {\n document.getElementById(\"error\").innerHTML = \"Year must be a number\"\n document.getElementById(\"error\").style.color = \"red\"\n useryear.style.border = \"2px solid red\"\n return false;\n }\n }\n\n while (!formValid && i < usergender.length) {\n if (usergender[i].checked) {\n\n gender = usergender[i].value;\n document.getElementById(\"my_gender\").style.color = \"\"\n formValid = true;\n }\n i++;\n }\n if (!formValid) {\n document.getElementById(\"my_gender\").style.color = \"red\"\n\n return false;\n }\n var validatedDetails = {\n gender: gender,\n date: date,\n month: month,\n year: year,\n valid: formValid\n }\n return validatedDetails;\n\n}", "function checkUserForm() {\n if ($(\"#FirstName\").val() == \"\") {\n alert(\"You need to enter your first name.\");\n return false;\n } else if ($(\"#LastName\").val() == \"\") {\n alert(\"You need to enter your last name.\");\n return false;\n } else if ($(\"#DOB\").val() == \"\") {\n alert(\"You need to enter your birthdate.\");\n return false;\n } else if ($(\"#DOB\").val() > getCurrentDateFormatted()) {\n alert(\"Your birthdate can't be in the future.\");\n return false;\n } else if ($(\"#height\").val() == \"\") {\n alert(\"You need to enter your height.\");\n return false;\n } else if ($(\"#height\") <= 0) {\n alert(\"Your height must be greater than 0.\");\n return false;\n } else if ($(\"#weight\").val() == \"\") {\n alert(\"You need to enter your weight.\");\n return false;\n } else if ($(\"#height\").val() <= 0) {\n alert(\"Your weight must be greater than 0.\");\n return false;\n } else {\n return true;\n }\n}", "function aggregateMyFunctions() {\n var validate = validateForm();\n var formValid = validate.valid;\n\n if (!formValid) {\n validateForm();\n return false;\n } else {\n //all other functions\n //update this functions af you write more functions\n //example \n calculateDayOfWk();\n get_and_Print_AkanName();\n return false;\n }\n}", "function validateFormUserParameter(event, state) {\n // clear all error messages\n const inputs = document.getElementsByClassName('is-danger');\n for (let i = 0; i < inputs.length; i++) {\n if (!inputs[i].classList.contains('error')) {\n inputs[i].classList.remove('is-danger');\n }\n }\n // check for blank field in setOwnGoal section\n if (state.hasOwnProperty('kcalGoal') && state.kcalGoal === '' && state.setOwnGoal === true) {\n document.getElementById('kcalGoal').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('proteinGoal') && state.proteinGoal === '' && state.setOwnGoal === true) {\n document.getElementById('proteinGoal').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('fatGoal') && state.fatGoal === '' && state.setOwnGoal === true) {\n document.getElementById('fatGoal').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('carbGoal') && state.carbGoal === '' && state.setOwnGoal === true) {\n document.getElementById('carbGoal').classList.add('is-danger');\n return { blankfield: true };\n }\n // check for blank fields in custom section\n if (state.hasOwnProperty('gender') && state.gender === '' && state.setOwnGoal === false) {\n document.getElementById('gender').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('activity') && state.activity === '' && state.setOwnGoal === false) {\n document.getElementById('activity').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('goal') && state.goal === '' && state.setOwnGoal === false) {\n document.getElementById('goal').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('weight') && state.weight === '' && state.setOwnGoal === false) {\n document.getElementById('weight').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('height') && state.height === '' && state.setOwnGoal === false) {\n document.getElementById('height').classList.add('is-danger');\n return { blankfield: true };\n }\n if (state.hasOwnProperty('age') && state.age === '' && state.setOwnGoal === false) {\n document.getElementById('age').classList.add('is-danger');\n return { blankfield: true };\n }\n \n \n // regex expression\n\n const numberRegexKcal = /^[0-9]{4}([,.][0-9]{1,2})?$/;\n const numberRegex = /^[0-9]{2,3}([,.][0-9]{1,2})?$/;\n // regex check for setOwnGoal\n if (state.hasOwnProperty('kcalGoal') && !numberRegexKcal.test(state.kcalGoal) && state.setOwnGoal === true ) {\n document.getElementById('kcalGoal').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n if (state.hasOwnProperty('proteinGoal') && !numberRegex.test(state.proteinGoal) && state.setOwnGoal === true ) {\n document.getElementById('proteinGoal').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n if (state.hasOwnProperty('fatGoal') && !numberRegex.test(state.fatGoal) && state.setOwnGoal === true ) {\n document.getElementById('fatGoal').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n if (state.hasOwnProperty('carbGoal') && !numberRegex.test(state.carbGoal) && state.setOwnGoal === true ) {\n document.getElementById('carbGoal').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n // regex check for custom section\n if (state.hasOwnProperty('weight') && !numberRegex.test(state.weight) && state.setOwnGoal === false ) {\n document.getElementById('weight').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n if (state.hasOwnProperty('height') && !numberRegex.test(state.height) && state.setOwnGoal === false ) {\n document.getElementById('height').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n if (state.hasOwnProperty('age') && !numberRegex.test(state.age) && state.setOwnGoal === false ) {\n document.getElementById('age').classList.add('is-danger');\n return { blankfield: false ,invalidFormat: true };\n }\n // own callory set makro not match exception\n const calculationSum = state.proteinGoal * 4 + state.fatGoal * 9 + state.carbGoal * 4;\n\n if ( calculationSum !== Number(state.kcalGoal) && state.setOwnGoal === true ) {\n document.getElementById('kcalGoal').classList.add('is-danger');\n return { invalidSum: true };\n }\n\n }", "function validateForm() {\r\n var YES_RADIO_VALUE = 0;\r\n var NO_RADIO_VALUE = 1;\r\n\r\n // check if all fences have been checked yes or no\r\n $(\"input[name^=fence_\").each(function() {\r\n fenceIsChecked = $(this).is(\"checked\"); // is the fence radio button checked?\r\n\r\n // fences are mandatory\r\n if (fenceIsChecked == false) {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara Já eða Nei í öllum girðingum!</p>\");\r\n return false;\r\n }\r\n });\r\n\r\n // all evaluation questions have to be answered but only if all fences have been passed\r\n if(passesFences() == true) {\r\n\r\n var evaluationValue;\r\n $(\"input:hidden[name$='_hidden']\").each(function() {\r\n evaluationValue = $(this).attr(\"value\");\r\n if (evaluationValue == null || evaluationValue == \"\" || evaluationValue == \" \") {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara öllum matsspurningum</p>\");\r\n return false;\r\n }\r\n });\r\n\r\n var review = document.forms[\"EvaluationPaper\"][\"review\"].value;\r\n\r\n // review is mandatory\r\n if (review == null || review == \"\" || review == \" \") {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Það þarf að skrifa texta í reit fyrir mat!</p>\");\r\n return false;\r\n }\r\n\r\n // propose_acceptance is mandatory\r\n var propose_acceptance = document.forms[\"EvaluationPaper\"][\"propose_acceptance\"].value;\r\n if (propose_acceptance == null || propose_acceptance == \"\" || propose_acceptance == \" \"){\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara hvort að mælt sé með að umsókn verði styrkt!</p>\");\r\n return false;\r\n }\r\n\r\n // proposal_discussion is mandatory\r\n var proposal_discussion = document.forms[\"EvaluationPaper\"][\"proposal_discussion\"].value;\r\n if (proposal_discussion == null || proposal_discussion == \"\" || proposal_discussion == \" \"){\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara hvort að matsmaður vilji að umsóknin verði rædd á matsfundi</p>\");\r\n return false;\r\n }\r\n }\r\n\r\n $(\"#form_field_error\").html(\" \");\r\n return true;\r\n }", "function validate_form() {\n valid = true;\n\n if (document.form.age.value == \"\") {\n alert(\"Please fill in the Age field.\");\n valid = false;\n }\n\n if (document.form.heightFeet.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Height field.\");\n valid = false;\n }\n\n if (document.form.weight.value == \"\") {\n alert(\"Please fill in the Weight field.\");\n valid = false;\n }\n\n if (document.form.position.selectedIndex == 0) {\n alert(\"Please fill in the Position field.\");\n valid = false;\n }\n\n if (document.form.playingStyle.selectedIndex == 0) {\n alert(\"Please fill in the Playing Style field.\");\n valid = false;\n }\n\n if (document.form.heightInches.selectedIndex == 0) {\n alert(\"Please fill in the Maximum Price field.\");\n valid = false;\n }\n\n return valid;\n}", "function validateForm(event) {\n // Prevent the browser from reloading the page when the form is submitted\n event.preventDefault();\n\n // Validate that the name has a value\n const name = document.querySelector(\"#name\");\n const nameValue = name.value.trim();\n const nameError = document.querySelector(\"#nameError\");\n let nameIsValid = false;\n\n if (nameValue) {\n nameError.style.display = \"none\";\n nameIsValid = true;\n } else {\n nameError.style.display = \"block\";\n nameIsValid = false;\n }\n\n // Validate that the answer has a value of at least 10 characters\n const answer = document.querySelector(\"#answer\");\n const answerValue = answer.value.trim();\n const answerError = document.querySelector(\"#answerError\");\n let answerIsValid = false;\n\n if (checkInputLength(answerValue, 10) === true) {\n answerError.style.display = \"none\";\n answerIsValid = true;\n } else {\n answerError.style.display = \"block\";\n answerIsValid = false;\n }\n\n // Validate that the email has a value and a valid format\n const email = document.querySelector(\"#email\");\n const emailValue = email.value.trim();\n const emailError = document.querySelector(\"#emailError\");\n const invalidEmailError = document.querySelector(\"#invalidEmailError\");\n let emailIsValid = false;\n\n if (emailValue) {\n emailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n emailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n if (checkEmailFormat(emailValue) === true) {\n invalidEmailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n invalidEmailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n // Validate that the answer has a value of at least 15 characters\n const address = document.querySelector(\"#address\");\n const addressValue = address.value.trim();\n const addressError = document.querySelector(\"#addressError\");\n addressIsValid = false;\n\n if (checkInputLength(addressValue, 15) === true) {\n addressError.style.display = \"none\";\n addressIsValid = true;\n } else {\n addressError.style.display = \"block\";\n addressIsValid = false;\n }\n\n // Display form submitted message if all fields are valid\n if (\n nameIsValid === true &&\n answerIsValid === true &&\n emailIsValid === true &&\n addressIsValid === true\n ) {\n submitMessage.style.display = \"block\";\n } else {\n submitMessage.style.display = \"none\";\n }\n}", "function grades()\n{\n\tvar hwavg, mtexam, finalexam, acravg, finalavg, grade;\n\t\n\tvar errorMessage = \"<span style='color: #000000; background-color: #FF8199;\" + \n\t\t\t\t\t\t\"width: 100px;font-weight: bold; font-size: 14px;'>\" +\n\t\t\t\t\t\t\"Input must be integers between 0 and 100</span>\";\n\n\thwavg = document.forms[\"myform\"].elements[\"hwavg\"].value;\n\tmtexam = document.forms[\"myform\"].elements[\"midterm\"].value;\n\tfinalexam = document.forms[\"myform\"].elements[\"finalexam\"].value;\n\tacravg = document.forms[\"myform\"].elements[\"acravg\"].value;\n\n\thwnum = parseInt(hwavg, 10);\n\tmtnum = parseInt(mtexam, 10);\n\tfinnum = parseInt(finalexam, 10);\n\tacrnum = parseInt(acravg, 10);\n\n\n\tif( isNaN(hwnum) || isNaN(mtnum) || isNaN(finnum) || isNaN(acrnum) || \n\t\thwnum < 0 || mtnum < 0 || finnum < 0 || acrnum < 0 || \n\t\thwnum > 100 || mtnum > 100 || finnum > 100 || acrnum > 100)\n {\n \tdocument.getElementById(\"errorMsg\").innerHTML = errorMessage; \n }\n \telse \n \t{\n\n\t\tfinalavg = (.5 * hwnum) + (.2 * mtnum) + (.2 * finnum) + (.1 * acrnum);\n\n\t\tif(finalavg >= 90) \n\t\t\t{grade = \"A\";}\n\t\telse if (finalavg >= 80 && finalavg < 90) \n\t\t\t{grade = \"B\";}\n\t\telse if (finalavg >= 70 && finalavg < 80) \n\t\t\t{grade = \"C\";}\n\t\telse if (finalavg >= 60 && finalavg < 70) \n\t\t\t{grade = \"D \\nStudent will need to retake the course\";}\n\t\telse if (finalavg < 60)\n\t\t\t{grade = \"F \\nStudent will need to retake the course\";}\n \n \tdocument.forms[\"myform\"].elements[\"result\"].value = ( \"Final Average: \" + finalavg.toFixed(0) +\n \t\t\"\\nFinal Grade: \" + grade);\n }\n\n \n\t\n}", "function validateForm(form) {\n\tvar reqField = []\n\treqField.push(form.elements['firstName']);\n\treqField.push(form.elements['lastName']);\n\treqField.push(form.elements['address1']);\n\treqField.push(form.elements['city']);\n\treqField.push(form.elements['state']);\n\tzip = form.elements['zip']\n\tbirthdate = form.elements['birthdate']\n\n\ttoReturn = true;\n\n\treqField.forEach(function(field) {\n\t\tif (field.value.trim().length == 0) {\n\t\t\tfield.className = field.className + \" invalid-field\";\n\t\t\ttoReturn = false;\n\t\t} else {\n\t\t\tfield.className = 'form-control'\n\t\t}\n\t});\n\n\tif (document.getElementById('occupation').value == 'other') {\n\t\tvar otherBox = document.getElementsByName('occupationOther')[0]\n\t\tif (otherBox.value.trim().length == 0) {\n\t\t\totherBox.className = otherBox.className + ' invalid-field';\n\t\t\ttoReturn = false;\n\t\t} else {\n\t\t\totherBox.className = 'form-control'\n\t\t}\n\t}\n\n\tvar zipRegExp = new RegExp('^\\\\d{5}$');\n\n\tif (!zipRegExp.test(zip.value.trim())) {\n\t\tzip.className = zip.className + ' invalid-field';\n\t\ttoReturn = false;\n\t} else {\n\t\tzip.className = 'form-control';\n\t}\n\n\tif (birthdate.value.trim().length == 0) {\n\t\tbirthdate.className = birthdate.className + ' invalid-field'\n\t} else {\n\t\tvar dob = new Date(birthdate.value);\n\t\tvar today = new Date();\n\t\tif (today.getUTCFullYear() - dob.getUTCFullYear() == 13) {\n\t\t\tif (today.getUTCMonth() - dob.getUTCMonth() == 0) {\n\t\t\t\tif (today.getUTCDate() - dob.getUTCDate() == 0) {\n\t\t\t\t\tcorrectAge(birthdate)\n\t\t\t\t} else if (today.getUTCDate() - dob.getUTCDate() < 0) {\n\t\t\t\t\ttoReturn = tooYoung(birthdate);\n\t\t\t\t} else {\n\t\t\t\t\tcorrectAge(birthdate)\n\t\t\t\t}\n\t\t\t} else if (today.getUTCMonth() - dob.getUTCMonth() < 0) {\n\t\t\t\ttoReturn = tooYoung(birthdate);\n\n\t\t\t} else {\n\t\t\t\tcorrectAge(birthdate)\n\t\t\t}\n\t\t} else if (today.getUTCFullYear() - dob.getUTCFullYear() < 13) {\n\t\t\ttoReturn = tooYoung(birthdate);\n\n\t\t} else {\n\t\t\tcorrectAge(birthdate)\n\t\t}\n\t}\n\n\treturn toReturn;\n}", "function compute(form) {\n var val1 = parseInt(form.day.value, 10)\n if ((val1 < 0) || (val1 > 31)) {\n alert(\"Day is out of range\")\n }\n var val2 = parseInt(form.month.value, 10)\n if ((val2 < 0) || (val2 > 12)) {\n alert(\"Month is out of range\")\n }\n var val2x = parseInt(form.month.value, 10)\n var val3 = parseInt(form.year.value, 10)\n if (val3 < 1900) {\n alert(\"You're that old!\")\n }\n if (val2 == 1) {\n val2x = 13;\n val3 = val3-1\n }\n if (val2 == 2) {\n val2x = 14;\n val3 = val3-1\n }\n var val4 = parseInt(((val2x+1)*3)/5, 10)\n var val5 = parseInt(val3/4, 10)\n var val6 = parseInt(val3/100, 10)\n var val7 = parseInt(val3/400, 10)\n var val8 = val1+(val2x*2)+val4+val3+val5-val6+val7+2\n var val9 = parseInt(val8/7, 10)\n var val0 = val8-(val9*7)\n form.result1.value = months[val2]+\" \"+form.day.value +\", \"+form.year.value\n form.result2.value = days[val0]\n}", "function validateForm() {\n\t// get the values from the inputs\n\tconst firstNameValue = firstName.value.trim();\n\tconst lastNameValue = lastName.value.trim();\n\tconst emailValue = email.value.trim();\n\tconst phoneValue = phone.value.trim();\n\tconst countryValue = country.value.trim();\n\tconst cityValue = city.value.trim();\n\tconst businessValue = business.value.trim();\n\tconst roleValue = role.value.trim();\n\tconst addressValue = address.value.trim();\n\tconst passwordValue = password.value.trim();\n\tconst password2Value = password2.value.trim();\n\n\t// Check Firstname\n\tif (firstNameValue === \"\") {\n\t\tsetErrorFor(firstName, \"First name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(firstName);\n\t}\n\n\t// Check Firstname\n\tif (lastNameValue === \"\") {\n\t\tsetErrorFor(lastName, \"Last name cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(lastName);\n\t}\n\n\t// Check Email\n\tif (emailValue === \"\") {\n\t\tsetErrorFor(email, \"Email cannot be blank\");\n\t} else if (!isEmail(emailValue)) {\n\t\tsetErrorFor(email, \"Please enter a valid email\");\n\t} else {\n\t\tsetSuccessFor(email);\n\t}\n\n\t// Check Number\n\tif (phoneValue === \"\") {\n\t\tsetErrorFor(phone, \"Phone number cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(phone);\n\t}\n\n\t// Check country\n\tif (countryValue === \"\") {\n\t\tsetErrorFor(country, \"Please select a country\");\n\t} else {\n\t\tsetSuccessFor(country);\n\t}\n\n\t// Check City\n\tif (cityValue === \"\") {\n\t\tsetErrorFor(city, \"Please enter a city\");\n\t} else {\n\t\tsetSuccessFor(city);\n\t}\n\n\t// Check business\n\tif (businessValue === \"\") {\n\t\tsetErrorFor(business, \"School cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(business);\n\t}\n\n\t// Check role\n\tif (roleValue === \"\") {\n\t\tsetErrorFor(role, \"Please select a role\");\n\t} else {\n\t\tsetSuccessFor(role);\n\t}\n\n\t// Check addresss\n\tif (addressValue === \"\") {\n\t\tsetErrorFor(address, \"Please enter a address\");\n\t} else {\n\t\tsetSuccessFor(address);\n\t}\n\n\t// Check passwords\n\tif (passwordValue === \"\") {\n\t\tsetErrorFor(password, \"Password cannot be blank\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\t// Check password2\n\tif (password2Value === \"\") {\n\t\tsetErrorFor(password2, \"Password confirmation is required\");\n\t} else if (password2Value !== passwordValue) {\n\t\tsetErrorFor(password2, \"Passwords do not match\");\n\t} else {\n\t\tsetSuccessFor(password);\n\t}\n\n\tif (genders[0].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\t\treturn true;\n\t} else if (genders[1].checked === true) {\n\t\tsetSuccessFor(genderInput);\n\n\t\treturn true;\n\t} else {\n\t\t// no checked\n\t\tsetErrorFor(genderInput, \"Please select a gender\");\n\t\treturn false;\n\t}\n}", "function validateForms() {\n var typedForms = document.querySelectorAll('input');\n var designMenu = document.getElementById('design');\n var designLabel = document.querySelector('.shirt').lastElementChild;\n var designChoice = designMenu.options[designMenu.selectedIndex].text;\n var paymentMethod = document.getElementById('payment');\n var paymentForm = paymentMethod.options[paymentMethod.selectedIndex].text;\n if (designChoice == 'Select Theme') {\n addErrorIndication('Please select a theme', designLabel);\n }\n if ($(\"[type=checkbox]:checked\").length < 1) {\n var activityList = document.querySelectorAll('.activities label')\n var str = 'Please select at least one activity';\n addErrorIndication(str, activityList[activityList.length-1]);\n }\n if (paymentForm == 'Select Payment Method') {\n addErrorIndication('Please select a payment method', paymentMenu);\n }\n for (let i = 0; i < typedForms.length; i++) {\n var currentForm = typedForms[i];\n if (currentForm.id == 'name' && currentForm.value.length < 1) {\n var str = 'Please enter a name';\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'mail' && checkFormat(currentForm) == false) {\n var str = 'Please enter an email address';\n addErrorIndication(str, currentForm);\n } else if (paymentForm == 'Credit Card' && checkFormat(currentForm) == false) {\n if (currentForm.id == 'cc-num') {\n var str = 'Please enter a credit card number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is between 13 and 16 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'zip') {\n var str = 'Please enter a zip number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 5 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'cvv') {\n var str = 'Please enter a CVV number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 3 digits long';\n }\n addErrorIndication(str, currentForm);\n }\n }\n }\n}", "function validateForm(e) {\n 'use strict';\n\n //Handles window-generated events (i.e. non-user)\n if (typeof e == 'undefined') {\n e = window.event;\n }\n\n //Get form object references\n var firstName = U.$('firstName');\n var lastName = U.$('lastName');\n var userName = U.$('userName');\n var email = U.$('email');\n var phone = U.$('phone');\n var city = U.$('city');\n var state = U.$('state');\n var zip = U.$('zip')\n var terms = U.$('terms');\n\n\n //Flag variable\n var error = false;\n\n //Validate the first name using a regular expression\n if (/^[A-Z \\.\\-']{2,20}$/i.test(firstName.value)) {\n //Everything between / and / is the expression\n //Allows any letter A-Z (case insensitive)\n //Allows spaces, periods, and hyphens\n //Name must be 2-20 characters long\n\n //alert(\"Valid first name\");\n removeErrorMessage('firstName');\n }\n else {\n //alert(\"Invalid first name\");\n addErrorMessage(\n 'firstName',\n 'Invalid/missing first name'\n );\n error = true;\n }\n\n //Validate the last name using a regular expression\n\n //Validate the username using a validation function\n if (validateUsername(userName.value)) {\n removeErrorMessage('userName');\n }\n else {\n addErrorMessage(\n 'userName',\n 'username does not meet criteria'\n );\n error = true;\n }\n\n //Validate the email using a regular expression\n //Validate the phone using a regular expression\n //Validate the city using a regular expression\n //Validate the zip using a regular expression\n\n //Prevent form from resubmitting\n if (error) {\n if (e.preventDefault) {\n e.preventDefault();\n }\n else {\n e.returnValue = false;\n }\n }\n\n return false;\n\n} // End of validateForm() function.", "function validateForm()\n {\n var firstname=document.forms[\"UserForm\"][\"field_first_name\"].value;\n var birthdate=document.forms[\"UserForm\"][\"field_birthdate\"].value;\n var email=document.forms[\"UserForm\"][\"mail\"].value;\n var phone=document.forms[\"UserForm\"][\"field_mobile\"].value;\n\t\t\t var pass=document.forms[\"UserForm\"][\"pass\"].value;\n\t\t\t var pass2=document.forms[\"UserForm\"][\"passconfirm\"].value;\n\n if (firstname==null || firstname==\"\")\n\t\t\t \n {\n\t\t\t document.getElementById('fn_validation').innerHTML=\"this is invalid name\";\n return false;\n\t\t\t \n }\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('fn_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t if (birthdate==null || birthdate==\"\" || !(validatebirthdate(birthdate)))\n\t\t\t{\n\t\t\t document.getElementById('birth_validation').innerHTML=\"this is invalid date\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('birth_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (email==null || email==\"\" || validateEmail(email)==false)\n\t\t\t{\n\t\t\t document.getElementById('email_validation').innerHTML=\"this is invalid email\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('email_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (!(validateMobileNum(phone)))\n\t\t\t{\n\t\t\t document.getElementById('phone_validation').innerHTML=\"this is invalid mobile number\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('phone_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (pass==null || pass==\"\" || pass.length < 6)\n\t\t\t{\n\t\t\t document.getElementById('pass_validation').innerHTML=\"this is invalid password\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('pass_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t//\n\t\t\tif (pass2!= pass )\n\t\t\t{\n\t\t\t document.getElementById('pass2_validation').innerHTML=\"this is invalid password\";\n return false;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t document.getElementById('pass2_validation').innerHTML=\"\";\n\t\t\t}\n\t\t\t\n\t\t\t\n }", "function check_form_verify () {\n const form = document.getElementById('form_verify');\n const error = document.getElementById('form_verify_error');\n error.style.display = 'none';\n if (form.diplom.value == '') {\n error.innerHTML = 'Please select a diplom.';\n error.style.display = 'block';\n return false;\n } else if (!(2010 <= parseInt(form.awarding_year.value, 10) && parseInt(form.awarding_year.value, 10) <= 2019)) {\n error.innerHTML = 'Please fill in a valid awarding date. (2010 -> 2019)';\n error.style.display = 'block';\n return false;\n } else if (!form.student_name.value.match(/^[A-Za-z ]+$/)) {\n error.innerHTML = 'Please fill in a valid name. What I call a \"valid name\" is a name given with only letters and spaces.<br>\\\n Ex: \"Jean-Pierre Dupont\" should be entered as \"Jean Pierre Dupont\"';\n error.style.display = 'block';\n return false;\n }\n const birthdate = form.student_birthdate.value.split('/');\n if (birthdate.length != 3) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1 <= parseInt(birthdate[0], 10) && parseInt(birthdate[0], 10) <= 31)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1 <= parseInt(birthdate[1], 10) && parseInt(birthdate[1], 10) <= 12)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1919 <= parseInt(birthdate[2], 10) && parseInt(birthdate[2], 10) <= 2019)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995 with the 1919 <= year <= 2019';\n error.style.display = 'block';\n return false;\n }\n const txid = form.txid.value;\n if (txid.length != 64) {\n error.innerHTML = 'Please fill in a valid transaction identifier (txid). This is a 64 characters hexadecimal value.';\n error.style.display = 'block';\n return false;\n }\n return true;\n}", "function validateForm(event) {\n\n //prevents default event action\n event.preventDefault();\n\n\n// checking if the input value is 1 character or more\n if (checkLength(firstName.value, 0)) {\n firstNameError.style.display = \"none\";\n } else {\n firstNameError.style.display = \"block\";\n }\n// checking if the input value is 3 characters or more\n if (checkLength(lastName.value, 2)) {\n lastNameError.style.display = \"none\";\n } else {\n lastNameError.style.display = \"block\";\n }\n// checking if the input value is a valid email address\n if (validateEmail(email.value)) {\n emailError.style.display = \"none\";\n } else {\n emailError.style.display = \"block\";\n }\n// checking if the input value is 7 characters or more\n if (checkLength(subject.value, 6)) {\n subjectError.style.display = \"none\";\n } else {\n subjectError.style.display = \"block\";\n }\n// checking if the input value is 15 characters or more\n if (checkLength(message.value, 14)) {\n messageError.style.display = \"none\";\n } else {\n messageError.style.display = \"block\";\n }\n}", "function validateForm(){\n // Set error catcher\n var error = 0;\n // Check name\n if(!validateName('reg_name')){\n document.getElementById('nameError').style.display = \"block\";\n error++;\n }\n // Validate email\n var x =document.getElementById('reg_email').value;\n if(!validateEmail(x)){\n document.getElementById('emailError').style.display = \"block\";\n error++;\n }\n // Validate animal dropdown box\n if(!validateSelect('Occupation')){\n document.getElementById('animalError').style.display = \"block\";\n error++;\n }\n if(!validatePassword('reg_pass')){\n document.getElementById('pass_Error').style.display = \"block\";\n error++;\n }\n // Don't submit form if there are errors\n if(error > 0){\n return false;\n }\n else if(error == 0){\n regfun();\n }\n }", "function compute(form) {\n var val1 = parseInt(form.day.value, 10)\n if ((val1 < 0) || (val1 > 31)) {\n alert(\"Day is out of range\")\n }\n var val2 = parseInt(form.month.value, 10)\n if ((val2 < 0) || (val2 > 12)) {\n alert(\"Month is out of range\")\n } \n var val2x = parseInt(form.month.value, 10)\n var val3 = parseInt(form.year.value, 10)\n if (val3 < 1900) {\n alert(\"You're that old!\")\n }\n if (val2 == 1) {\n val2x = 13;\n val3 = val3-1\n }\n if (val2 == 2) {\n val2x = 14;\n val3 = val3-1\n }\n var val4 = parseInt(((val2x+1)*3)/5, 10)\n var val5 = parseInt(val3/4, 10)\n var val6 = parseInt(val3/100, 10)\n var val7 = parseInt(val3/400, 10)\n var val8 = val1+(val2x*2)+val4+val3+val5-val6+val7+2\n var val9 = parseInt(val8/7, 10)\n var val0 = val8-(val9*7)\n form.result1.value = months[val2]+\" \"+form.day.value +\", \"+form.year.value\n form.result2.value = days[val0]\n \n }", "function formValidation(user_name, last_Name, user_email, user_password, user_confirm_password){ \n var user_name = getInputVal(\"firstName\");\n var last_Name = getInputVal(\"userLastName\");\n var user_email = getInputVal(\"userEmail\"); \n var user_password = getInputVal(\"user_Password\");\n var user_confirm_password = getInputVal(\"user_Confirm_Password\"); \n\n if(user_name) {\n document.getElementById(\"firstNameError\").innerHTML = \"\"; \n }\n if(last_Name) {\n document.getElementById(\"firstLastError\").innerHTML = \"\"; \n }\n if(user_email) {\n document.getElementById(\"firstEmailError\").innerHTML = \"\"; \n }\n if(user_password) {\n document.getElementById(\"password_Error\").innerHTML = \"\"; \n }\n if(user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\"; \n }\n else if(user_password != user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\";\n }\n }", "function calculateHealth() {\r\n let heightType = document.querySelector(\"input[name='heightType']:checked\").value;\r\n let calculateItemChecked = document.querySelector(\"input[name='calculate']:checked\").value;\r\n let age = Number(inputAge.value);\r\n let weight = Number(inputWeight.value);\r\n let gender = document.querySelector(\"input[name='gender']:checked\").value;\r\n let physicalState = document.getElementById('physicalState').value;\r\n let height;\r\n //Convert Inches to centimeter for get the height in cm scale \r\n if (heightType === \"centimeter\") {\r\n let centimeter = Number(inputCentimeter.value);\r\n height = centimeter;\r\n } else {\r\n console.log(\"You used inch section\");\r\n let foot = Number(inputFoot.value);\r\n let inches = Number(inputInch.value);\r\n let totalInches = Number((foot * 12) + inches);\r\n let convertToCentimeter = Number(totalInches * 2.54);\r\n console.log(foot, inches, totalInches, convertToCentimeter);\r\n height = convertToCentimeter;\r\n }\r\n\r\n console.log(`Height ${height}, Weight ${weight}, Age ${age}, gender ${gender}, physical state ${physicalState}`);\r\n //TODO: Add a verification for calculation\r\n\r\n if (age == 0 || height == null || height === undefined || weight == 0 || physicalState === \"none\") {\r\n errorAlert.style.display = \"block\";\r\n successAlert.style.display = \"none\";\r\n result.innerHTML = `\r\n <div class=\"d-flex align-items-center\">\r\n <strong>Loading...</strong>\r\n <div class=\"spinner-border ml-auto\" role=\"status\" aria-hidden=\"true\"></div>\r\n </div>`\r\n setTimeout(() => {\r\n result.innerHTML = `\r\n <h5 class=\"alert alert-danger d-block font-weight-bolder text-center\">404 Error <i class=\"fa fa-exclamation-circle\"></i> <br> No values has been given</h5>`\r\n }, 5000);\r\n }\r\n //! When all values is correct\r\n else {\r\n // !Calculate BMR (Heris BeneDict law)\r\n //According to gender\r\n let BMR;\r\n let calories;\r\n let kilojoules;\r\n let icon;\r\n if (gender === \"male\") {\r\n BMR = `${(66 + (13.7 * weight) + (5 * height)) - (6.8 * age)}`\r\n icon = 'male';\r\n } else {\r\n BMR = `${(655 + (9.6 * weight) + (1.8 * height)) - (4.7 * age)}`\r\n icon = 'female';\r\n }\r\n console.log(`Your BMR ${BMR}`);\r\n\r\n //TODO: Calculate calorie according to physical state \r\n let multipicationValue;\r\n if (physicalState === 'low') {\r\n multipicationValue = 1.2;\r\n } else if (physicalState === 'normal') {\r\n multipicationValue = 1.375;\r\n } else if (physicalState === 'medium') {\r\n multipicationValue = 1.55;\r\n } else if (physicalState === 'high') {\r\n multipicationValue = 1.725;\r\n } else if (physicalState === 'veryHigh') {\r\n multipicationValue = 1.9;\r\n } else {\r\n multipicationValue = \"Choose the physical state\"\r\n }\r\n calories = (BMR * multipicationValue);\r\n\r\n // TODO: Calculate KiloJoules from calories\r\n kilojoules = calories * 4.184;\r\n calories = Number(calories).toFixed(2);\r\n kilojoules = Number(kilojoules).toFixed(1);\r\n BMR = Number(BMR).toFixed(2);\r\n console.log(`Your calorie need ${calories}`);\r\n\r\n //TODO: Show the bodyBurnsValue let \r\n let bodyBurning;\r\n let bodyBurningText;\r\n let multipicationValue2;\r\n let resultTypeChecked = document.querySelector(\"input[name='resultIn']:checked\").value;\r\n if (resultTypeChecked === \"kiloJoules\") {\r\n bodyBurning = kilojoules;\r\n bodyBurningText = \"kiloJoules\";\r\n multipicationValue2 = \"X 4.184\";\r\n } else {\r\n bodyBurning = calories;\r\n bodyBurningText = \"calories\";\r\n multipicationValue2 = \"\";\r\n }\r\n\r\n // !Calculate BMI according to height and weight\r\n heightInMeter = `${height / 100}`;\r\n let BMI = `${weight / (heightInMeter**2)}`\r\n BMI = Number(BMI).toFixed(1);\r\n console.log(BMI, heightInMeter);\r\n\r\n //TODO: Justify the BMI index value\r\n let textColor;\r\n let state;\r\n let explainState;\r\n let tips;\r\n let weightText;\r\n if (BMI < 18.5) {\r\n state = \"Underweight\"\r\n explainState = \"শরীরের ওজন কম\";\r\n tips = \"পরিমিত খাদ্য গ্রহণ করে ওজন বাড়াতে হবে\"\r\n textColor = 'black-50';\r\n weightText = \"Low weight\";\r\n } else if (BMI >= 18.5 && BMI <= 24.9) {\r\n state = \"Normal\"\r\n explainState = \"সুসাস্থ্যের আদর্শ মান\";\r\n tips = \"এটি বজায় রাখতে হবে । অতিরিক্ত বা অসাস্থ্যকর খাদ্য গ্রহণ করে সাস্থ্য বাড়ানো যাবে না\"\r\n textColor = 'success';\r\n weightText = \"OverWeight / Underweight\";\r\n } else if (BMI > 24.9 && BMI <= 29.9) {\r\n state = \"Overweight\"\r\n explainState = \"শরীরের ওজন বেশি\";\r\n tips = \"চিন্তিত হবেন না । ব্যায়াম করে ওজন কমাতে হবে\";\r\n textColor = 'warning'\r\n weightText = \"OverWeight\";\r\n } else if (BMI > 29.9 && BMI <= 34.9) {\r\n state = \"obese\"\r\n explainState = \"স্থুল (পর্যায়-১): মেদ বেশি | অতিরিক্ত ওজন\";\r\n tips = \"বেছে খাদ্যগ্রহণ ও ব্যায়াম করা প্রয়োজন ।\"\r\n textColor = 'warning';\r\n weightText = \"High OverWeight\";\r\n } else if (BMI > 34.9 && BMI <= 39.9) {\r\n state = \"obese (High)\"\r\n explainState = \"বেশি স্থুল (পর্যায়-২) ।<br> অতিরিক্ত মেদ\";\r\n tips = \"পরিমিত খাদ্যগ্রহণ ও বেশ ব্যায়াম করা প্রয়োজন । <br> ওজন নিয়োন্ত্রণে আনতে হবে | <br> প্রয়োজনে ডাক্তারের পরামর্শ প্রয়োজন\"\r\n textColor = 'danger';\r\n weightText = \"OverWeight (very high)\";\r\n } else {\r\n state = \"Extremly obese\"\r\n explainState = \"অতিরিক্ত স্থুল (শেষ পর্যায়)। মৃত্যুঝুঁকির আশংকা!\";\r\n tips = \"ডাক্তারের পরামর্শ প্রয়োজন । দ্রুত ওজন নিয়ন্ত্রণে আনতে হবে\"\r\n textColor = 'danger';\r\n weightText = \"OverWeight (extreme)\";\r\n }\r\n // TODO: According to good BMI and given Height calculate the perfect weight for this height\r\n //from \r\n let healthyBMI1 = 18.5;\r\n //to\r\n let healthyBMI2 = 24.9;\r\n //from\r\n let healthyWeight1 = `${healthyBMI1 * (heightInMeter**2)}`\r\n healthyWeight1 = Math.round(healthyWeight1);\r\n //to\r\n let healthyWeight2 = `${healthyBMI2 * (heightInMeter**2)}`\r\n healthyWeight2 = Math.round(healthyWeight2);\r\n //a sequence resulth\r\n let healthyWeight = `${healthyWeight1} to ${healthyWeight2}`\r\n let healthyBMI = `${healthyBMI1} to ${healthyBMI2}`\r\n //Average Result\r\n let averageHealthyWeight = `${(healthyWeight1 + healthyWeight2) / 2}`\r\n let averageHealthyBMI = `${(healthyBMI1 + healthyBMI2) / 2}`\r\n\r\n //TODO: Calculate the difference between healty weight and Given Weight;\r\n let defferenceWeight;\r\n if (state === \"Underweight\") {\r\n defferenceWeight = `${healthyWeight1 - weight}kg To ${healthyWeight2 - weight}kg`\r\n } else if (state === \"Normal\") {\r\n defferenceWeight = \"(N/A) Perfect Weight\"\r\n } else {\r\n defferenceWeight = `${weight - healthyWeight1}kg To ${weight - healthyWeight2}kg`\r\n }\r\n\r\n //TODO; Make the HTML for show the results for each sections\r\n let htmlForBMI;\r\n let htmlForCalories;\r\n let htmlForButtons\r\n\r\n htmlForCalories = `\r\n <div class=\"my-3 d-flex justify-content-center align-content-center flex-column\">\r\n <h5 class=\"card-header text-center my-3\">Your Daily ${bodyBurningText} needs</h5>\r\n <h3 class=\"card-title text-center\" id=\"calculateTitle\">${bodyBurningText} need Per Day : </h3>\r\n <h4 class=\"d-block font-weight-bold mx-auto\" style=\"font-size: 1.5rem;\">\r\n <sup><i class=\"fa fa-fire text-danger\"></i></sup> <span id=\"calorieResult\"> ${bodyBurning}\r\n ${bodyBurningText}/Day</span>\r\n </h4>\r\n</div>\r\n<hr>\r\n<h5 class=\"d-inline-block\">BMR : </h5>\r\n<h5 class=\"d-inline-block text-danger font-weight-bold position-relative float-right\"\r\n style=\"font-size: 1.5rem;\" id=\"BMRResult\">${BMR}</h5>\r\n<hr>\r\n<h5 class=\"d-inline-block\">${bodyBurningText} : (c)</h5>\r\n<h5 class=\"d-inline-block text-danger font-weight-bold position-relative float-right\"\r\n style=\"font-size: 1.5rem;\" id=\"SD\">\r\n <i class=\"fa fa-clipboard\"></i> ${BMR} X ${multipicationValue} ${multipicationValue2}\r\n</h5>\r\n<hr>\r\n<h5 class=\"d-inline-block\">Used BMR Law : </h5>\r\n<h5 class=\"d-inline-block text-danger font-weight-bold position-relative float-right\"\r\nstyle=\"font-size: 1.5rem;\" id=\"SD\">\r\n<i class=\"fa fa-codepen text-codepen\"></i> Heris Bene-Dict \r\n</h5>\r\n<hr>`\r\n\r\n //TODO: BMI HTML\r\n htmlForBMI = `\r\n <div class=\"my-3 d-flex justify-content-center align-content-center flex-column text-center\">\r\n <h5 class=\"card-header my-3\">Your Health Statistics</h5>\r\n <h3 class=\"card-title text-center\" id=\"calculateTitle\">Health State (BMI) : </h3>\r\n <h4 class=\"d-block font-weight-bold mx-auto\" style=\"font-size: 1rem;\">\r\n <sup><i class=\"fa fa-${icon} text-${textColor}\"></i></sup> &nbsp;&nbsp;<span id=\"calorieResult\"> ${explainState}\r\n </span> <small><a id=\"showBMIChart\" onclick=\"showChart()\" class=\"link text-primary\">Chart <i class=\"fa fa-area-chart\"></i></a></small>\r\n </h4>\r\n</div>\r\n<h4>\r\n <ul class=\"list-group\">\r\n <li class=\"list-group-item\" style=\"display: none;\" id=\"BMIChart\">Chart : <div id=\"img d-flex justify-content-center\">\r\n <img src=\"bmi-chart.gif\" class=\"d-block mx-auto img\" alt=\"BMI Chart\">\r\n </div>\r\n </li>\r\n <li class=\"list-group-item\">BMI Formula : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> weight(kg) /\r\n Height(m) <sup class=\"font-weight-bolder\">2</sup></span>\r\n </li>\r\n\r\n <li class=\"list-group-item\">Your BMI (Body Mass Index) : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\">= ${BMI}</span> <a onclick=\"showBMIStateTable()\" class=\"link text-primary\" id=\"BMITableBtn\">Show BMI Table</a>\r\n <div class=\"card mx-auto\" id=\"BMIStateTable\" style=\"border: none;\r\n width: 100%;\r\n height: auto;\r\n display: none;\">\r\n <br>\r\n <div class=\"card-body bg-light mx-auto\">\r\n <b>Check the health stats according to BMI (Body Mass Index) </b>\r\n </div>\r\n <table class=\"table table-striped mx-auto\">\r\n <thead>\r\n <tr>\r\n <th scope=\"col\">BMI</th>\r\n <th scope=\"col\">State</th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n <tr>\r\n <th scope=\"row\"> &lt; 18.5</th>\r\n <td>শরীরের ওজন কম (Underweight)</td>\r\n </tr>\r\n <tr>\r\n <th scope=\"row\">18.5 to 24.9</th>\r\n <td>সুসাস্থ্যের আদর্শ মান (Normal)</td>\r\n </tr>\r\n <tr>\r\n <th scope=\"row\">25 to 29.9</th>\r\n <td>শরীরের ওজন বেশি (Overweight)</td>\r\n </tr>\r\n <tr>\r\n <th scope=\"row\">30 to 34.9</th>\r\n <td>\"স্থুল (পর্যায়-১): মেদ বেশি | অতিরিক্ত ওজন (Obese I)</td>\r\n </tr>\r\n <tr>\r\n <th scope=\"row\">35 to 39.9</th>\r\n <td>বেশি স্থুল (পর্যায়-২) । অতিরিক্ত মেদ (Obese II)</td>\r\n </tr>\r\n <tr>\r\n <th scope=\"row\">&gt 40</th>\r\n <td>অতিরিক্ত স্থুল (শেষ পর্যায়)। মৃত্যুঝুঁকির আশংকা! (Obese III Extreme)</td>\r\n </tr>\r\n </tbody>\r\n </table>\r\n</div>\r\n </li>\r\n <li class=\"list-group-item\" id=\"state\">State : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${state}</span>\r\n </li>\r\n <hr>\r\n <h5 class=\"card-header text-weight-bolder text-muted\">Calculated Standard Health</h5>\r\n <li class=\"list-group-item\" id=\"goodValues\">1. Your BMI should be : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${healthyBMI}</span>\r\n <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${averageHealthyBMI} <small>(Average)</small></span>\r\n </li>\r\n <li class=\"list-group-item\">2.Your Weight should be : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${healthyWeight}</span>\r\n <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${averageHealthyWeight} <small>(Average)</small></span>\r\n </li>\r\n <li class=\"list-group-item\" id=\"goodWeightDifference\">${weightText}<span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${defferenceWeight}</span>\r\n </li>\r\n <hr>\r\n <h5 class=\"card-header text-weight-bolder text-muted\">Suggetions</h5>\r\n <li class=\"list-group-item\" id=\"tips\">Tips (করনীয়) : <span\r\n class=\" alert responsive d-block font-weight-bolder text-warning text-muted bg-light my-3\"><i\r\n class=\"font-weight-bolder text-muted\">=</i> ${tips}</span>\r\n </li>\r\n </ul>\r\n</h4>\r\n `\r\n //TODO: Button HTML \r\n htmlForButtons = `\r\n <button class=\"btn btn-outline-warning\" type=\"submit\" onclick=\"location.reload();\">Reload</button>\r\n <button class=\"btn btn-outline-success position-relative float-right\" type=\"submit\"\r\n onclick=\"window.print();\">Print/Save</button>`\r\n result.classList.add('d-none');\r\n\r\n //TODO: Add alert with success message when calculate will be finished\r\n errorAlert.style.display = \"none\";\r\n successAlert.style.display = \"block\";\r\n setTimeout(() => {\r\n successAlert.classList.add('hide')\r\n successAlert.style.display = \"none\";\r\n }, 4000);\r\n\r\n //TODO: Show the results according to user need\r\n if (calculateItemChecked === \"bmr\") {\r\n calorieSection.innerHTML = htmlForCalories;\r\n healthSection.innerHTML = \"\";\r\n } else if (calculateItemChecked === \"bmi\") {\r\n healthSection.innerHTML = htmlForBMI;\r\n calorieSection.innerHTML = \"\";\r\n } else if (calculateItemChecked === \"all\") {\r\n healthSection.innerHTML = htmlForBMI;\r\n calorieSection.innerHTML = htmlForCalories;\r\n }\r\n buttons.innerHTML = htmlForButtons;\r\n\r\n //! Show the navigator\r\n let navigator = document.getElementById('navigator');\r\n if (calculateItemChecked === \"all\") {\r\n navigator.style.display = \"block\";\r\n } else {\r\n navigator.style.display = \"none\";\r\n }\r\n } //End of the else statement\r\n}", "function evaluateForm(newCamp) {\n var formIsValid = true;\n if (newCamp.campName.value == \"\") {\n newCamp.campName.setAttribute(\"class\", \"required\");\n document.getElementById(\"campName\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.comfort.value == \"\") {\n document.getElementById(\"comfort\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n\n }\n if (newCamp.isolation.value == \"\") {\n document.getElementById(\"isolation\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.accessibility.value == \"\") {\n document.getElementById(\"accessibility\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.pet.value == \"\") {\n document.getElementById(\"pet\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.family.value == \"\") {\n document.getElementById(\"family\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.activities.value == \"\") {\n document.getElementById(\"activities\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.areaType.value == \"\") {\n document.getElementById(\"areaType\").setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.lat.value == \"\") {\n document.getElementById(\"location\").setAttribute(\"class\", \"required\");\n newCamp.lat.setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n if (newCamp.long.value == \"\") {\n document.getElementById(\"location\").setAttribute(\"class\", \"required\");\n newCamp.long.setAttribute(\"class\", \"required\");\n formIsValid = false;\n }\n console.log(formIsValid);\n if (formIsValid) {\n buildCampArray(newCamp);\n };\n}", "function getFormValuesAndDisplayResults() {\n}", "function validateForm() {\n // Retrieving the values of form elements \n var name = document.contactForm.name.value;\n var email = document.contactForm.email.value;\n var mobile = document.contactForm.mobile.value;\n var country = document.contactForm.country.value;\n var gender = document.contactForm.gender.value;\n\n // Defining error variables with a default value\n var nameErr = emailErr = mobileErr = countryErr = genderErr = true;\n\n // Validate name\n if (name == \"\") {\n printError(\"nameErr\", \"Por Favor Ingrese su nombre \");\n } else {\n var regex = /^[a-zA-Z\\s]+$/;\n if (regex.test(name) === false) {\n printError(\"nameErr\", \"Por Favor Ingresa un nombre valido\");\n } else {\n printError(\"nameErr\", \"\");\n nameErr = false;\n }\n }\n\n // Validate email address\n if (email == \"\") {\n printError(\"emailErr\", \"Por Favor Ingrese Su Correo\");\n } else {\n // Regular expression for basic email validation\n var regex = /^\\S+@\\S+\\.\\S+$/;\n if (regex.test(email) === false) {\n printError(\"emailErr\", \"Por Favor Ingrese un Correo Valido\");\n } else {\n printError(\"emailErr\", \"\");\n emailErr = false;\n }\n }\n\n // Validate mobile number\n if (mobile == \"\") {\n printError(\"mobileErr\", \"Por Favor Ingrese Su Numero Telefonico\");\n } else {\n var regex = /^[1-9]\\d{9}$/;\n if (regex.test(mobile) === false) {\n printError(\"mobileErr\", \"Por favor Ingrese un Numero Valido(+569)12345678\");\n } else {\n printError(\"mobileErr\", \"\");\n mobileErr = false;\n }\n }\n\n // Validate country\n if (country == \"seleccionar\") {\n printError(\"countryErr\", \"Por Favor Ingrese Su Region\");\n } else {\n printError(\"countryErr\", \"\");\n countryErr = false;\n }\n\n // Validate gender\n if (gender == \"\") {\n printError(\"genderErr\", \"Por Favor Ingrese Su Genero\");\n } else {\n printError(\"genderErr\", \"\");\n genderErr = false;\n }\n\n // Prevent the form from being submitted if there are any errors\n if ((nameErr || emailErr || mobileErr || countryErr || genderErr) == true) {\n return false;\n } else {\n // Creating a string from input data for preview\n var dataPreview = \"Tu Has Ingresado los siguientes Datos: \\n\" +\n \"Nombre Completo: \" + name + \"\\n\" +\n \"Correo: \" + email + \"\\n\" +\n \"Telefono: \" + mobile + \"\\n\" +\n \"Region: \" + country + \"\\n\" +\n \"Genero: \" + gender + \"\\n\";\n }\n // Display input data in a dialog box before submitting the form\n alert(dataPreview);\n}", "function formValidator() {\n //create object that will save user's input (empty value)\n let feedback = [];\n //create an array that will save error messages (empty)\n let errors = [];\n //check if full name has a value\n if (fn.value !== ``){\n //if it does, save it\n feedback.fname = fn.value; \n }else {\n //if it doesn't, crete the error message and save it\n errors.push(`<p>Invalid Full Name</p>`);\n }\n \n //for email\n if (em.value !== ``){\n feedback.email = em.value;\n //expression.test(String('my-email@test.com').toLowerCase()); \n }else {\n errors.push(`<p>Invalid Email</p>`);\n }\n\n //for message\n if (mes.value !== ``){\n feedback.message = mes.value;\n }else {\n errors.push(`<p>Write a comment</p>`)\n }\n \n //create either feedback or display all errors\n if (errors.length === 0) {\n console.log(feedback);\n }else {\n console.log(errors);\n }\n //close event handler\n}", "function formValidation() {\n //* If validation of email fails, add the warning class to email input and set the display of warning message to inline.\n if (!validation.isEmailValid(email.value)) {\n email.classList.add(\"warning\");\n email.nextElementSibling.style.display = \"inline\";\n }\n //* If validation of name fails, add the warning class to name input and set the display of warning message to inline.\n if (!validation.isNameValid(name.value)) {\n name.classList.add(\"warning\");\n name.nextElementSibling.style.display = \"inline\";\n }\n /*\n * If validation of message fails, add the warning class to message text area and set the display of warning\n * message to inline\n */\n if (!validation.isMessageValid(message.value)) {\n message.classList.add(\"warning\");\n message.nextElementSibling.style.display = \"inline\";\n }\n /*\n *If validation of title fails, add the warning class to title input and set the display of warning\n *message to inline\n */\n\n if (!validation.isTitleValid(title.value)) {\n title.classList.add(\"warning\");\n title.nextElementSibling.style.display = \"inline\";\n }\n if (\n validation.isEmailValid(email.value) &&\n validation.isNameValid(name.value) &&\n validation.isTitleValid(title.valid) &&\n validation.isMessageValid(message.value)\n ) {\n return true;\n } else return false;\n}", "function validateSubmitResults() {\n\tconsole.log(\"Calling from validator\");\n\tvar validated; \n // Select only the inputs that have a parent with a required class\n var required_fields = $('.required');\n // Check if the required fields are filled in\n \trequired_fields.each(function(){\n \t\t// Determite what type of input it is, and display appropriate alert message\n\t\tvar field, msg_string;\n \tif( $(this).hasClass('checkbox_container') || $(this).hasClass('radio_container') ){\n \t\tfield = $(this).find('input:checked');\n \t\tmsg_string = \"Please select an option\";\n \t}else{\n \t\tfield = $(this).find('input:text, textarea');\n \t\tmsg_string = \"Please fill in the field\";\n \t} \n\t\t// For the checkbox/radio check the lenght of selected inputs,\n\t\t// at least 1 needs to be selected for it to validate \n\t\t// And for the text, check that the value is not an empty string\n \t\tif( (field.length <= 0) || !field.val() ){\n \t\t\tconsole.log(\"Field length: \" + field.length);\n \t\t\t$(this).addClass('alert alert-warning');\n \t\t\tvar msg = addParagraph(msg_string, \"validator-msg text-danger\");\n \t\t\t// Check if there is already an alert message class, \n \t\t\t// so that there wouldn't be duplicates\n\t\t\tif( $(this).find('p.validator-msg').length == 0 ){\n \t$(this).find('.section-title').before(msg);\n }\n validated = false;\n \t\t}\n \t\telse{\n \t\t\t// Remove the alert classes and message\n \t\t\t$(this).find('p.validator-msg').detach();\n $(this).removeClass('alert-warning').removeClass('alert'); \n validated = true;\n \t\t}\n \t\t// Sanitize the inputs values\n \t\tif( validated ){\n \t\t\tvar answer = sanitizeString(field.val());\n \t\t\tfield.val(answer);\n \t\t}\n \t});\n\n\treturn validated;\n}", "function validateDemographics(form) {\n\tvar zipVal = validateZip(form);\n\tif (!zipVal) {\n\t\treturn zipVal;\n\t}\n\tvar emailVal = validateEmail(form);\n\tif (!emailVal) {\n\t\tconsole.log(emailVal);\n\t\treturn emailVal;\n\t}\n\n\tvar age = document.getElementById(\"select_age\").value;\n\tif (age === \"SelectRange\") {\n\t\talert(\"You must enter your age.\");\n\t\treturn false;\n\t}\n}", "refreshResult() {\r\n if(this.validateForm()) {\r\n let bill = +(this.getInputVal(this.inputBill));\r\n let people = +(this.getInputVal(this.inputPeople));\r\n let perc = +(this.getInputVal(this.inputCustom) || \r\n this.percentageBtns.filter(btn => btn.classList.contains(\"active\"))[0].value);\r\n\r\n if(people === 0) return;\r\n\r\n this.errorStyles(\"remove\");\r\n let tip = (bill * (perc / 100));\r\n let tipPerPerson = (tip / people).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\r\n let total = ((bill + tip) / people).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\r\n\r\n this.displayResult(tipPerPerson, total);\r\n }\r\n else {\r\n return ;\r\n }\r\n }", "function validateForm()\n{\n // errorMessage holds all errors which may occur during validation and is shown in an alert at the end if there are\n // errors\n var errorMessage = \"\";\n // firstOffender is used to find the first error field so that the cursor can be placed there... see bottom of method\n var firstOffender = [];\n // valid is used to return a boolean to the form, if a true return, the form is saved, if false it is not saved\n var valid = true;\n // these 2 variables are used to get a value after comparison with the regexs and used later\n var email = check_email.test(document.userForm.email.value);\n var city = check_city.test(document.userForm.city.value);\n\n // the following if statements simply check if a field is empty, if it is the error \"no field\" is appended to the\n // error message\n if (document.userForm.fname.value == \"\")\n {\n errorMessage += \"no first name\" + \"\\n\";\n valid = false;\n firstOffender.push(\"firstname\");\n }\n if (document.userForm.lname.value == \"\")\n {\n errorMessage += \"no last name\" + \"\\n\";\n valid = false;\n firstOffender.push(\"lastname\");\n }\n if (document.userForm.email.value == \"\")\n {\n errorMessage += \"no email\" + \"\\n\";\n valid = false;\n firstOffender.push(\"emailField\");\n }\n // test regex against entered value, if result does not match the pattern, the if statement will evaluate to true and enter\n else if (!email)\n {\n errorMessage += \"not a valid email\" + \"\\n\";\n valid = false;\n firstOffender.push(\"emailField\");\n }\n if (document.userForm.phone.value == \"\")\n {\n errorMessage += \"no phone number\" + \"\\n\";\n valid = false;\n firstOffender.push(\"phoneNumber\");\n }\n if (document.userForm.city.value == \"\")\n {\n errorMessage += \"no city\" + \"\\n\";\n valid = false;\n firstOffender.push(\"cityField\");\n }\n // test regex against entered value, if result does not match the pattern, the if statement will evaluate to true and enter\n else if (!city)\n {\n errorMessage += \"not a valid city\" + \"\\n\";\n valid = false;\n firstOffender.push(\"cityField\");\n }\n alert(errorMessage);\n var focusError = document.getElementById(firstOffender[0]);\n focusError.focus();\n return valid;\n}", "function formValidation() {\n var email = document.getElementById('email').value;\n var firstname = document.getElementById('firstname').value;\n var lastname = document.getElementById('lastname').value;\n var phone = document.getElementById('phone').value;\n var address = document.getElementById('address').value;\n var postcode = document.getElementById('postcode').value;\n\n // nest all supporting functions, if all true then send thank you alert\n if (email_validation(email)) {\n if (firstname_validation(firstname)) {\n if (lastname_validation(lastname)) {\n if (phone_validation(phone)) {\n if (address_validation(address)) {\n if (postcode_validation(postcode)) {\n alert('Thank you for submitting the form.');\n document.getElementById(\"edit_account\").submit();\n }\n }\n }\n }\n }\n }\n\n}", "function formSubmit(){\n\n return true; // uncomment this line to bypass the validations\n\n // Fetch all user inputs\n var name = document.getElementById('name').value;\n var email = document.getElementById('email').value;\n var password = document.getElementById('password').value;\n var confirmPassword = document.getElementById('confirmPassword').value;\n var mouse = document.getElementById('mouse').value;\n var ram = document.getElementById('ram').value;\n var ssd = document.getElementById('ssd').value;\n var creditCard = document.getElementById('creditCard').value;\n var province = document.getElementById('province').value;\n var city = document.getElementById('city').value;\n var address = document.getElementById('address').value;\n var paperReceiptRadios = document.getElementsByName('paperReceipt');\n var taxRate;\n\n // Calculate total price\n var sum = mouse * mousePrice + ram * ramPrice + ssd * ssdPrice;\n\n //Identify the selected radios input and assign it to \"paperReceipt\" \n var paperReceipt;\n for(var i = 0; i < paperReceiptRadios.length; i++) {\n if(paperReceiptRadios[i].checked) {\n paperReceipt = paperReceiptRadios[i].value;\n }\n }\n\n // add error if any input is empty\n var error = '';\n if(name == '') {\n error += 'Name is required. <br>';\n }\n if(email == '') {\n error += 'Email is required. <br>';\n }\n\n // add error if email is in wrong format\n if(!emailRegex.test(email)) {\n error += 'Email is in wrong format. <br>';\n }\n\n if(password == '') {\n error += 'Password is required. <br>';\n }\n if(confirmPassword == '') {\n error += 'Confirm Password is required. <br>';\n }\n\n // add error if password is in wrong format\n if(!passwordRegex.test(password)) {\n error += 'Password length must be at least 8 alphanumeric characters. <br>';\n } \n\n // add error if two passwords don't match\n if(password != confirmPassword) {\n error += \"Two passwords don't match. <br>\";\n } \n \n if(creditCard == '') {\n error += 'Credit Card is required. <br>';\n }\n if(province == '') {\n error += 'Province is required. <br>';\n }\n if(city == '') {\n error += 'City is required. <br>';\n }\n if(address == '') {\n error += 'Address is required. <br>';\n }\n\n // add error if total cost is less than $10\n if(sum < 10) {\n error += 'You must at least by $10 worth products. <br>';\n }\n\n // add error if credit card is in wrong format\n if(!creditCardRegex.test(creditCard)) {\n error += \"The credit card should be in the format xxxx-xxxx-xxxx-xxxx with all numerical values. <br>\";\n }\n\n // show a message if there is any error\n if(error != '') {\n document.getElementById('error').innerHTML = error;\n } else {\n document.getElementById('error').innerHTML = '';\n \n // Set tax rate by province\n switch(province) {\n case 'Alberta':\n case 'Northwest Territories':\n case 'Nunavut':\n case 'Yukon':\n taxRate = 0.05;\n break;\n case 'British Columbia':\n case 'Manitoba':\n taxRate = 0.12;\n break;\n case 'New Brunswick':\n case 'Newfoundland and Labrador':\n case 'Nova Scotia':\n case 'Prince Edward Island':\n taxRate = 0.15;\n break;\n case 'Ontario':\n taxRate = 0.13;\n break;\n case 'Quebec':\n taxRate = 0.14975;\n break;\n case 'Saskatchewan':\n taxRate = 0.11;\n break;\n\n // The default should never be excuted, but set it in case it runs\n default:\n taxRate = 9999;\n break;\n }\n\n // Generate a receipt to user\n document.getElementById('receipt').innerHTML = `------------Your receipt------------\n Name: ${name}<br>\n Email: ${email}<br>\n Password: ${password}<br>\n ${mouse ? 'Bluetooth mouse * ' + mouse + '<br>' : ''}\n ${ram ? '8GB RAM * ' + ram + '<br>' : ''}\n ${ssd ? '500GB SSD * ' + ssd + '<br>' : ''}\n Credit card number:<br> ${creditCard}<br>\n Province: ${province}<br>\n City: ${city}<br>\n Address: ${address}<br>\n Paper receipt: ${paperReceipt}<br>\n Total cost(without tax): $${sum}<br>\n Total tax: $${sum * taxRate}<br>\n Total cost(including tax): $${(sum * (1 + taxRate)).toFixed(2)}<br>\n ------------End of receipt------------\n `;\n }\n\n // Stop redirecting to next page.\n return false;\n}", "function formValidate(form) {\n function camelCase(string) {\n string = string||'';\n string = string.replace(/\\(|\\)/,'').split(/-|\\s/);\n var out = [];\n for (var i = 0;i<string.length;i++) {\n if (i<1) {\n out.push(string[i].toLowerCase());\n } else {\n out.push(string[i][0].toUpperCase() + string[i].substr(1,string[i].length).toLowerCase());\n }\n }\n return out.join('');\n }\n\n function nullBool(value) {\n return (value);\n }\n\n function getGroup(el) {\n return {\n container: el.closest('.form-validate-group'),\n label: $('[for=\"' + el.attr('id') + '\"]'),\n prompt: el.closest('.form-validate-group').find('.form-validate-prompt')\n }\n }\n\n function isValid(el) {\n function getType() {\n var attr = camelCase(el.attr('id')).toLowerCase();\n var tag = (el.attr('type') === 'checkbox') ? 'checkbox' : el[0].tagName.toLowerCase();\n function type() {\n var _type = 'text';\n if (attr.match(/zip(code|)/)) {\n _type = 'zipCode';\n } else if (attr.match(/zippostal/)) {\n _type = 'zipPostal';\n } else if (attr.match(/(confirm|)(new|old|current|)password/)) {\n _type = 'password'\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)email/)) {\n _type = 'email';\n } else if (attr.match(/(confirm|)([a-zA-Z0-9_-]+|)(phone)(number|)/)) {\n _type = 'phone';\n } else if (attr.match(/merchantid/)) {\n _type = 'merchantId';\n } else if (attr.match(/marketplaceid/)) {\n _type = 'marketplaceId';\n } else if (attr.match(/number/)) {\n _type = 'number';\n }\n return _type;\n }\n if (tag === 'input' || tag === 'textarea') {\n return type();\n } else {\n return tag;\n }\n } // Get Type\n var string = el.val()||'';\n var exe = {\n text: function () {\n return (string.length > 0);\n },\n password: function () {\n return (string.length > 6 && nullBool(string.match(/^[\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)a-zA-Z0-9_-]+$/)));\n },\n zipCode: function () {\n return (nullBool(string.match(/^[0-9]{5}$/)));\n },\n zipPostal: function () {\n return (nullBool(string.match(/^([0-9]{5}|[a-zA-Z][0-9][a-zA-Z](\\s|)[0-9][a-zA-Z][0-9])$/)));\n },\n email: function () {\n return (nullBool(string.match(/[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\\.([a-z]{2}|[a-z]{3})/)));\n },\n merchantId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n return ((match) && (match[0].length > 9 && match[0].length < 22));\n },\n marketplaceId: function () {\n var match = string.match(/^[A-Z0-9]+$/);\n var length = {'United States of America':13}[region()];\n return ((match) && (match[0].length === length));\n },\n select: function () {\n return (el[0].selectedIndex > 0);\n },\n checkbox: function () {\n return el[0].checked;\n },\n phone: function () {\n return (nullBool(string.replace(/\\s|\\(|\\)|\\-/g,'').match(/^([0-9]{7}|[0-9]{10})$/)));\n },\n number: function () {\n return nullBool(string.match(/^[0-9\\.\\,]+$/));\n }\n }\n return exe[getType()]();\n }; // contentsValid\n\n return {\n confirm: function (el) {\n\n function condition(el) {\n var bool = dingo.get(el).find('form-validate').condition||false;\n if (bool && el.val().length > 0) {\n return el;\n } else {\n return false;\n }\n }\n\n function dependency(el) {\n // Needs to use recursion to climb the dependency tree to determine whether or not\n // the element is dependent on anything\n var dep = $('#' + dingo.get(el).find('form-validate').dependency);\n if (dep.size() > 0) {\n return dep;\n } else {\n return false;\n }\n }\n\n function confirm(el) {\n var match = $('#' + dingo.get(el).find('form-validate').confirm);\n if (match.size()) {\n return match;\n } else {\n return false;\n }\n }\n\n function normal(el) {\n var check = dingo.get(el).find('form-validate');\n var out = true;\n var attr = ['condition','dependency','confirm'];\n $.each(attr,function (i,k) {\n if (typeof check[k] === 'string' || check[k]) {\n out = false;\n }\n });\n return out;\n }\n\n function validate(el) {\n var group = getGroup(el);\n function exe(el,bool) {\n if (bool) {\n el.removeClass('_invalid');\n group.label.addClass('_fulfilled');\n animate(group.prompt).end();\n group.prompt.removeClass('_active');\n } else {\n el.addClass('_invalid');\n group.label.removeClass('_fulfilled');\n }\n }\n return {\n condition: function () {\n exe(el,isValid(el));\n },\n dependency: function (match) {\n if (normal(match) || condition(match)) {\n exe(el,isValid(el));\n }\n },\n confirm: function (match) {\n if (el.val() === match.val()) {\n exe(el,true);\n } else {\n exe(el,false);\n }\n },\n normal: function () {\n exe(el,isValid(el));\n }\n }\n }\n\n if (condition(el)) {\n validate(el).condition();\n } else if (dependency(el)) {\n validate(el).dependency(dependency(el));\n } else if (confirm(el)) {\n validate(el).confirm(confirm(el));\n } else if (normal(el)) {\n validate(el).normal();\n }\n },\n get: function () {\n return form.find('[data-dingo*=\"form-validate\"]').not('[data-dingo*=\"form-validate_submit\"]');\n },\n init: function (base, confirm) {\n if (el.size() > 0) {\n parameters.bool = bool;\n formValidate(el).fufilled();\n return formValidate(el);\n } else {\n return false;\n }\n },\n is: function () {\n return (form.find('.form-validate').size() < 1);\n },\n check: function () {\n var el;\n formValidate(form).get().each(function () {\n formValidate(form).confirm($(this));\n });\n return form.find('._invalid');\n },\n submit: function (event) {\n var out = true;\n var requiredField = formValidate(form).check();\n if (requiredField.size() > 0) {\n requiredField.each(function () {\n var group = getGroup($(this));\n group.prompt.addClass('_active');\n group.prompt.css('top',group.container.outerHeight() + 'px');\n if (typeof animate === 'function') {\n animate(group.prompt).start();\n }\n })\n if (requiredField.eq(0).closest('[class*=\"modal\"]').size() < 1) {\n if (typeof animate === 'function') {\n if (!dingo.isMobile()) { \n animate(requiredField.eq(0)).scroll(); \n }\n }\n requiredField.eq(0).focus();\n }\n out = false;\n }\n return out;\n }\n }\n}", "function validate(){\r\n validateFirstName();\r\n validateSubnames();\r\n validateDni();\r\n validateTelephone ();\r\n validateDate();\r\n validateEmail();\r\n if(validateFirstName() && validateSubnames() && validateDni() && validateTelephone() &&\r\n validateDate() && validateEmail()){\r\n alert(\"DATOS ENVIADOS CORRECTAMENTE\");\r\n form.submit(); \r\n }\r\n\r\n}", "function processForm()\r\n{\r\n var $repairAgentSet; // boolean used to tell if claim should be processed\r\n var $claimType = $('#claimdetails-claimtype-select').val();\r\n \r\n $errorMessageArray = []; // reset arry for each process of the form\r\n \r\n \r\n // check to make sure at least one product is in the claim before being submitted\r\n if ($quantityProductClaim == 0 )\r\n {\r\n showMessage('Error', 'A product must be in the claim before saving.');\r\n return false;\r\n }\r\n \r\n // check to make sure repair agent has been set if claim status is shipped\r\n // or complete for repair claims\r\n $repairAgentSet = checkRepairAgentSet();\r\n\r\n if ($repairAgentSet == true)\r\n {\r\n $('#claimdetails-repairagentid-input').prop(\"disabled\", false);\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n \r\n // check inputs to make sure there vaild\r\n if ($claimType == 'Warranty' || $claimType == 'Non-Warranty')\r\n {\r\n checkCustomerInputs();\r\n checkFinailseRepairInputs();\r\n checkRepairAgentInputs();\r\n }\r\n \r\n\r\n // loop through the error array and print to the screen, if errors exist return false\r\n // if no error return true\r\n $arraylength = $errorMessageArray.length;\r\n\r\n // if errors exist - entries in array show error message box and messages\r\n if ($arraylength > 0)\r\n {\r\n var $errorMsgs = \"\";\r\n\r\n // add each error to error msg string\r\n for (i = 0; i < $arraylength; i++)\r\n {\r\n $errorMsgs += \"<h3 class=\\\"error-list\\\">\" + $errorMessageArray[i] + \"</h3> \";\r\n }\r\n\r\n $('#customerclaim-error-container').html($errorMsgs);\r\n $('#customerclaim-error-container').fadeIn(1500);\r\n\r\n // scroll to error box - so it will be seen straight away - animates\r\n $('html, body').animate({\r\n scrollTop: $(\"#customerclaim-error-container\").offset().top\r\n }, 2000);\r\n\r\n return false;\r\n }\r\n else // if no error return true to process the form\r\n {\r\n // on submit make sure inputs are enables so they will be posted\r\n $('#claimdetails-claimtype-select').prop(\"disabled\", false);\r\n $('#claimdetails-supplierid-input').prop(\"disabled\", false);\r\n $('#claimdetails-claimid-input').prop(\"disabled\", false);\r\n \r\n id=\"claimdetails-claimtype-select\"\r\n disableRepairAgentInputs(false);\r\n \r\n return true;\r\n }\r\n}", "function validate() {\n\t\t//Invaild entry responces.\n\t\tvar nameConf = \"Please provide your Name.\";\n\t\tvar emailConf = \"Please provide your Email.\";\n\t\tvar phoneConf = \"Please provide a valid Phone Number.\";\n\t\t\n\t\t//Regular Expression validation.\n\t\tvar phoneNumber = /^\\d{10}$/; //validate that the user enters a 10 digit phone number\n\t\n\t if(document.myForm.name.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = nameConf;\n\t document.myForm.name.focus();\n\t return false;\n\t }\n\t \n\t if(document.myForm.email.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = emailConf;\n\t document.myForm.email.focus();\n\t return false;\n\t }\n\t \n\t \tif(document.myForm.phone.value.match(phoneNumber) ) {\n\t document.getElementById(\"valConf\").innerHTML = phoneConf;\n\t document.myForm.phone.focus();\n\t return false;\n\t }\n\t} //form validation to confirm the form isn't empty ", "function MM_validateForm() {\r\n if (document.getElementById){\r\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;\r\n for (i=0; i<(args.length-2); i+=3) { \r\n\t\t\ttest=args[i+2]; val=document.getElementById(args[i]);\r\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\r\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\r\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n'; \r\n\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (test!='R') { num = parseFloat(val);\r\n\t\t\t\t\t\tif (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\r\n\t\t\t\t\t\tif (test.indexOf('inRange') != -1) { p=test.indexOf(':');\r\n min=test.substring(8,p); max=test.substring(p+1);\r\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\r\n\t\t\t\t\t} \r\n\t\t\t\t} \r\n\t\t\t} \r\n\t\t\telse if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\r\n } \r\n\t\tif (errors) alert('The following error(s) occurred:\\n'+errors);\r\n document.MM_returnValue = (errors == '');\r\n\t}\r\n}", "function calculateLoan(e) {\n // Check for number of input errors, if none then run the calculating functions\n if (checkErrors() > 0) {\n stop();\n } else {\n // Hide the results each time the button is pressed\n document.getElementById(\"results\").style.display = \"none\";\n // Show the loading gif\n document.getElementById(\"loading\").style.display = \"block\";\n // Stop the loading gif after 3 seconds\n setTimeout(loadGIF, 2000);\n // Run the functions that calculate the results\n calculateMonthlyPayment();\n calculateTotalPayment();\n calculateTotalInterest();\n // Delay results by 3 seconds\n setTimeout(showResults, 2000);\n // document.getElementById(\"results\").style.display = \"block\";\n }\n\n // Prevent submit and refresh (default behaviour of submit form event)\n e.preventDefault();\n}", "function validationsOk() {\n\n // Validate if in the HTML document exist a form\n if (formExistence.length === 0) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"Form tag doesn't exist in the html document\"\n return;\n }\n\n // Validate the quantity of labels tags are in the document\n if (labelsQuantity.length !== 4) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of label tags in the document\"\n return;\n }\n\n // Validate the quantity of buttons are in the document\n if (buttonsQuantity.length !== 2) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of button tags in the document\"\n return;\n }\n\n // Validate the quantity of inputs tags are in the document\n if (inputsQuantity.length !== 4) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of inputs tags in the document\"\n return;\n }\n\n // Validate if the email input contains text \n if (emailInput.value === \"\" || emailInput.value === null || !isEmail(emailInput.value)) {\n return;\n }\n if (nameInput.value === \"\" || nameInput.value === null) {\n return;\n }\n // Validate if the password input contains text\n if (passwordInput.value === \"\" || passwordInput.value === null) {\n return;\n }\n // Validate if the confirm-password input contains text\n if (confirmPasswordInput.value === \"\" || confirmPasswordInput.value === null) {\n return;\n }\n // Validate if the confirm-password match with the password\n if (confirmPasswordInput.value !== passwordInput.value) {\n return;\n }\n // all validations passed\n else {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"green\"\n infoDiv.innerText = `Registered Succesfully. Your account data is: ${emailInput.value} ${nameInput.value} ${passwordInput.value.type = \"******\"} ${confirmPasswordInput.value.type = \"******\"}`\n return;\n }\n}", "function processForm($btn, callback){\n\t// get all the inputs into an array.\n\tvar $form = $btn.parents(\"form\");\n var $inputs = $form.find(':input');\n var $selects = $form.find('select');\n var $textareas = $form.find('textarea');\n var validCheckAmount = 0;\n\n // get an associative array of just the values.\n var data = {};\n if($form.attr('name') == \"/medicijnbeheer/create\"){\n\t data[\"bnf_percentage_id\"] = new Array();\n\t data[\"bnf_value\"] = new Array();\n\t data[\"chem_bonding_id\"] = new Array();\n\t data[\"med_ki_val_id\"] = new Array();\n }\n \n $inputs.each(function() {\n \t\tif ($(this).hasClass(\"valCheckString\")) {\n\t\t\t\tif (!validateString($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckDate\")){\n\t\t\t\tif (!validateDate($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckEmpty\")){\n\t\t\t\tif (!validateInputEmpty($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckEmailAdmin\")){\n\t\t\t\tif (!validateEmailAdmin($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckStringAdmin\")){\n\t\t\t\tif (!validateStringAdmin($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n \t\tif($(this).attr('type')==\"radio\"){\n \t\t\tif($(this).is(':checked'))\n \t\t\t\tdata[this.name] = $(this).val();\n \t\t}else if($(this).attr('name').indexOf(\"bnf_\") > -1){\n \t\t\tdata.bnf_percentage_id.push($(this).attr('id'));\n \t\t\tdata.bnf_value.push($(this).val());\n \t\t}else if($(this).attr('class')!=\"no_process\"){\n \t\t\tdata[this.name] = $(this).val();\n \t\t}\n });\n \n //check the select boxes for their values\n $selects.each(function(){\n \t//the med form has to be treated a little different\n \tif(this.name.indexOf(\"neuro_\") > -1){\n \t\tdata.chem_bonding_id.push($(this).attr('id'));\n \t\tdata.med_ki_val_id.push($(this).find('option:selected').val());\n \t}else{\n \t\tdata[this.name] = $(this).find('option:selected').val();\n \t}\n });\n \n $textareas.each(function(){\n \tdata[this.name] = $(this).val();\n });\n \n if(validCheckAmount == 0){\n\t //the form should have the path as name attribute\n\t var path = $form.attr(\"name\");\n\t //send the data to the database and if successful, show the new patient's page.\n\t callWebservice(data, path, callback);\n }else{\n \tcallback(false);\n }\n}", "calculateForm(){\n\t\tlet instance = this;\n\n\t\tif(instance.hasErrorInTheForm()) return;\n\t\t\n\t\tinstance.debt = instance.calculateDebt({\n\t\t\tamount: instance.calculatorData,\n\t\t\tinterest: instance.dropdownData.interest,\n\t\t\tmonths: instance.dropdownData.months\n\t\t});\n\n\t\tinstance.element.querySelector('#input-total').placeholder = `R$: ${instance.debt}`;\n\t\tinstance.element.querySelector('.get-quot').removeAttribute('disabled');\n\t}", "function validation() {\t\t\t\t\t\r\n\t\t\t\t\tvar frmvalidator = new Validator(\"app2Form\");\r\n\t\t\t\t\tfrmvalidator.EnableOnPageErrorDisplay();\r\n\t\t\t\t\tfrmvalidator.EnableMsgsTogether();\r\n\r\n\t\t\t\t\tif (document.getElementById('reasonForVisit').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitPatientReason\",\"req\",\"Please enter your reason For Visit\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitPatientReason_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (document.getElementById('visitYes').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitNewpatient\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\tif (document.getElementById('visitNo').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"visitNewpatient\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitNewpatient_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visitPrDocYes').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"hasPhysian\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\tif (document.getElementById('visitPrDocNo').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"hasPhysian\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_hasPhysian_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('emailAddress').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitEmail\",\"req\", \"Email is required\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitEmail\",\"email\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitEmail_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientFirstName').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientFirstName\",\"req\",\"Please enter your First Name\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientFirstName_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientLastName').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientLastName\",\"req\",\"Please enter your Last Name\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientLastName_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('pdob').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"pdob\",\"\",\"DOB is required\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_pdob_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('phoneNumber').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"req\",\"Phone Number is required\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"numeric\",\"numbers only\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"minlen=10\",\"not enough numbers\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientPhoneNumber_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visitGender').value==\"0\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitGender\",\"dontselect=0\",\"Please select an option 'Male or Female'\");\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitGender_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientZipCode').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"numeric\",\"numbers only\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"minlen=5\",\"not a valid zipcode\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"req\",\"zip code is required\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientZipCode_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visit_terms_911').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"agreeTerms\",\"selmin=2\",\"please check all boxes to continue\");\r\n\t\t\t\t\t\tif (document.getElementById('visit_custom_terms').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"agreeTerms\",\"selmin=2\",\"please check all boxes to continue\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_agreeTerms_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n \r\n}", "function calculatePrice() {\n validateForm(document.getElementById(\"numDaysInput\")); // calls validateForm to check for positive values\n\n let carPriceFinal = calcCarChoice();\n let optionCostsFinal = calculateOptionsCosts();\n let ageCosts = calculateAgeCost();\n let returnDate = calculateReturnDate();\n\n let surcharge = ageCosts * carPriceFinal;\n document.getElementById(\"underOutput\").value = surcharge.toFixed(2); // Age surcharge\n\n document.getElementById(\"carRentalPmtTotal\").value = carPriceFinal.toFixed(2); // Car Rental Output\n document.getElementById(\"carOptionPmtTotal\").value = optionCostsFinal.toFixed(2); // Car Options\n \n let totalCosts = carPriceFinal + surcharge + optionCostsFinal;\n\n let totalDueField = document.getElementById(\"pmtTotalDue\");\n totalDueField.value = totalCosts.toFixed(2);\n\n let returnDateField = document.getElementById(\"returnDateOutput\");\n returnDateField.value = returnDate.toDateString();\n\n // If any changes to input form, remove error message\n document.getElementById(\"car-Rental\").onchange = function() {\n doReset();\n }\n}", "function calculateFormScore() {\r\n\r\n //higligt selected values from previously submitted entry\r\n $(\"input:hidden[name$='_hidden']\").each(function() { // only chose hidden inputs with postfix _hidden\r\n \r\n // aquire form category\r\n var category = $(this).attr(\"name\");\r\n category = category.replace(\"_hidden\", \"\");\r\n\r\n // update score calculation overview\r\n var score = 0; // category score\r\n score = roundToDecimalPlace(calculateCategory(category), 2);\r\n var scoreDiv = '#' + category + '_score';\r\n\r\n $(scoreDiv).html(\"Einkunn - \" + score); // display the score on the page\r\n $(scoreDiv).attr(\"data-score\", score); // store the score\r\n \r\n // always finish by calculating current total score\r\n var totalScore = performScoreCalculation();\r\n $('#totalScoreHeader').html(\"Heildarskor - \" + totalScore);\r\n $('input[name=totalScoreHidden]').val(totalScore);\r\n });\r\n }", "function validateAllInputs() {\n // first, clear out warning box\n clearWarnings();\n\n // username: lowercase letters, numbers, between 4-12 characters\n let userName = document.getElementById('username').value;\n let userNameIsValid = /^[a-z0-9]{4,12}$/.test(userName);\n\n // email: contains @, ends in .net/.org/.com/.edu\n let email = document.getElementById('email').value;\n let emailIsValid = /^.+@.+\\.(net|com|org|edu)$/.test(email);\n\n // phone number: format XXX-XXX-XXXX\n let phoneNumber = document.getElementById('phone').value;\n let phoneNumberIsValid = /^([0-9]{3}-){2}[0-9]{4}$/.test(phoneNumber);\n\n // password: 1 uppercase, 1 lowercase, 1 number, 1 special character\n let password = document.getElementById('password').value;\n let passwordIsValid = (/^.*[A-Z].*$/.test(password) &&\n /^.*[a-z].*$/.test(password) &&\n /^.*[0-9].*$/.test(password) &&\n /^.*[^A-Za-z0-9].*$/.test(password));\n\n // confirm password: must be same as password\n let confirmPassword = document.getElementById('confirm-password').value;\n let confirmPasswordIsValid = (confirmPassword === password);\n\n // gender: one of the three radio buttons must be checked\n let genderButtons = document.getElementsByName('gender');\n let gender = null;\n for (const button of genderButtons) {\n if (button.checked) {\n gender = button.id;\n break;\n }\n }\n let genderIsValid = (gender != null);\n\n // birthday: all three birthdays must not be empty\n let birthdayMonth = document.getElementById('month').value;\n let birthdayDate = document.getElementById('day').value;\n let birthdayYear = document.getElementById('year').value;\n let birthdayIsValid = (birthdayYear !== \"none\" && birthdayMonth !== \"none\" && birthdayDate !== \"none\");\n\n // music: at least one checkbox is checked\n let popChecked = document.getElementById('pop').checked;\n let hiphopChecked = document.getElementById('hiphop').checked;\n let jazzChecked = document.getElementById('jazz').checked;\n let rockChecked = document.getElementById('rock').checked;\n let classicalChecked = document.getElementById('classical').checked;\n let countryChecked = document.getElementById('country').checked;\n let musicIsValid = (popChecked || hiphopChecked || jazzChecked || rockChecked\n || classicalChecked || countryChecked);\n\n // Debug statements, comment out before release\n console.log('Username ' + userName + (userNameIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Email ' + email + (emailIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Phone number ' + phoneNumber + (phoneNumberIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Password ' + password + (passwordIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Confirm password ' + confirmPassword + (confirmPasswordIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Gender ' + gender + (genderIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Birthday' + (birthdayIsValid ? \" is valid\" : \" is not valid\"));\n console.log('Music' + (musicIsValid ? \" is valid\" : \" is not valid\"));\n\n // check confirm password LAST\n let inputsAreValid = userNameIsValid && emailIsValid && phoneNumberIsValid &&\n passwordIsValid && genderIsValid && birthdayIsValid && musicIsValid;\n if (inputsAreValid) {\n if (confirmPasswordIsValid) {\n window.location.replace('index.html');\n } else {\n window.alert(\"Passwords do not match.\");\n }\n } else {\n // else, we need to add messages for everything that's borked\n let redText = \"<span style='color: red; font-weight:bold;'>\";\n let orangeText = \"<span style='color: orange; font-weight:bold;'>\";\n\n if (!userNameIsValid) {\n if (userName === \"\") {\n addWarningMessage(\"Please enter \" + redText + \" a username </span>\");\n } else {\n addWarningMessage(\"Please enter \" + orangeText + \" a valid username </span>\");\n }\n }\n if (!emailIsValid) {\n if (email === \"\") {\n addWarningMessage(\"Please enter \" + redText + \" an email address </span>\");\n } else {\n addWarningMessage(\"Please enter \" + orangeText + \" a valid email address </span>\");\n }\n }\n if (!phoneNumberIsValid) {\n if (phoneNumber === \"\") {\n addWarningMessage(\"Please enter \" + redText + \" a phone number </span>\");\n } else {\n addWarningMessage(\"Please enter \" + orangeText + \" a valid phone number </span>\");\n }\n }\n if (!passwordIsValid) {\n if (password === \"\") {\n addWarningMessage(\"Please enter \" + redText + \" a password </span>\");\n } else {\n addWarningMessage(\"Please enter \" + orangeText + \" a valid password </span>\");\n }\n }\n if (!genderIsValid) {\n addWarningMessage(\"Please select \" + redText + \" a gender </span>\");\n }\n if (!birthdayIsValid) {\n addWarningMessage(\"Please select \" + redText + \" a birthday </span>\");\n }\n if (!musicIsValid) {\n addWarningMessage(\"Please select \" + redText + \" at least one favorite music genre </span>\");\n }\n }\n}", "function validateForm() {\n\t\n\tvar coApplWorkPhone = document.forms[\"myForm\"][\"coApplWorkPhone\"].value;\n\tif (!coApplWorkPhone) {\n\t\tdocument.getElementById('input_4101').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\tdocument.getElementById('phonedatata5').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4101\").innerHTML = \"\";\n\t}\n\t\t\t\t\n\tvar coApplBirthday = document.forms[\"myForm\"][\"coApplBirthday\"].value;\n\tif (!coApplBirthday) {\n\t\tdocument.getElementById('input_4103').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\tdocument.getElementById('datepicker').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4103\").innerHTML = \"\";\n\t}\n\t\n\tvar coApplInsurNum = document.forms[\"myForm\"][\"coApplInsurNum\"].value;\n\tif (!coApplInsurNum) {\n\t\tdocument.getElementById('input_4104').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\t//document.getElementById('phonedatata8').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4104\").innerHTML = \"\";\n\t}\n\t//alert(isNum(coApplInsurNum,\"input_4104\"));\n\tif(!(isNum(coApplInsurNum,\"input_4104\"))){\n\t\tconsole.log(\"coming \");\n\t\t//alert(\"coming\")\n\t\treturn false;\n\t}\n\tvar coAppDependants = document.forms[\"myForm\"][\"coAppDependants\"].value;\n\tif (!coAppDependants) {\n\t\tdocument.getElementById('input_4106').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\t//document.getElementById('phonedatata8').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4106\").innerHTML = \"\";\n\t}\n\t\n\t\n\tvar movedCanadas = document.forms[\"myForm\"][\"movedCanadas\"].value;\n\tif (!movedCanadas) {\n\t\tdocument.getElementById('input_4009').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\t\t//document.getElementById('phonedatata8').focus();\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4009\").innerHTML = \"\";\n\t}\n\t\t\n\t/* var coApplicantss = document.forms[\"myForm\"][\"coApplicantss\"].value;\n\tif (!coApplicantss) {\n\t\tdocument.getElementById('input_4107').innerHTML = \"<span style='color:red'>*This field is Required.</span>\";\n\n\t\treturn false;\n\t} else {\n\t\tdocument.getElementById(\"input_4107\").innerHTML = \"\";\n\t} */\n\t\n\treturn true;\n}", "function calculateResults() {\n\ttry {\n\t\tvar x = getUserInput();\n //if user input results in error, the error will be presented on the html.\n //e is the event.\n\t} catch(e) {\n\t\talert(\"Error: \" + e);\n\t\treturn;\n\t}\n //This will keep from displaying the same answer over and over if the calculate\n //button is clicked; without setDefaultText() the calculate button will keep\n //appending the same answer indefinitely.\n\tsetDefaultText();\n\n\tfor (var i = 0; i < resultElements.length; i++) {\n\t\tvar element = resultElements[i];\n //functionName looks for the function attribute in the html\n var functionName = element.getAttribute('function');\n //func invokes the Math function and is defined the function tag\n //accessed by the functionName funtion above\n\t\tvar func = Math[functionName];\n //The results are rendered based on the user input\n\t\tvar result = func(x);\n //The user input is captured here and input is evaluated and the results\n //added to the respective functions in the html - sin/cons/tan/log\n\t\telement.innerText = element.innerText + \" \" + result;\n\n\t}\n\n}", "function validateForm() {\n\t\n\tvar messageString = \"\"; // Start with blank error message\n\tvar tableViewRows = $.tableView.data[0].rows;\n\t\n\tfor (var i = 0; i < tableViewRows.length; ++i) {\n\t\t\n\t\tvar fieldObject = tableViewRows[i].fieldObject;\n\t\tvar value = getFieldValue(tableViewRows[i]);\n\t\t\n\t\tif (fieldObject.field_type == 'Checkbox') {\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\t// Checks if the field is blank and/or required\n\t\tif (value == \"\" || value == null) {\n\t\t\tif (fieldObject.required == \"No\") {\n\t\t\t\tcontinue;\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" is a required field.\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\n\t\t// -------------- Text ----------------\n \t\tif (fieldObject.field_type == 'Text') {\n \t\t\t// Do Nothing\n \t\t\t\n \t\t// -------------- Checkbox ----------------\n \t\t} else if (fieldObject.field_type == 'Checkbox') { \n \t\t\t// Do Nothing\t\n \t\t\n \t\t\n \t\t// ------------ Integer ----------------\n \t\t} else if (fieldObject.field_type == 'Integer') { \n\t\t\t// Is number? And is integer?\n\t\t\tif (Number(value) > 0 && value % 1 == 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be an integer.\\n\";\n\t\t\t}\n\t\t\n\t\t\n\t\t// ------------ Decimal ----------------\n\t\t} else if (fieldObject.field_type == 'Decimal') { \n\t\t // Is number?\n\t\t\tif (Number(value) > 0) {\n\t\t\t\t// Is it in range?\n\t\t\t\tif (value > fieldObject.numeric_max || value < fieldObject.numeric_min) {\n\t\t\t\t\tmessageString += fieldObject.prompt + \" must be in range [\" + fieldObject.numeric_min + \", \" + fieldObject.numeric_max + \"]\\n\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tmessageString += fieldObject.prompt + \" must be a number.\\n\";\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t// ---------- Calculated ------------\n\t\t} else if (fieldObject.field_type == 'Calculated') { \n\t\t\n\t\t\n\t\t// -------------- Incremental Text ----------------\n\t\t} else if (fieldObject.field_type == 'Incremental Text') { \n\t\t\n\t\t\n\t\t// -------------- Date ----------------\n\t\t} else if (fieldObject.field_type == 'Date') { \n\t\t\n\t\t\n\t\t// -------------- Time ----------------\n\t\t} else if (fieldObject.field_type == 'Time') { \n\t\t\t\n\t\t\t\n\t\t// -------------- Date-Time ----------------\n\t\t} else if (fieldObject.field_type == 'Date-Time') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Message') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Location') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Photo') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Recording') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Button Selection') { \n\t\t\n\t\t} else if (fieldObject.field_type == 'Structural Attitude') { \n\t\t\n\t\t} else { \n\t\t\t\n\t\t}\n\t\t//------------------------------------------------------------------------------------------------------------------------------------------\n\t}\n\treturn messageString;\n}", "function validate() {\n\t// Generate basic Info\n\tvar settings = {};\n\tvar generate = {};\n\n\t// Sentinel to how everything should be handled\n\tvar correct = true;\n\n\t// All input values\n\tconst all_select = document.getElementsByTagName(\"select\");\n\tconst all_inputs = document.getElementsByTagName(\"input\");\n\n\t/*********************/\n\t/* Validate Settings */\n\t/*********************/\n\tsettings[\"System\"] = document.getElementById(\"System\").value;\n\tsettings[\"Race\"] = chosen_race;\n\tsettings[\"Population\"] = parseInt(document.getElementById(\"Population\").value);\n\tsettings[\"Variance\"] = parseInt(document.getElementById(\"Variance\").value);\n\tvar exotic_list = [];\n\n\tfor (var i = all_inputs.length - 1; i >= 0; i--) {\n\t\tif (all_inputs[i].type == \"checkbox\" && all_inputs[i].checked && all_inputs[i].value !== \"on\") {\n\t\t\texotic_list.push(all_inputs[i].value);\n\t\t}\n\t}\n\tsettings[\"Exotic\"] = exotic_list;\n\n\n\t/*********************/\n\t/* Validate Stores */\n\t/*********************/\n\t// Normal generations\n\tfor (var i = normal_types.length - 1; i >= 0; i--) {\n\t\tvar ret = normal(normal_types[i], normal_rarity[i]);\n\t\tif (!ret) {\n\t\t\tcorrect = false;\n\t\t} else {\n\t\t\tgenerate[generate_names[normal_types[i]]] = ret;\n\t\t}\n\t}\n\n\t// Odd generators\n\tfor (var i = normal_types.length - 1; i >= 0; i--) {\n\t\tvar ret = odd(odd_types[i]);\n\t\tif (!ret) {\n\t\t\tcorrect = false;\n\t\t} else {\n\t\t\tgenerate[generate_names[odd_types[i]]] = ret;\n\t\t}\n\t}\n\n\t/*********************/\n\t/* Validate People */\n\t/*********************/\n\tvar raw_people_info = document.getElementById(\"People_List\").value.split('\\n');\n\tgenerate[\"Occupations\"] = raw_people_info.filter((el) => {\n\t\treturn el != null && el != \"\";\n\t})\n\n\tvar raw_npc_info = document.getElementById(\"NPC_List\").value.split('\\n');\n\tgenerate[\"NPCs\"] = raw_npc_info.filter((el) => {\n\t\treturn el != null && el != \"\";\n\t})\n\n\n\t/*********************/\n\t/* Validate Misc */\n\t/*********************/\n\tgenerate[\"Allow Pokemon\"] = all_select.Pokemon.value;\n\tgenerate[\"Dump Json\"] = all_select.DumpJson.value;\n\tgenerate[\"Town Name\"] = document.getElementById('TownName').value;\n\n\tconsole.log(settings);\n\tconsole.log(generate);\n\t// If there are no errors, submit everything\n\tif (correct) {\n\t\teel.submit(settings, generate);\n\t}\n\n\t// document.getElementById(\"wholeForm\").style.display = 'none';\n\tdocument.getElementById(\"mainHeader\").innerHTML = 'Form Submitted.';\n}", "function validate(event) {\n event.preventDefault()\n removeErrorMessage()\n removeValidMessage()\n\n validForm = true\n validateName()\n validateCarYear()\n validateCarMake()\n validateCarModel()\n validateStartDate()\n validateDays()\n validateCard()\n validateCvv()\n validateExpiration()\n\n showValidMessage()\n}", "calculate() {\n let age = inputsRequired[0].elem.value;\n let height = inputsRequired[1].elem.value;\n let weight = inputsRequired[2].elem.value;\n let neckCircumference = inputsRequired[3].elem.value;\n let waistCircumference = inputsRequired[4].elem.value;\n let hipCircumference = inputsRequired[5].elem?.value;\n \n let person = new Person();\n \n let feetToCMFactor = 30.48; // *\n let poundsToKGFactor = 2.205; // /\n let inchesToCMFactor = 2.54; // *\n \n person.age = age;\n person.height = height;\n person.weight = weight;\n person.neckCircumference = neckCircumference;\n person.waistCircumference = waistCircumference;\n person.hipCircumference = hipCircumference;\n\n if(this.unit === 1) {\n person.height = height * feetToCMFactor;\n person.weight = weight / poundsToKGFactor;\n person.neckCircumference = neckCircumference * inchesToCMFactor;\n person.waistCircumference = waistCircumference * inchesToCMFactor;\n person.hipCircumference = hipCircumference * inchesToCMFactor;\n }\n \n if(this.gender === 'male') {\n person.gender = 0;\n } else if(this.gender === 'female') {\n person.gender = 1;\n }\n \n let bodyMassIndex = person.findBMI();\n let bodyFatPercentage = person.findBodyFatPercentage();\n let dailyCalorieIntake = person.findDailyCalorieIntake();\n let bmr = person.findBMR(dailyCalorieIntake);\n let activityLevelBmr = bmr * activityLevel.find(lvl => lvl.name === this.activityLevelDetails).value;\n \n function valueFromPercentage(v, p) {\n return ((v * p) / 100);\n }\n \n let calorieBasedOnGoal = activityLevelBmr - workoutGoal.find(goal => goal.name === this.workoutGoalChoosen).execute(activityLevelBmr);\n let macroValuesBasedOnGoal = macroForWorkoutGoal.find(goal => goal.name === this.workoutGoalChoosen);\n let carb = Math.round(valueFromPercentage(calorieBasedOnGoal, macroValuesBasedOnGoal.carb)/4);\n let protein = Math.round(valueFromPercentage(calorieBasedOnGoal, macroValuesBasedOnGoal.protein)/4);\n let fat = Math.round(valueFromPercentage(calorieBasedOnGoal, macroValuesBasedOnGoal.fat)/9);\n \n this.renderOutput(\n bodyMassIndex,\n bodyFatPercentage,\n dailyCalorieIntake,\n activityLevelBmr,\n carb,\n protein,\n fat\n );\n }", "function proceed1() {\n\n //pull our current form data\n var _numberRenting = document.getElementById(\"numberRenting\").value;\n var _groupName = document.getElementById(\"groupName\").value;\n var _phoneNumber = document.getElementById(\"phoneNumber\").value;\n var _emailAddress = document.getElementById(\"email\").value;\n var _pickUpDate = document.getElementById(\"pickUpDate\").value;\n var _returnDate = document.getElementById(\"returnDate\").value;\n\n if (_numberRenting == \"-\") {\n alert(\"Please enter the number of people in your group.\");\n return;\n }\n else if (_groupName == \"\") {\n alert(\"Please enter a 'Group Name'\");\n return;\n }\n else if (_phoneNumber == \"\") {\n alert(\"Please enter a 'Phone Number'\");\n return;\n }\n else if (_emailAddress == \"\") {\n alert(\"Please enter an 'Email Address'\");\n return;\n }\n else if (_pickUpDate == \"\") {\n alert(\"Please enter a 'Pick Up Date'\");\n return;\n }\n else if (_returnDate == \"\") {\n alert(\"Please enter a 'Return Date'\");\n return;\n }\n\n //check the dates to make sure they are valid\n if (isNaN(parseInt(_pickUpDate.substring(0, 2))) == true ||\n isNaN(parseInt(_pickUpDate.substring(3, 5))) == true ||\n isNaN(parseInt(_pickUpDate.substring(6))) == true ||\n _pickUpDate.substring(2, 3) != \"/\" ||\n _pickUpDate.substring(5, 6) != \"/\" ||\n _pickUpDate.substring(6, 9) != \"201\") {\n alert(\"Please enter a 'Pick Up Date' in the format XX/XX/201X\");\n return;\n }\n\n //check pick up date month and day\n if (parseInt(_pickUpDate.substring(0, 2)) > 12 ||\n parseInt(_pickUpDate.substring(0, 2)) < 1 ||\n parseInt(_pickUpDate.substring(3, 5)) > 31 ||\n parseInt(_pickUpDate.substring(3, 5)) < 1) {\n alert(\"Please enter a valid 'Pick Up Date'\");\n return;\n }\n\n //check return date month and day\n if (parseInt(_returnDate.substring(0, 2)) > 12 ||\n parseInt(_returnDate.substring(0, 2)) < 1 ||\n parseInt(_returnDate.substring(3, 5)) > 31 ||\n parseInt(_returnDate.substring(3, 5)) < 1) {\n alert(\"Please enter a valid 'Return Date'\");\n return;\n }\n\n if (isNaN(parseInt(_returnDate.substring(0, 2))) == true ||\n isNaN(parseInt(_returnDate.substring(3, 5))) == true ||\n isNaN(parseInt(_returnDate.substring(6))) == true ||\n _returnDate.substring(2, 3) != \"/\" ||\n _returnDate.substring(5, 6) != \"/\" ||\n _returnDate.substring(6, 9) != \"201\") {\n alert(\"Please enter a 'Return Date' in the format XX/XX/201X\");\n return;\n }\n\n //if our code reaches this point, the dates are formatted correctly\n //now we'll check dates in relation to each other\n if (parseInt(_pickUpDate.substring(0, 2)) >\n parseInt(_returnDate.substring(0, 2))) {\n alert(\"Please make sure 'Return Date' is after 'Pick Up Date'\");\n return;\n }\n\n if (parseInt(_pickUpDate.substring(0, 2)) ==\n parseInt(_returnDate.substring(0, 2)) &&\n parseInt(_pickUpDate.substring(3, 5)) >\n parseInt(_returnDate.substring(3, 5))) {\n alert(\"Please make sure 'Return Date' is after 'Pick Up Date'\");\n return;\n }\n\n if (parseInt(_pickUpDate.substring(9)) >\n parseInt(_returnDate.substring(9))) {\n alert(\"Please make sure 'Return Date' is after 'Pick Up Date'\");\n return;\n }\n\n //our dates are correct, now let's assign the form values to our global variables\n numberRenting = _numberRenting;\n groupName = _groupName;\n phoneNumber = _phoneNumber;\n emailAddress = _emailAddress;\n pickUpDate = _pickUpDate;\n returnDate = _returnDate;\n\n setupStep2();\n}", "function processEntries() {\n\tlet investmentValue = parseFloat($('investment').value);\n\tlet rate = parseFloat($('rate').value);\n\tlet years = parseFloat($('years').value);\n\tlet errorMessage;\n\tif (!$('investment').value || !$('rate').value || !$('investment').value) {\n\t\talert(\"All fields are required\");\n\t}\n\telse if(isNaN(investmentValue) || isNaN(rate) || isNaN(years)) {\n\t\talert(\"All entries must be numeric\");\n\t}\n\telse if \t(investmentValue <= 0 || investmentValue > 100000){\n\t\terrorMessage = \"Investment must be a number greater than 0 and less than or equal to 100,000.\"\n\t\talert(errorMessage);\n\t\t$('investment').focus();\n\t}\n\telse if (rate <= 0 || rate > 15) {\n\t\terrorMessage = \"Investment rate must be greater than 0 and less than or equal to 15%.\"\n\t\talert(errorMessage);\n\t\t$('rate').focus();\n\t}\n\telse if (years <= 0 || years > 50 || years % 1 !== 0) {\n\t\terrorMessage = \"Number of years must be a positive integer of 50 or less\";\n\t\talert(errorMessage);\n\t\t$('years').focus();\n\t}\n\telse {\n\t\tfuture_value.value = calculateFV(investmentValue, rate, years).toFixed(2);\n\t}\t\n}", "function validateAndSubmit() {\r\n var isValid = false;\r\n isValid = validateForm();\r\n if (isValid == true) {\r\n disableButtons() // make sure you can only press the submit button once\r\n document.getElementById('evaluationForm').submit();\r\n }\r\n }", "function calculateResults() {\n document.getElementById('answer').style.display = 'block';\n\n document.getElementById('loading').style.display = 'none';\n\n document.getElementById('calc').style.display = 'none';\n\n inputProgress.style.display = 'none';\n progress.style.display = 'none';\n var showTable = document.getElementById('table');\n showTable.classList.remove('invisible');\n\n caclRiskProfile();\n}", "function validateScreenTimeGoalSubmission()\n{\n //get all form fields\n var stGoal = document.getElementById(\"screenTimeGoal\").value; \t\t//screen time goal\n \t \n //flag to ensure all data accurate\n var isValid = true;\n \n //ensure screen time goal is submitted\n if(stGoal === \"\" || isNaN(stGoal) || stGoal<=0)\n {\n //show error message and mark input invalid\n document.getElementById(\"st_error\").style.display = \"block\";\n isValid = false;\n }//end if\n \n\telse\n\t{\n\t\tdocument.getElementById(\"st_error\").style.display = \"none\";\n\t}\n return isValid;\n}//close validateScreenTimeGoalSubmission", "function validateForm(){\r\n\r\n\tvar fn= document.forms[\"myform\"][\"fname\"].value;\r\n\tvar ln= document.forms[\"myform\"][\"lname\"].value;\r\n\tvar eml= document.forms[\"myform\"][\"email\"].value;\r\n\tvar mbl= document.forms[\"myform\"][\"mobile\"].value;\r\n\tvar trip= document.forms[\"myform\"][\"trip\"].value;\r\n\tvar prsn= document.forms[\"myform\"][\"person\"].value;\r\n\t\r\n\r\n\r\n\tif(fn == \"\"){\r\n\t\talert(\"Please enter First Name\");\r\n\t\treturn false;\r\n\t}\r\n\tif(ln == \"\"){\r\n\t\talert(\"Please enter last Name\");\r\n\t\treturn false;\r\n\t}\r\n\tif(eml == \"\"){\r\n\t\talert(\"Please enter Email-id\");\r\n\t\treturn false;\r\n\t}\r\n\tif(mbl == \"\"){\r\n\t\talert(\"Please enter Mobile Number\");\r\n\t\treturn false;\r\n\t}\r\n\tif(trip == \"\"){\r\n\t\talert(\"Select Your trip\");\r\n\t\treturn false;\r\n\t}\r\n\tif(prsn == \"\"){\r\n\t\talert(\"select persons for trip\");\r\n\t\treturn false;\r\n\t}\r\n\t\r\n}", "function calculateResults(){\n// console.log('calculating.....');\n\n// UI variables\n// amount variable\nconst amount = document.getElementById('amount');\n// interest rate variable\nconst interest = document.getElementById('interest');\n// years to pay\nconst years = document.getElementById('years');\n// monthly payment\nconst monthlyPayment = document.getElementById('monthly-payment');\n// total payment\nconst totalPayment = document.getElementById('total-payment');\n// total interest\nconst totalInterest = document.getElementById('total-interest')\n\nconst principal = parseFloat(amount.value);\nconst calculatedInterest = parseFloat(interest.value)/100/12;\nconst calculatedPayments = parseFloat(years.value)*12;\n\n// compute monthly payment\nconst x = Math.pow(1 + calculatedInterest , calculatedPayments);\nconst monthly = (principal*x*calculatedInterest)/(x-1);\n\n\n// hide the loading image\ndocument.getElementById('loading').style.display = 'none'\n\n\nif (isFinite(monthly)){\n\n// show results\ndocument.getElementById('result').style.display = 'block';\n\n// show the reset all button\ndocument.querySelector('div.reset').style.display = 'block'\n\ndocument.querySelector('div.reset input#resetAll').addEventListener('dblclick', resetAll);\n\n monthlyPayment.value = monthly.toFixed(2);\n totalPayment.value = (monthly*calculatedPayments).toFixed(2);\n totalInterest.value = ((monthly*calculatedPayments)-principal).toFixed(2);\n}else {\nshowError('please check your numbers')\n}\n\n}", "function validateForm() {\n // Retrieving the values of form elements \n var dept_num = document.contactForm.dept_num.value;\n var dept_name = document.contactForm.dept_name.value;\n var dept_leader = document.contactForm.dept_leader.value;\n\t// Defining error variables with a default value\n var deptnumErr = deptnameErr = deptleaderErr = true;\n // Validate name\n if(dept_num == \"\") {\n printError(\"deptnumErr\", \"Please enter Depertment Number\");\n } else {\n printError(\"deptnumErr\", \"\");\n deptnumErr = false;\n }\n // Validate email address\n if(dept_name == \"\") {\n printError(\"deptnameErr\", \"Please enter Depertment Name\");\n } else {\n printError(\"deptnameErr\", \"\");\n deptnameErr = false;\n }\n // Validate mobile number\n if(dept_leader == \"\") {\n printError(\"deptleaderErr\", \"Please enter Depertment Leader\");\n } else {\n printError(\"deptleaderErr\", \"\");\n deptleaderErr = false;\n }\n\n \n // Prevent the form from being submitted if there are any errors\n if((deptnumErr || deptleaderErr || deptnameErr ) == true) {\n return false;\n } else {\n // Creating a string from input data for preview\n var dataPreview = \"You've entered the following details: \\n\" +\n \"Depertment Number: \" + dept_num + \"\\n\" +\n \"Depertment Name: \" + dept_name + \"\\n\" +\n \"Depertment Leader: \" + dept_leader + \"\\n\";\n // Display input data in a dialog box before submitting the form\n alert(dataPreview);\n }\n}", "function validateForm() {\n\n //this variable will contain all data delivered by the form\n let data = {}\n\n //this variable will contain all the errors, if any where made while filing in the form\n let validationErrors = {}\n\n //let's link the path from which our data var will get the data which is the inputs\n data.firstName = document.querySelector('#firstName')\n data.lastName = document.querySelector('#lastName')\n data.email = document.querySelector('#email')\n data.textbox = document.querySelector('#textbox')\n\n //validation start\n\n //first name validation. if empty, length\n if (!data.firstName.value) {\n console.error('No first name value')\n validationErrors.firstName = 'Please enter your first name'\n\n } else if (!data.firstName.length > 2) {\n console.error('Name value too short')\n validationErrors.firstName = 'Your name is too short, please enter atleast two letters'\n console.info('First Name present')\n }\n\n\n //validate last name. if empty, length\n if (!data.lastName.value) {\n console.error('No Last name value')\n validationErrors.lastName = 'Please enter your first name'\n\n } else if (!data.lastName.length > 2) {\n console.error('Last name value too short')\n validationErrors.lastName = 'Your Last name is too short, please enter atleast two letters'\n console.info('Last Name present')\n }\n\n //validate email\n if (!data.email.value) {\n console.error('no email value')\n validationErrors.email = 'please enter your Email';\n } else {\n console.info('Email present')\n //the email part of the form is not empty, we should still check if the mail contains a valid combination\n\n let emailRegExp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/;\n //test the mail now. if the value is valid or not\n if (!emailRegExp.test(data.email.value)) {\n validationErrors.email = 'Invalid email address'\n }\n }\n\n\n //validate textbox\n if (!data.textbox.value) {\n console.error('no value in textbox')\n validationErrors.textbox = 'please enter a message'\n } else if (!data.textbox.length > 3) {\n console.error('textbox value too short')\n validationErrors.lastName = 'your text is too short!'\n console.info('Last Name present')\n }\n //call the functions. if we have errors we will implement them in the DOM. else the \n\n //check if the errors object has data \n if (Object.keys(validationErrors).length > 0) {\n console.log('error')\n displayErrors(validationErrors, data)\n } else {\n console.log('no errors found');\n sendForm(data)\n }\n\n }", "function check_form_certify() {\n const form = document.getElementById('form_certify');\n const error = document.getElementById('form_certify_error');\n error.style.display = 'none';\n if (form.diplom.value == '') {\n error.innerHTML = 'Please select a diplom.';\n error.style.display = 'block';\n return false;\n } else if (!(2010 <= parseInt(form.awarding_year.value, 10) && parseInt(form.awarding_year.value, 10) <= 2019)) {\n error.innerHTML = 'Please fill in a valid awarding date. (2010 -> 2019)';\n error.style.display = 'block';\n return false;\n } else if (!form.student_name.value.match(/^[A-Za-z ]+$/)) {\n error.innerHTML = 'Please fill in a valid name. What I call a \"valid name\" is a name given with only letters and spaces.<br>\\\n Ex: \"Jean-Pierre Dupont\" should be entered as \"Jean Pierre Dupont\"';\n error.style.display = 'block';\n return false;\n }\n const birthdate = form.birthdate.value.split('/');\n if (birthdate.length != 3) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1 <= parseInt(birthdate[0], 10) && parseInt(birthdate[0], 10) <= 31)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1 <= parseInt(birthdate[1], 10) && parseInt(birthdate[1], 10) <= 12)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995';\n error.style.display = 'block';\n return false;\n } else if (!(1919 <= parseInt(birthdate[2], 10) && parseInt(birthdate[2], 10) <= 2019)) {\n error.innerHTML = 'Please fill in a valid birthdate. Ex: 01/01/1995 with the 1919 <= year <= 2019';\n error.style.display = 'block';\n return false;\n }\n return true;\n}", "function MM_validateForm() { //v4.0\n var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;\n for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);\n if (val) { nm=val.name; if ((val=val.value)!=\"\") {\n if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');\n if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\\n';\n } else if (test!='R') { num = parseFloat(val);\n if (isNaN(val)) errors+='- '+nm+' must contain a number.\\n';\n if (test.indexOf('inRange') != -1) { p=test.indexOf(':');\n min=test.substring(8,p); max=test.substring(p+1);\n if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\\n';\n } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\\n'; }\n } if (errors) alert('The following error(s) occurred:\\n'+errors);\n document.MM_returnValue = (errors == '');\n}", "function validateForm() {\r\n var x = document.forms[\"myForm\"][\"AccountNumber\"].value;\r\n if (x == \"\") {\r\n alert(\"Invalid Card Number\");\r\n myForm.AccountNumber.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"AccountNumber2\"].value;\r\n if (x == \"\") {\r\n alert(\"Invalid Card Number\");\r\n myForm.AccountNumber2.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"AccountNumber3\"].value;\r\n if (x == \"\") {\r\n alert(\"Invalid Card Number\");\r\n myForm.AccountNumber3.focus();\r\n return false;\r\n }\r\n\tvar x = document.forms[\"myForm\"][\"AccountNumber4\"].value;\r\n if (x == \"\") {\r\n alert(\"Invalid Card Number\");\r\n myForm.AccountNumber4.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"ExpMonth\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Expiration Month\");\r\n myForm.ExpMonth.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"ExpYear\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Expiration Year\");\r\n myForm.ExpYear.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"AVS\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter the CVV Code\");\r\n myForm.AVS.focus();\r\n return false;\r\n }\r\n \r\n var x = document.forms[\"myForm\"][\"Contact_FullName\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Name as it Appears on Your Card\");\r\n myForm.Contact_FullName.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"Contact_StreetAddress\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Billing Address\");\r\n myForm.Contact_StreetAddress.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"Contact_City\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Billing City\");\r\n myForm.Contact_City.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"Contact_State\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Billing State\");\r\n myForm.Contact_State.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"zip\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Billing Zip Code\");\r\n myForm.zip.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"email\"].value;\r\n var atpos = x.indexOf(\"@\");\r\n var dotpos = x.lastIndexOf(\".\");\r\n if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {\r\n alert(\"Please Enter a Valid Email Address\");\r\n myForm.email.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"SContact_FullName\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Full Name\");\r\n myForm.SContact_FullName.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"SContact_StreetAddress\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Shipping Address\");\r\n myForm.SContact_StreetAddress.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"SContact_City\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Shipping City\");\r\n myForm.SContact_City.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"SContact_State\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Shipping State\");\r\n myForm.SContact_State.focus();\r\n return false;\r\n }\r\n var x = document.forms[\"myForm\"][\"Szip\"].value;\r\n if (x == \"\") {\r\n alert(\"Please Enter Your Shipping Zip Code\");\r\n myForm.zip.focus();\r\n return false;\r\n }\r\n}", "function formValidator(d) {\nd.preventDefault();\n\t// Create 2 empty 'buckets', one for collecting data and \n\t// the other for error-messages\n\tlet data = {};\n// data.prop = 'Test property';\n\tlet errors = [];\n\t\n\t// 1. Validating fullname\n\tif (fn.value) {\n\t\tdata.fullname = fn.value;\n\t} else {\n\t\terrors.push('First name has to be added!');\n\t}\n\t\n\t// 2. Validating email\n\t\n \tif (em.value) {\n if (pattern.test(em.value)) { \n\t\t\n \n \n data.email = em.value;\n\t} else {\n error.push('Invalid email!');\n }\n \n \n } else {\n\t\terrors.push('Email has to be added!');\n\t}\n\t\n // 1. Validating email\n\tif (msg.value) {\n\t\tdata.message = msg.value;\n\t} else {\n\t\terrors.push('Message has to be added!');\n\t}\n \n \n \n \n\t// 3. Handle the feedback\n if (errors.length === 0)\n\t{\n// Print the data obect inside the console \nconsole.log(data);\n\n document.getElementById(\"htmlform\").reset();\n }\n else {\nconsole.log(errors); \n }\n\n \n\n}", "function showResult(event) {\n event.preventDefault();\n const fullName = getFullName();\n const email = getEmail();\n const house = getHouse();\n const family = getFamily();\n const content = getContent();\n const rate = getRate();\n const comment = getComment();\n deleteFormContent();\n const form = document.getElementById('evaluation-form');\n form.innerHTML = `${fullName}${email}${house}${family}${content}${rate}${comment}`;\n}", "function validateForm(ul, amnt, d, form) {\n\n // Ensure at least one payee is selected.\n if (document.getElementById(ul).getElementsByTagName('li').length < 1) {\n return \"Please choose at least one payee.\";\n }\n\n // Validate dates.\n var date = document.getElementById(d).value;\n console.log(date)\n date = date.split(\"-\");\n if (date.length != 3) {\n return \"Please ensure you use the correct YYYY-MM-DD format.\"\n }\n var day = date[2];\n var month = date[1];\n var year = date[0];\n day = day.replace(/\\D/g, '');\n month = month.replace(/\\D/g, '');\n year = year.replace(/\\D/g, '');\n if (parseInt(day, 10) > 31 || parseInt(day, 10) <= 0) {\n return \"Please ensure you have a valid day and follow the MM-DD-YYYY format.\"\n }\n if (parseInt(month, 10) > 12 || parseInt(month, 10) <= 0) {\n return \"Please ensure you have a valid month and follow the MM-DD-YYYY format.\"\n }\n\n var dt = new Date();\n if (parseInt(year, 10) < dt.getFullYear()\n && parseInt(month, 10) < dt.getMonth()\n && parseInt(day, 10) < dt.getDate()) {\n return \"The date has passed.\"\n }\n\n // Validate amount.\n var amount = document.getElementById(amnt).value;\n if (parseFloat(amount) <= 0) {\n return \"Please only input positive numeric amounts.\"\n }\n\n // check from_acc != payee\n if (form == 'req-form') {\n var from_acc = document.getElementById('req_from').value;\n var result = exist('req_users',from_acc)\n if(result == 1) {\n return \"You are requesting from yourself !\"\n }\n } else {\n var from_acc = document.getElementById('pay_from').value;\n var result = exist('pay_users',from_acc)\n if(result == 1) {\n return \"You are paying from yourself !\"\n }\n }\n\n // Checks split amounts for a request form.\n if (form == 'req-form') {\n var result = check_split(amount, ul);\n if (result == 1) {\n return \"Split amounts do not sum up to requested amount.\"\n }\n }\n\n return \"\";\n}", "function submitResults() {\n\tif ( conditionsMet() ) {\n\t\tdisplayForm(\"#form\");\n\t}\n\telse {\n\t\talert(\"One of the sets is empty! Each set must contain at least one number.\");\n\t}\n}", "function isValidForm () {\n\n let validForm = true;\n\n // Regex for validation of certain inputs\n const emailRegex = /^\\w+@\\w+.[A-Za-z]{3}$/;\n const creditCardNumberRegex = /^\\d{13,16}$/;\n const zipCodeRegex = /^\\d{5}$/;\n const cvvRegex = /^\\d{3}$/;\n\n resetInvalidInfo();\n\n // Checks if name field is empty\n if ($(\"#name\").val() === \"\") {\n validForm = false;\n $(\"#name\").addClass(\"invalid-information\");\n $(\"label[for='name']\").addClass(\"invalid-label\");\n }\n\n // Checks if a invalid email address is entered\n if (emailRegex.test($(\"#mail\").val()) === false) {\n validForm = false;\n $(\"#mail\").addClass(\"invalid-information\");\n $(\"label[for='mail']\").addClass(\"invalid-label\");\n }\n\n // Checks if no activities are checked\n if ($(\"input:checked\").length === 0) {\n validForm = false;\n $(\"legend\").eq(2).addClass(\"invalid-label\");\n }\n\n // Validates Credit Card information if chosen\n if ($(\"#payment :selected\").text() === \"Credit Card\") {\n\n // Checks if Credit Card number is valid\n if (creditCardNumberRegex.test($(\"#cc-num\").val()) === false) {\n validForm = false;\n $(\"#cc-num\").addClass(\"invalid-information\");\n $(\"label[for='cc-num']\").addClass(\"invalid-label\");\n }\n\n // Checks if Zip Code is valid\n if (zipCodeRegex.test($(\"#zip\").val()) === false) {\n validForm = false;\n $(\"#zip\").addClass(\"invalid-information\");\n $(\"label[for='zip']\").addClass(\"invalid-label\");\n }\n\n // Checks if CVV is valid\n if (cvvRegex.test($(\"#cvv\").val()) === false) {\n validForm = false;\n $(\"#cvv\").addClass(\"invalid-information\");\n $(\"label[for='cvv']\").addClass(\"invalid-label\");\n }\n\n }\n\n return validForm;\n\n}", "validate(event) {\n\t\tevent.preventDefault();\n\n\t\tlet valid = true;\n\n\t\tconst form = document.forms['form'];\n\t\tconst formNodes = Array.prototype.slice.call(form.childNodes);\n\t\tvalid = this.props.schema.fields.every(field => {\n\t\t\tconst input = formNodes.find(node => node.id === field.id);\n\n\t\t\t// Check field is answered if mandatory\n\t\t\tif (!field.optional || typeof field.optional === 'object') {\n\t\t\t\tlet optional;\n\n\t\t\t\t// Check type of 'optional' field.\n\t\t\t\tif (typeof field.optional === 'object') {\n\n\t\t\t\t\t// Resolve condition in 'optional' object.\n\t\t\t\t\tconst dependentOn = formNodes.find(node => node.id === field.optional.dependentOn);\n\t\t\t\t\tconst dependentOnValue = this.getValue(dependentOn, field.type);\n\n\t\t\t\t\t// Try and find a value in schema 'values' object that matches a value\n\t\t\t\t\t// given in 'dependentOn' input.\n\t\t\t\t\t// Otherwise, use the default value provided.\n\t\t\t\t\tconst value = field.optional.values.find(val => dependentOnValue in val);\n\n\t\t\t\t\tif (value) {\n\t\t\t\t\t\toptional = value[dependentOnValue];\n\t\t\t\t\t} else {\n\t\t\t\t\t\toptional = field.optional.default;\n\t\t\t\t\t}\n\n\t\t\t\t} else {\n\t\t\t\t\t// Else 'optional' field is just a boolean value.\n\t\t\t\t\toptional = field.optional;\n\t\t\t\t}\n\n\t\t\t\t// If not optional, make sure input is answered.\n\t\t\t\tif (!optional) {\n\t\t\t\t\treturn Boolean(this.getValue(input, field.type));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn field.validations.every(validation => {\n\t\t\t\tif (validation.containsChar) {\n\t\t\t\t\t// Ensure input value has the specified char.\n\t\t\t\t\treturn this.getValue(input, field.type).trim().includes(validation.containsChar);\n\n\t\t\t\t} else if (validation.dateGreaterThan) {\n\t\t\t\t\t// Ensure difference between today and given date is larger than specified interval.\n\t\t\t\t\tconst value = this.getValue(input, field.type);\n\n\t\t\t\t\tlet diff = Date.now() - new Date(value).getTime();\n\n\t\t\t\t\t// Convert from milliseconds to the unit given in schema.\n\t\t\t\t\tswitch(validation.dateGreaterThan.unit) {\n\t\t\t\t\t\tcase \"seconds\":\n\t\t\t\t\t\t\tdiff = diff / 1000;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"minutes\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"hours\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"days\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"years\":\n\t\t\t\t\t\t\tdiff = diff / 1000 / 60 / 60 / 24 / 365;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\treturn diff > validation.dateGreaterThan.value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\n\t\t// If all checks pass, submit the form. Otherwise alert the user.\n\t\tif (valid) {\n\t\t\tthis.submit();\n\t\t} else {\n\t\t\talert(\"Form is not valid. Please make sure all inputs have been correctly answered.\");\n\t\t}\n\n\t}", "function calcEEF() {\n //get the value of the factors to be used in calculations\n var coal_factor = document.getElementById(\"coal_factor\").innerHTML;\n var coal_percent = parseFloat(document.getElementById(\"coal_percent\").innerHTML) / 100;\n var oil_factor = document.getElementById(\"oil_factor\").innerHTML;\n var oil_percent = parseFloat(document.getElementById(\"oil_percent\").innerHTML) / 100;\n var nat_gas_factor = document.getElementById(\"nat_gas_factor\").innerHTML;\n var nat_gas_percent = parseFloat(document.getElementById(\"nat_gas_percent\").innerHTML) / 100;\n var EEF;\n\n //Is radio button for national average checked\n if (document.getElementById('national_average').checked) {\n //Calculate the national average EEF\n var EEF = coal_factor * coal_percent + oil_factor * oil_percent + nat_gas_factor * nat_gas_percent;\n\n //Is radio button for custom average checked\n } else if (document.getElementById('custom_average').checked) {\n\n //get the custom values\n var coal_percent = document.getElementById(\"custom_coal_percent\").value / 100;\n var oil_percent = document.getElementById(\"custom_oil_percent\").value / 100;\n var nat_gas_percent = document.getElementById(\"custom_nat_gas_percent\").value / 100;\n\n //Calculate the custom EEF\n var EEF = coal_factor * coal_percent + oil_factor * oil_percent + nat_gas_factor * nat_gas_percent;\n\n }\n return EEF;\n\n}", "validateForm() {\r\n if(this.getInputVal(this.inputBill) !== \"\" && \r\n this.getInputVal(this.inputPeople) !== \"\" &&\r\n (this.getInputVal(this.inputCustom) !== \"\" || \r\n this.percentageBtns.some(btn => btn.classList.contains(\"active\")))) \r\n {\r\n this.disableReset(false);\r\n return true;\r\n }\r\n else {\r\n this.disableReset(true);\r\n this.displayResult(\"__.__\", \"__.__\");\r\n return false;\r\n }\r\n }", "function calculate() {\r\n //---- FORM VALUES ----\r\n //variables: miles_driving, average_miles_per_gallon, cost_per_gallon, hotel_cost, snacks, other_costs\r\n //Estimate Distance\r\n var miles_driving = Number($(\"#miles_driving\").val()); //YOUR CODE HERE TO GET THE VALUE\r\n console.log(\"miles_driving \" + miles_driving);\r\n //MPG\r\n var average_miles_per_gallon = Number($(\"#average_miles_per_gallon\").val()); //YOUR CODE HERE TO GET THE VALUE\r\n console.log(\"average_miles_per_gallon \" + average_miles_per_gallon);\r\n //PPG\r\n var cost_per_gallon = Number($(\"#cost_per_gallon\").val()); //YOUR CODE HERE TO GET THE VALUE\r\n console.log(\"cost_per_gallon \" + cost_per_gallon);\r\n //Hotel\r\n var hotel_cost = Number($(\"#hotel_cost\").val());\r\n console.log(\"hotel_cost \" + hotel_cost);\r\n //Snacks\r\n var snacks_cost = Number($(\"#snacks_cost\").val());\r\n console.log(\"snacks_cost \" + snacks_cost);\r\n //other_costs\r\n var other_costs = Number($(\"#other_costs\").val());\r\n console.log(\"other_costs\" + other_costs);\r\n\r\n //----- CALCULATED VALUES -----\r\n //calculate: distance / mpg\r\n var number_of_gallons = miles_driving / average_miles_per_gallon; //YOUR CODE HERE TO GET THE VALUE\r\n console.log(\"number_of_gallons\" + number_of_gallons);\r\n //calculate: total_mileage_cost = estimate distance * ppg\r\n var total_mileage_cost = number_of_gallons * cost_per_gallon; //YOUR CODE HERE TO GET THE VALUE\r\n console.log(\"total_mileage_cost \" + total_mileage_cost);\r\n\r\n\r\n var sum = total_mileage_cost + hotel_cost + snacks_cost + other_costs;\r\n\r\n alert(\"$\" + sum);\r\n }", "function validate() {\n // Purpose - First, errors are cleared. Then, input is verified as valid by making sure it is a positive number. If the input is not valid an error class name is attached to the parent element of the Starting Bet input field. (This error may be cleared by the clearErr() function on the next call. See clearErr() function below.) If input is valid, next the playUntilBroke function is called to evaluate the outcome of a Lucky Sevens rule set as described here https://lms.thesoftwareguild.com/courses/281/pages/code-practice-lucky-sevens?module_item_id=35721.\n \n clearErr();\n var startingBet = parseInt(document.forms[\"startingBetForm\"][\"startingBet\"].value, 10);\n\n if(isNaN(startingBet) || startingBet <= 0) {\n alert(\"In order to play the game, you must have a starting bet that is greater than $0.\");\n document.forms[\"startingBetForm\"][\"startingBet\"].parentElement.className = \"form-inline has-error\";\n document.forms[\"startingBetForm\"][\"startingBet\"].focus();\n return false;\n }\n\n playUntilBroke(startingBet);\n\n return false;\n // Returning false to the form that calls this function prevents the form from being submitted and the page from being updated. This in turn allows us to view the results title and table.\n}", "function validateSubmission(form) {\n var alertMsg = \"\"; // Stores the message to display to user indicating which fields are entered incorrectly\n var checkEntry = true; // Is true if all fields are entered correctly, set to false if a field is entered incorrectly\n if (form.name.value == \"\") {\n //checks to see if Name field contains user input\n window.alert(\"No Name entered.\");\n return false;\n }\n if (form.price.value == \"\") {\n //checks to see if Price field contains user input, if not the validate function returns false\n window.alert(\"No Price entered.\");\n return false;\n }\n if (form.long1.value == \"\") {\n //checks to see if Longittude field contains user input, if not the validate function returns false\n window.alert(\"No Longittude entered.\");\n return false;\n }\n if (form.latt1.value == \"\") {\n //checks to see if Lattitude field contains user input, if not the validate function returns false\n window.alert(\"No Lattitude entered.\");\n return false;\n }\n\n if (!validateSpotName(form.name.value)) {\n //checks to see if Name entry is in the appropriate format\n var el = document.getElementsByName(\"name\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Name must be 5 characters long and cannot begin with a space or have consecutive spaces.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"name\")[0].style.backgroundColor = \"white\";\n }\n if (\n !validateDescription(form.description.value) &&\n form.description.value != \"\"\n ) {\n //checks to see if Description entry is in the appropriate format\n var el = document.getElementsByName(\"description\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += \"Description must be less than 300 characters.\\n\"; //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n checkEntry = false;\n } else {\n document.getElementsByName(\"description\")[0].style.backgroundColor =\n \"white\";\n }\n if (!validatePrice(form.price.value)) {\n //checks to see if Price entry is in the appropriate format\n var el = document.getElementsByName(\"price\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Price must contain only digits, a single decimal point and up to 2 digits following the decimal point.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"price\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.long1.value)) {\n //checks to see if Longittude entry is in the appropriate format\n var el = document.getElementsByName(\"long1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Longittude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"long1\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.latt1.value)) {\n //checks to see if Lattitude entry is in the appropriate format\n var el = document.getElementsByName(\"latt1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Lattitude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"latt1\")[0].style.backgroundColor = \"white\";\n }\n if (!checkEntry) {\n //if any of the input fields have an entry in an incorrect format\n window.alert(alertMsg); //displays an error message for each incorrect field to user\n return false; //the validate function returns fa;se\n }\n\n return true; //All input fields contain values in the correct format so the validate function returns true\n}", "function validation() {\r\n\t\tif ((circleRecipe.checked == true && recipeCircleArea() > 0) || (rectangleRecipe.checked == true && returnValue(lengthARecipe) > 0 && returnValue(lengthBRecipe) > 0)) {\r\n\t\t\tif ((circleUser.checked == true && userCircleArea() > 0) || (rectangleUser.checked == true && returnValue(lengthAUser) > 0 && returnValue(lengthBUser) > 0)) {\r\n\t\t\t\tconvertAlert.innerHTML = '';\r\n\t\t\t\tconvert();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tconvertAlert.innerHTML = '<p>You must define what kind of baking mold you use and inscribe its dimensions before convert!</p>';\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tconvertAlert.innerHTML = '<p>You must define what kind of baking mold is used in the recipe and inscribe its dimensions before convert!</p>';\r\n\t\t}\r\n\t}", "function validateForm() {\n clearPage(); // Removes previous popups\n\n // Alerts the user if they have submitted an input with no text\n if (document.forms[\"inputFood\"][\"food\"].value == \"\") {\n warningAlert.innerHTML = \"Please Provide a Dish\";\n warningAlert.classList.add(\"reveal\");\n return false;\n }\n getFood(document.forms[\"inputFood\"][\"food\"].value);\n}", "function validateForm(e) {\n e.preventDefault();\n let rateValue = ratingSelected;\n let satValue = document.forms[\"surveyForm\"][\"satisfaction\"].value;\n if (rateValue == \"\" || rateValue == null) {\n alert(\"Provide rating for the survey\");\n return false;\n } else if (satValue == \"\") {\n alert(\n \"Tell us how satisfied you are with this survey, select option accordingly\"\n );\n return false;\n } else if (!isValidDescription()) {\n alert(\"Select at least one description for our product\");\n return false;\n } else {\n //Hide the container and show success alert div\n let containerDiv = document.getElementById(\"container\");\n setTimeout(function() {}, 500);\n containerDiv.style.display = \"none\";\n let sucessDiv = document.getElementById(\"success\");\n sucessDiv.classList.remove(\"success-hide\");\n sucessDiv.classList.add(\"success-alert\");\n return true;\n }\n}", "function validation(form) {\n function isEmail(email) {\n return /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/.test(\n email\n );\n }\n\n function isPostCode(postal) {\n if (\n /^[ABCEGHJKLMNPRSTVXY]\\d[ABCEGHJKLMNPRSTVWXYZ]( )?\\d[ABCEGHJKLMNPRSTVWXYZ]\\d$/i.test(\n postal\n ) ||\n /^\\d{5}$|^\\d{5}-\\d{4}$/.test(postal)\n )\n return true;\n else return false;\n }\n\n function isPhone(phone) {\n if (/^\\d{10}$/.test(phone)) return true;\n else return false;\n }\n\n function isPassword(password) {\n // Input Password and Submit [7 to 15 characters which contain only characters, numeric digits, underscore and first character must be a letter]</h2\n if (/^[A-Za-z]\\w{7,14}$/.test(password)) {\n return true;\n } else {\n return false;\n }\n }\n\n let isError = false;\n let password = '';\n\n validationFields.forEach((field) => {\n const isRequired =\n [\n 'firstName',\n 'LastName',\n 'email',\n 'address',\n 'postalCode',\n 'password',\n 'conPassword',\n ].indexOf(field) != -1;\n\n if (isRequired) {\n const item = document.querySelector('#' + field);\n\n if (item) {\n const value = item.value.trim();\n if (value === '') {\n setErrorFor(item, field + ' cannot be blank!');\n isError = true;\n } else if (field === 'email' && !isEmail(value)) {\n setErrorFor(item, 'Invalid Email Address!');\n isError = true;\n } else if (field === 'postalCode' && !isPostCode(value)) {\n setErrorFor(item, 'Invalid Postal Code!');\n isError = true;\n } else if (field === 'phone' && !isPhone(value)) {\n setErrorFor(item, 'Invalid Phone Number!');\n isError = true;\n } else if (field === 'password' && isPassword(value)) {\n setSuccessFor(item);\n password = value;\n } else if (field === 'password' && !isPassword(value)) {\n setErrorFor(\n item,\n ' Minimum 7 and Maximum 15 characters, numeric digits, underscore and first character must be a letter!'\n );\n isError = true;\n password = '';\n } else if (field === 'conPassword' && password !== value) {\n setErrorFor(item, 'Confirmation Password Not Match!');\n isError = true;\n } else {\n setSuccessFor(item);\n }\n }\n }\n });\n\n return isError === false;\n}" ]
[ "0.7129552", "0.69248116", "0.6914516", "0.68146706", "0.680093", "0.6701954", "0.65745425", "0.6408853", "0.63911575", "0.62697077", "0.6230799", "0.6220002", "0.6200124", "0.61972755", "0.6182241", "0.6176631", "0.6169938", "0.61676365", "0.6167057", "0.61466616", "0.61388093", "0.6132019", "0.6116597", "0.6094993", "0.6068049", "0.60608286", "0.6056854", "0.6054969", "0.6052248", "0.60462135", "0.6040499", "0.60123175", "0.6009608", "0.5971351", "0.59642315", "0.5960146", "0.5960118", "0.594503", "0.5942501", "0.5933592", "0.5932843", "0.592882", "0.592555", "0.59027886", "0.5901449", "0.58992255", "0.58927244", "0.5891052", "0.5884319", "0.5876713", "0.58683556", "0.5866963", "0.58669263", "0.58595973", "0.5859433", "0.58473146", "0.58398277", "0.58354515", "0.5833588", "0.5832739", "0.58301556", "0.5828173", "0.5822264", "0.58127546", "0.5810021", "0.5809179", "0.5807915", "0.5806047", "0.58001494", "0.578936", "0.5787782", "0.578381", "0.57825756", "0.5779053", "0.57708585", "0.57641304", "0.5760938", "0.57511747", "0.57483506", "0.57461023", "0.57429415", "0.5742185", "0.57416165", "0.5741104", "0.5722906", "0.5710956", "0.5706925", "0.5702665", "0.569812", "0.5697976", "0.5694434", "0.56929314", "0.56915146", "0.5681912", "0.5681629", "0.5680714", "0.56769806", "0.56680727", "0.566068", "0.5656777", "0.56558734" ]
0.0
-1
validateForm() SUB FUNCTIONS DISPLAY RESULTS FUNCTION Displays results; sends the BMR and TDEE output from calculateResults() back to the user. Fires when user clicks submit form, and inputs are determined valid based on validateForm() Main Function
function displayResults () { if(validateForm()) { // If all inputs are valid, create a user profile to calculate results const user = createUserProfile(); // TDEE Results document.getElementById("tdee-results").innerHTML = "Your TDEE: results"; // BMR Results document.getElementById("bmr-results").innerHTML = "Your BMR: results"; // Input Results var inputResults = ""; inputResults += "Showing results for a "; inputResults += user.get("activity") + " " + user.get("age") + " year old " + user.get("gender") + " who is " + user.get("feet") + " feet " + user.get("inches") + " inch(es) tall and weighs " + user.get("weight") + " pounds."; document.getElementById("input-results").innerHTML = inputResults; } else { document.getElementById("error-message").innerHTML = "Error"; } return; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function CalculateResults()\r\n {\r\n var inputsAllValid;\r\n\r\n // Fetch all input values from the on-screen form.\r\n\r\n inputsAllValid = FetchInputValues();\r\n\r\n // If the fetched input values are all valid...\r\n\r\n if (inputsAllValid)\r\n {\r\n // Do the natural gas pressure loss calculation.\r\n\r\n DoCalculation();\r\n\r\n // Display the results of the calculation.\r\n\r\n DisplayResults();\r\n }\r\n }", "function calculateResults() {\n //UI vars\n const height = document.querySelector('#height').value;\n const weight = document.querySelector('#weight').value;\n const age = document.querySelector('#age').value;\n const sex = document.querySelector('#sex').value;\n const activity = document.querySelector('#activity').value;\n\n //Output vars\n const dailyCalorieRequirements = document.querySelector('#dailyCalorie');\n const daliyProteinIntake = document.querySelector('#dailyProtein');\n const dailyCarbsIntake = document.querySelector('#dailyCarbs');\n const dailyFatIntake = document.querySelector('#dailyFat');\n\n //calculating basal metabolic rate\n const bmr = ((10 * weight) + (6.25 * height) - (5 * age)) + parseFloat(sex);\n \n if (isFinite(bmr)) {\n let dailyCalorie = bmr * parseFloat(activity);\n dailyCalorieRequirements.value = Math.round(dailyCalorie);\n daliyProteinIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 25, 'p');\n dailyCarbsIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 35, 'c');\n dailyFatIntake.value = getAmountOfMacronutrient(dailyCalorieRequirements.value, 40, 'f');\n displayResults();\n hideLoading();\n displayMacrosRatioChart();\n } else {\n showError('Please check your numbers');\n }\n}", "function submitResults() {\n\tif ( conditionsMet() ) {\n\t\tdisplayForm(\"#form\");\n\t}\n\telse {\n\t\talert(\"One of the sets is empty! Each set must contain at least one number.\");\n\t}\n}", "function btnCalculator() {\n const txtMonthlyPaymentEl = document.getElementById('txtMonthlyPayment');\n const txtYearlyRateEl = document.getElementById('txtYearlyRate');\n const listNumOfYearsEl = document.getElementById('listNumOfYears');\n const errorLogEl = document.getElementById('errorLog');\n const futureValueEl = document.getElementById('futureValue');\n\n // Determine form values provided by user\n const monthlyPayment = txtMonthlyPaymentEl ? txtMonthlyPaymentEl.value : 0;\n const rate = txtYearlyRateEl ? txtYearlyRateEl.value : 0;\n const years = listNumOfYearsEl ? listNumOfYearsEl.value : 0;\n\n // --- Form Validation ---\n\n const monthlyPaymentValidator = new Validator('Monthly Payment', monthlyPayment);\n monthlyPaymentValidator.addRequiredField();\n monthlyPaymentValidator.addRequiredFloatField();\n monthlyPaymentValidator.addFloatMinField(100);\n\n const rateValidator = new Validator('Interest Rate', rate);\n rateValidator.addRequiredField();\n rateValidator.addRequiredFloatField();\n rateValidator.addFloatMaxField(100);\n\n const errorLog = [];\n const monthlyPaymentValidation = monthlyPaymentValidator.validate();\n const rateValidation = rateValidator.validate();\n\n // --- Render Results ---\n\n if (monthlyPaymentValidation && rateValidation) {\n // Send future value calculation to client display\n errorLogEl.innerHTML = '';\n const futureValue = FinanceCalculator.calculateFutureValue(monthlyPayment, rate, years);\n if (futureValueEl) futureValueEl.innerHTML = FinanceCalculator.convertToCurrency(futureValue);\n } else {\n // Send error messages to client display\n if (futureValueEl) futureValueEl.innerHTML = '';\n if (!monthlyPaymentValidation) {\n for (const message of monthlyPaymentValidator.messages) {\n errorLog.push(message);\n }\n }\n if (!rateValidation) {\n for (const message of rateValidator.messages) {\n errorLog.push(message);\n }\n }\n let errorLogMessage = '<ul>';\n for (const msg of errorLog) {\n errorLogMessage += `<li>${msg}</li>`;\n }\n errorLogMessage += '</ul>';\n errorLogEl.innerHTML = errorLogMessage;\n }\n}", "function getFormValuesAndDisplayResults() {\n}", "function getFormValuesAndDisplayResults() {\n\tgetFormValues();\n\tlet monthlyPayment = calcMonthlyPayment(principle, loanYears, interest);\n\tdocument.getElementById(\"calc-monthly-payment\").innerHTML = monthlyPayment;\n}", "function validateSubmitResults() {\n\tconsole.log(\"Calling from validator\");\n\tvar validated; \n // Select only the inputs that have a parent with a required class\n var required_fields = $('.required');\n // Check if the required fields are filled in\n \trequired_fields.each(function(){\n \t\t// Determite what type of input it is, and display appropriate alert message\n\t\tvar field, msg_string;\n \tif( $(this).hasClass('checkbox_container') || $(this).hasClass('radio_container') ){\n \t\tfield = $(this).find('input:checked');\n \t\tmsg_string = \"Please select an option\";\n \t}else{\n \t\tfield = $(this).find('input:text, textarea');\n \t\tmsg_string = \"Please fill in the field\";\n \t} \n\t\t// For the checkbox/radio check the lenght of selected inputs,\n\t\t// at least 1 needs to be selected for it to validate \n\t\t// And for the text, check that the value is not an empty string\n \t\tif( (field.length <= 0) || !field.val() ){\n \t\t\tconsole.log(\"Field length: \" + field.length);\n \t\t\t$(this).addClass('alert alert-warning');\n \t\t\tvar msg = addParagraph(msg_string, \"validator-msg text-danger\");\n \t\t\t// Check if there is already an alert message class, \n \t\t\t// so that there wouldn't be duplicates\n\t\t\tif( $(this).find('p.validator-msg').length == 0 ){\n \t$(this).find('.section-title').before(msg);\n }\n validated = false;\n \t\t}\n \t\telse{\n \t\t\t// Remove the alert classes and message\n \t\t\t$(this).find('p.validator-msg').detach();\n $(this).removeClass('alert-warning').removeClass('alert'); \n validated = true;\n \t\t}\n \t\t// Sanitize the inputs values\n \t\tif( validated ){\n \t\t\tvar answer = sanitizeString(field.val());\n \t\t\tfield.val(answer);\n \t\t}\n \t});\n\n\treturn validated;\n}", "function processForm() {\n // validate elevation\n if ($('#mtnElevation').val() < 4003 || $('#mtnElevation').val() > 6288) {\n $('#alertMsg').html('Elevation must be between 4,003 and 6,288 feet.');\n $('#mtnElevation').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate effort\n if ($('#mtnEffort').val() === '') {\n $('#alertMsg').html('Please select an effort.');\n $('#mtnEffort').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate image\n if ($('#mtnImage').val() === '') {\n $('#alertMsg').html('Please enter an image name.');\n $('#mtnImage').focus();\n $('#alertMsg').show();\n return false;\n }\n\n // validate lat / lng\n // Note: Can break into Lat and Lgn checks, and place cursor as needed\n var regex = /^([-+]?)([\\d]{1,2})(((\\.)(\\d+)(,)))(\\s*)(([-+]?)([\\d]{1,3})((\\.)(\\d+))?)$/;\n var latLng = `${$('#mtnLat').val()},${$('#mtnLng').val()}`;\n if (! regex.test(latLng)) {\n $('#alertMsg').html('Latitude and Longitude must be numeric.');\n $('#alertMsg').show();\n return false;\n }\n\n // Form is valid\n $('#alertMsg').html('');\n $('#alertMsg').hide();\n\n return true;\n }", "function calculateForm() {\n setFields();\n\n if (formIsValid()) {\n var loan_amount, interest, monthly_interest, years, months,\n payment, paid, interest_paid;\n\n loan_amount = total_loan_box.value;\n interest = interest_rate_box.value;\n\n if (interest >= 1) interest = interest / 100;\n\n monthly_interest = interest / 12;\n years = loan_term_box.value;\n months = years * 12;\n\n number_payments_box.value = months;\n\n payment = Math.floor((loan_amount * monthly_interest) / (1 - Math.pow((1 + monthly_interest), (-1 * months))) * 100) / 100;\n payment_amount_box.value = payment.toFixed(2);\n\n paid = payment * months;\n total_paid_box.value = paid.toFixed(2);\n\n interest_paid = paid - loan_amount;\n interest_paid_box.value = interest_paid.toFixed(2);\n\n return true;\n }\n\n focus_box.select();\n return false;\n}", "function showResult(event) {\n event.preventDefault();\n const fullName = getFullName();\n const email = getEmail();\n const house = getHouse();\n const family = getFamily();\n const content = getContent();\n const rate = getRate();\n const comment = getComment();\n deleteFormContent();\n const form = document.getElementById('evaluation-form');\n form.innerHTML = `${fullName}${email}${house}${family}${content}${rate}${comment}`;\n}", "function calculate() {\n if (validateInputs()) {\n if ($age.val() > 110) {\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Invalid Age</span>\");\n } else if (($weight.val() > 600 && imperial) || ($weight.val() > 270 && !imperial)) {\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Invalid Weight</span>\");\n } else if (imperial) { // calculation if imperial units\n if ($heightInputIn.val() > 12) {\n inchesConvert();\n }\n var BMR = Math.round(calculateBMR());\n var TDEE = Math.round(calculateBMR() * 1.2);\n var BMI = calculateBMI();\n $calcResultsBox.removeClass(\"hidden\").html(\n \"To lose \" + $slider.slider(\"value\") + \" lb per week, you would need to eat \" + Math.round((TDEE - 500 * $slider.slider(\"value\"))) + \"* kcal per day (not including exercise).<br/><br/>BMR: \" + BMR + \" kcal<br/>TDEE: \" + TDEE + \" kcal<br/>BMI: \" + BMI + \"</td><br/><br/>* Eating less than 1200 kcal daily is not recommended.\");\n } else {\n // calculation if metric units\n var BMR = Math.round(calculateBMR());\n var TDEE = Math.round(calculateBMR() * 1.2);\n var BMI = calculateBMI();\n $calcResultsBox.removeClass(\"hidden\").html(\n \"To lose \" + $slider.slider(\"value\") + \" kg per week, you would need to eat \" + Math.round((TDEE - 1102 * $slider.slider(\"value\"))) + \"* kcal per day (not including exercise).<br/><br/>BMR: \" + BMR + \" kcal<br/>TDEE: \" + TDEE + \" kcal<br/>BMI: \" + BMI + \"</td><br/><br/>* Eating less than 1200 kcal daily is not recommended.\");\n }\n } else\n $calcResultsBox.removeClass(\"hidden\").html(\"<span style='color:red'>Please fill in all fields.</span>\");\n }", "refreshResult() {\r\n if(this.validateForm()) {\r\n let bill = +(this.getInputVal(this.inputBill));\r\n let people = +(this.getInputVal(this.inputPeople));\r\n let perc = +(this.getInputVal(this.inputCustom) || \r\n this.percentageBtns.filter(btn => btn.classList.contains(\"active\"))[0].value);\r\n\r\n if(people === 0) return;\r\n\r\n this.errorStyles(\"remove\");\r\n let tip = (bill * (perc / 100));\r\n let tipPerPerson = (tip / people).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\r\n let total = ((bill + tip) / people).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});\r\n\r\n this.displayResult(tipPerPerson, total);\r\n }\r\n else {\r\n return ;\r\n }\r\n }", "function processForm(evt) {\n evt.preventDefault();\n let sideA = +document.getElementById(\"side-a\").value;\n let sideB = +document.getElementById(\"side-b\").value;\n let resultsMessages = getResultsFromSideLengths(sideA,sideB);\n\n document.getElementById(\"a-msg\").innerHTML = resultsMessages.aMsg;\n document.getElementById(\"b-msg\").innerHTML = resultsMessages.bMsg;\n document.getElementById(\"msg\").innerHTML = resultsMessages.msg;\n}", "function validate() {\n // Purpose - First, errors are cleared. Then, input is verified as valid by making sure it is a positive number. If the input is not valid an error class name is attached to the parent element of the Starting Bet input field. (This error may be cleared by the clearErr() function on the next call. See clearErr() function below.) If input is valid, next the playUntilBroke function is called to evaluate the outcome of a Lucky Sevens rule set as described here https://lms.thesoftwareguild.com/courses/281/pages/code-practice-lucky-sevens?module_item_id=35721.\n \n clearErr();\n var startingBet = parseInt(document.forms[\"startingBetForm\"][\"startingBet\"].value, 10);\n\n if(isNaN(startingBet) || startingBet <= 0) {\n alert(\"In order to play the game, you must have a starting bet that is greater than $0.\");\n document.forms[\"startingBetForm\"][\"startingBet\"].parentElement.className = \"form-inline has-error\";\n document.forms[\"startingBetForm\"][\"startingBet\"].focus();\n return false;\n }\n\n playUntilBroke(startingBet);\n\n return false;\n // Returning false to the form that calls this function prevents the form from being submitted and the page from being updated. This in turn allows us to view the results title and table.\n}", "function calculateLoan(e) {\n // Check for number of input errors, if none then run the calculating functions\n if (checkErrors() > 0) {\n stop();\n } else {\n // Hide the results each time the button is pressed\n document.getElementById(\"results\").style.display = \"none\";\n // Show the loading gif\n document.getElementById(\"loading\").style.display = \"block\";\n // Stop the loading gif after 3 seconds\n setTimeout(loadGIF, 2000);\n // Run the functions that calculate the results\n calculateMonthlyPayment();\n calculateTotalPayment();\n calculateTotalInterest();\n // Delay results by 3 seconds\n setTimeout(showResults, 2000);\n // document.getElementById(\"results\").style.display = \"block\";\n }\n\n // Prevent submit and refresh (default behaviour of submit form event)\n e.preventDefault();\n}", "function processForm(){\t\n\t//set an error message variable (start as an empty string)\n\tvar msg = \"\";\n\t\n\t//validate the name! (call a function to do this)\n\tvar name = checkName();\n\t//check for a return...if it is returned, set error variable to false\n\tif(name == true){\n\t\tmsg\t= false;\n\t}\t\n\t\n\t//validate email!\n\tvar email = checkEmail();\n\t//check for a return...\n\tif(email == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//validate select menus\n\t//this is easier if we use separate functions, because here we only have to check for false (if they have entered something correct, no reason to change it). modifying the original functions to work both on submit and on change would be harder, though certainly possible. something for them to consider in the future.\n\tvar charType = theForm.charType;\n\t\n\tif(charType.options[charType.selectedIndex].value == \"X\"){\n\t\tcharType.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a character.</span>';\n\t\tmsg = false;\n\t}\n\t\n\tvar job = theForm.charJob;\n\t\n\tif(job.options[job.selectedIndex].value == \"X\"){\n\t\tjob.parentNode.childNodes[5].innerHTML = '<span class=\"error\">Please choose a job.</span>';\n\t\tmsg = false;\n\t}\n\t\n\t\n\t/*validate checkbox*/\n\tvar spam = checkChecker();\n\tif(spam == true){\n\t\tmsg = false;\t\n\t}\n\t\n\t//finally, check for errors\n\tif(msg == false){\n\t\t//return false, normally, but we are always returning false\tfor testing purposes\n\t}else{\n\t\t//submit form\n\t}\n\t//alert(msg);\n\t//prevent form from submitting\n\treturn false;\n}", "function calculateResults() {\n document.getElementById('answer').style.display = 'block';\n\n document.getElementById('loading').style.display = 'none';\n\n document.getElementById('calc').style.display = 'none';\n\n inputProgress.style.display = 'none';\n progress.style.display = 'none';\n var showTable = document.getElementById('table');\n showTable.classList.remove('invisible');\n\n caclRiskProfile();\n}", "function validateForm()\n{\n // Set textarea value to VTBE contents\n if ( typeof(finalizeEditors) == \"function\" )\n {\n finalizeEditors();\n }\n\n var ismath = window.api ? true : false; // True if webeq is there\n\n /* Transform equations place holders into html before validation */\n if ( ismath )\n {\n api.setHtml();\n }\n\n if ( skipValidation )\n {\n return true;\n }\n\n /* Validate form */\n var valid = formCheckList.check();\n var i;\n\n /*Check for invalid answers if any present */\n var invalidAnswersArray = [];\n var invAns = window.invalidAnswers;\n if ( typeof( invAns) == 'object' && invAns.length > 0 )\n {\n for ( i = 0; i < invAns.length; ++i )\n {\n invalidAnswersArray.push( invAns[i] );\n }\n }\n invAns = window.invalidAnswersTmp;\n if ( typeof(invAns) == 'object' && invAns.length > 0 )\n {\n for ( i = 0; i < invAns.length; ++i )\n {\n invalidAnswersArray.push( invAns[i] );\n }\n }\n var stringArg = '';\n if ( invalidAnswersArray.length > 0 )\n {\n invalidAnswersArray.sort(numericalArraySortAscending);\n var lastIndex = invalidAnswersArray.length - 1;\n for ( var x = 0; x < invalidAnswersArray.length; x++ )\n {\n stringArg += invalidAnswersArray[x];\n if ( x < lastIndex )\n {\n if ( ( (x+1) % 10 ) === 0 )\n {\n stringArg += \",\\n\";\n }\n else\n {\n stringArg += \",\";\n }\n }\n }\n }\n if ( stringArg !== '' && valid )\n {\n var msgKey;\n if ( !assessment.backtrackProhibited )\n {\n msgKey = 'assessment.incomplete.confirm';\n }\n else\n {\n msgKey = 'assessment.incomplete.confirm.backtrackProhibited';\n }\n if (assessment.isSurvey)\n {\n msgKey = msgKey + \".survey\";\n }\n\n if ( !confirm( JS_RESOURCES.getFormattedString( msgKey, [stringArg] ) ) )\n {\n valid = false; // User decided not to submit\n }\n else\n {\n assessment.userReallyWantsToSubmit = true;\n }\n\n window.invalidAnswersTmp = []; // Clearing up\n }\n\n /* Go back to placeholders if validation failed (valid == false) */\n if ( ismath && !valid )\n {\n api.setMathmlBoxes();\n }\n\n return valid;\n}", "function calculateResults() {\n\ttry {\n\t\tvar x = getUserInput();\n //if user input results in error, the error will be presented on the html.\n //e is the event.\n\t} catch(e) {\n\t\talert(\"Error: \" + e);\n\t\treturn;\n\t}\n //This will keep from displaying the same answer over and over if the calculate\n //button is clicked; without setDefaultText() the calculate button will keep\n //appending the same answer indefinitely.\n\tsetDefaultText();\n\n\tfor (var i = 0; i < resultElements.length; i++) {\n\t\tvar element = resultElements[i];\n //functionName looks for the function attribute in the html\n var functionName = element.getAttribute('function');\n //func invokes the Math function and is defined the function tag\n //accessed by the functionName funtion above\n\t\tvar func = Math[functionName];\n //The results are rendered based on the user input\n\t\tvar result = func(x);\n //The user input is captured here and input is evaluated and the results\n //added to the respective functions in the html - sin/cons/tan/log\n\t\telement.innerText = element.innerText + \" \" + result;\n\n\t}\n\n}", "function calculateResult()\r\n{\r\n\tresults = [resultA, resultB, resultC, resultD];\r\n\tcalculatedResult = resultA;\r\n\t\r\n\tfor (var i = 0; i < results.length; i++) {\r\n\t\tif (calculatedResult < results[i]){\r\n\t\t\tcalculatedResult = results[i];\r\n\t\t}\r\n\t}\r\n\t\r\n\tif (calculatedResult == resultA){\r\n\t\twindow.location.href = \"resultA.html\";\r\n\t} else if (calculatedResult == resultB){\r\n\t\twindow.location.href = \"resultB.html\";\r\n\t} else if (calculatedResult == resultC){\r\n\t\twindow.location.href = \"resultC.html\";\r\n\t} else {\r\n\t\twindow.location.href = \"resultD.html\";\r\n\t}\r\n\t\r\n\t/*\r\n\t\tthis function is called when the submit button is clicked on\r\n\t\t\r\n\t\tthis function puts all of the result variables into a results array. calculatedResult \r\n\t\twill be the the result the user gets, but it starts off as resultA. then the for loop\r\n\t\tgoes throught the results array to see which result variable has the highest score\r\n\t\t\r\n\t\tbased on what the calculatedResult is, that corresponding result page is loaded for\r\n\t\tthe user\r\n\t*/\r\n}", "function calculateResults(){\n// console.log('calculating.....');\n\n// UI variables\n// amount variable\nconst amount = document.getElementById('amount');\n// interest rate variable\nconst interest = document.getElementById('interest');\n// years to pay\nconst years = document.getElementById('years');\n// monthly payment\nconst monthlyPayment = document.getElementById('monthly-payment');\n// total payment\nconst totalPayment = document.getElementById('total-payment');\n// total interest\nconst totalInterest = document.getElementById('total-interest')\n\nconst principal = parseFloat(amount.value);\nconst calculatedInterest = parseFloat(interest.value)/100/12;\nconst calculatedPayments = parseFloat(years.value)*12;\n\n// compute monthly payment\nconst x = Math.pow(1 + calculatedInterest , calculatedPayments);\nconst monthly = (principal*x*calculatedInterest)/(x-1);\n\n\n// hide the loading image\ndocument.getElementById('loading').style.display = 'none'\n\n\nif (isFinite(monthly)){\n\n// show results\ndocument.getElementById('result').style.display = 'block';\n\n// show the reset all button\ndocument.querySelector('div.reset').style.display = 'block'\n\ndocument.querySelector('div.reset input#resetAll').addEventListener('dblclick', resetAll);\n\n monthlyPayment.value = monthly.toFixed(2);\n totalPayment.value = (monthly*calculatedPayments).toFixed(2);\n totalInterest.value = ((monthly*calculatedPayments)-principal).toFixed(2);\n}else {\nshowError('please check your numbers')\n}\n\n}", "function formValidation(){\n var result;\n\n result = textValidation(firstName,fName);\n result = textValidation(middleName,mName) && result;\n result = textValidation(sirName,lName) && result;\n result = numberValidation(unitNum,unitNumber) && result;\n result = numberValidation(StreetNum,stNumber) && result;\n result = textValidation(streetName,stName) && result;\n result = textValidation(city,cityName) && result;\n result = postCodeValidation(postCode,pCode) && result;\n result = phoneValidation(phoneNumber,phoNumber) && result;\n result = userNameValidation(userName,uName) && result;\n result = password1Validation(password1,pWord) && result;\n result = password2Validation(password2,pWordC,password1) && result;\n if (result == false){\n alert(\"Submission Failed\")\n }\n else {\n alert(\"Submission was Successful\")\n }\n return result;\n}", "function processForm()\r\n{\r\n var $repairAgentSet; // boolean used to tell if claim should be processed\r\n var $claimType = $('#claimdetails-claimtype-select').val();\r\n \r\n $errorMessageArray = []; // reset arry for each process of the form\r\n \r\n \r\n // check to make sure at least one product is in the claim before being submitted\r\n if ($quantityProductClaim == 0 )\r\n {\r\n showMessage('Error', 'A product must be in the claim before saving.');\r\n return false;\r\n }\r\n \r\n // check to make sure repair agent has been set if claim status is shipped\r\n // or complete for repair claims\r\n $repairAgentSet = checkRepairAgentSet();\r\n\r\n if ($repairAgentSet == true)\r\n {\r\n $('#claimdetails-repairagentid-input').prop(\"disabled\", false);\r\n }\r\n else\r\n {\r\n return false;\r\n }\r\n \r\n // check inputs to make sure there vaild\r\n if ($claimType == 'Warranty' || $claimType == 'Non-Warranty')\r\n {\r\n checkCustomerInputs();\r\n checkFinailseRepairInputs();\r\n checkRepairAgentInputs();\r\n }\r\n \r\n\r\n // loop through the error array and print to the screen, if errors exist return false\r\n // if no error return true\r\n $arraylength = $errorMessageArray.length;\r\n\r\n // if errors exist - entries in array show error message box and messages\r\n if ($arraylength > 0)\r\n {\r\n var $errorMsgs = \"\";\r\n\r\n // add each error to error msg string\r\n for (i = 0; i < $arraylength; i++)\r\n {\r\n $errorMsgs += \"<h3 class=\\\"error-list\\\">\" + $errorMessageArray[i] + \"</h3> \";\r\n }\r\n\r\n $('#customerclaim-error-container').html($errorMsgs);\r\n $('#customerclaim-error-container').fadeIn(1500);\r\n\r\n // scroll to error box - so it will be seen straight away - animates\r\n $('html, body').animate({\r\n scrollTop: $(\"#customerclaim-error-container\").offset().top\r\n }, 2000);\r\n\r\n return false;\r\n }\r\n else // if no error return true to process the form\r\n {\r\n // on submit make sure inputs are enables so they will be posted\r\n $('#claimdetails-claimtype-select').prop(\"disabled\", false);\r\n $('#claimdetails-supplierid-input').prop(\"disabled\", false);\r\n $('#claimdetails-claimid-input').prop(\"disabled\", false);\r\n \r\n id=\"claimdetails-claimtype-select\"\r\n disableRepairAgentInputs(false);\r\n \r\n return true;\r\n }\r\n}", "function showResults(){\n stopTimer();\n resultDisplay.textContent=\"\";\n content.textContent = \"\";\n queslistEl.innerHTML = \"\";\n var ptag = document.createElement(\"p\");\n ptag.setAttribute(\"class\", \"mt-4\")\n ptag.textContent = \"Completed!!! You secured \" +(score/50)*100 +\" percentage \";\n content.append(ptag);\n var ptag2 = document.createElement(\"p\");\n ptag2.textContent = \"Your final score: \" +score; \n content.append(ptag2);\n\n var form = document.createElement(\"form\");\n var div = document.createElement(\"div\");\n div.setAttribute(\"class\", \"form-group\");\n var label = document.createElement(\"label\");\n label.setAttribute(\"for\", \"initials\");\n label.textContent = \"Your Initials: \";\n label.setAttribute(\"style\", \"margin-right:8px;\");\n input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"text\");\n input.setAttribute(\"id\", \"initials\");\n input.setAttribute(\"class\", \"form-control\");\n input.setAttribute(\"placeholder\",\"JS\");\n input.setAttribute(\"required\",\"true\");\n \n var button = document.createElement(\"button\");\n button.setAttribute(\"type\", \"submit\");\n button.setAttribute(\"class\", \"btn btn-primary\");\n button.setAttribute(\"id\", \"submitBtn\");\n button.textContent = \"Submit\";\n div.append(label);\n div.append(input);\n\n form.append(div);\n form.append(button);\n content.append(form); \n}", "function validateSubmission(form) {\n var alertMsg = \"\"; // Stores the message to display to user indicating which fields are entered incorrectly\n var checkEntry = true; // Is true if all fields are entered correctly, set to false if a field is entered incorrectly\n if (form.name.value == \"\") {\n //checks to see if Name field contains user input\n window.alert(\"No Name entered.\");\n return false;\n }\n if (form.price.value == \"\") {\n //checks to see if Price field contains user input, if not the validate function returns false\n window.alert(\"No Price entered.\");\n return false;\n }\n if (form.long1.value == \"\") {\n //checks to see if Longittude field contains user input, if not the validate function returns false\n window.alert(\"No Longittude entered.\");\n return false;\n }\n if (form.latt1.value == \"\") {\n //checks to see if Lattitude field contains user input, if not the validate function returns false\n window.alert(\"No Lattitude entered.\");\n return false;\n }\n\n if (!validateSpotName(form.name.value)) {\n //checks to see if Name entry is in the appropriate format\n var el = document.getElementsByName(\"name\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Name must be 5 characters long and cannot begin with a space or have consecutive spaces.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"name\")[0].style.backgroundColor = \"white\";\n }\n if (\n !validateDescription(form.description.value) &&\n form.description.value != \"\"\n ) {\n //checks to see if Description entry is in the appropriate format\n var el = document.getElementsByName(\"description\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += \"Description must be less than 300 characters.\\n\"; //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n checkEntry = false;\n } else {\n document.getElementsByName(\"description\")[0].style.backgroundColor =\n \"white\";\n }\n if (!validatePrice(form.price.value)) {\n //checks to see if Price entry is in the appropriate format\n var el = document.getElementsByName(\"price\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Price must contain only digits, a single decimal point and up to 2 digits following the decimal point.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"price\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.long1.value)) {\n //checks to see if Longittude entry is in the appropriate format\n var el = document.getElementsByName(\"long1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Longittude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"long1\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.latt1.value)) {\n //checks to see if Lattitude entry is in the appropriate format\n var el = document.getElementsByName(\"latt1\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Lattitude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"latt1\")[0].style.backgroundColor = \"white\";\n }\n if (!checkEntry) {\n //if any of the input fields have an entry in an incorrect format\n window.alert(alertMsg); //displays an error message for each incorrect field to user\n return false; //the validate function returns fa;se\n }\n\n return true; //All input fields contain values in the correct format so the validate function returns true\n}", "function f_submit()\n{\n var message = \"\";\n for(var i=0 ; i < this.elements.length ; i++) {\n\tif ( this.elements[i].validationset ) {\n\t var txt = this.elements[i].validationset.run();\n\t if ( txt.length > 0 ) {\n\t\tif ( message.length > 0 ) {\n\t\t message += \"\\n\";\n\t\t}\n\t\tmessage += txt;\n\t }\n\t}\n }\n if(this.uservalidator) {\n\tstr =\" var ret = \"+this.uservalidator+\"()\";\n\teval(str);\n\tif ( ret.length > 0 ) {\n\t if ( message.length > 0 ) {\n\t\tmessage += \"\\n\";\n\t }\n\t message += txt;\n\t}\n }\n if ( message.length > 0 ) {\n\talert(\"Input Validation Errors Occurred:\\n\\n\" + message);\n\treturn false;\n } else {\n\treturn true;\n }\n}", "function formValidation() {\n //* If validation of email fails, add the warning class to email input and set the display of warning message to inline.\n if (!validation.isEmailValid(email.value)) {\n email.classList.add(\"warning\");\n email.nextElementSibling.style.display = \"inline\";\n }\n //* If validation of name fails, add the warning class to name input and set the display of warning message to inline.\n if (!validation.isNameValid(name.value)) {\n name.classList.add(\"warning\");\n name.nextElementSibling.style.display = \"inline\";\n }\n /*\n * If validation of message fails, add the warning class to message text area and set the display of warning\n * message to inline\n */\n if (!validation.isMessageValid(message.value)) {\n message.classList.add(\"warning\");\n message.nextElementSibling.style.display = \"inline\";\n }\n /*\n *If validation of title fails, add the warning class to title input and set the display of warning\n *message to inline\n */\n\n if (!validation.isTitleValid(title.value)) {\n title.classList.add(\"warning\");\n title.nextElementSibling.style.display = \"inline\";\n }\n if (\n validation.isEmailValid(email.value) &&\n validation.isNameValid(name.value) &&\n validation.isTitleValid(title.valid) &&\n validation.isMessageValid(message.value)\n ) {\n return true;\n } else return false;\n}", "function process() \n{\n\t//Read parameters\n\tvar theform = document.theform;\n\n\touttype = 0;\n\tif (theform.outtype[1].checked) outtype = 1;\n\tif (theform.outtype[2].checked) outtype = 2;\n\n\tprintRules = true; //theform.report.checked;\n\tshowDiff = theform.showdiff.checked;\n\trewout = theform.rewout.checked;\n \n // flush all arrays\n all_rules = [];\n all_rewrites = [];\n all_categories = [];\n applied_rules = {};\n \n\t// Stuff we can do once\n\ts = readStuff();\n\n\t// If that went OK, apply the rules\n\tif (s.length == 0) {\n\n\t\tDoWords();\n\t}\n \n // now, check the goodness of fit\n var goodness = compareAO();\n s += '</li><li>Correct conversions: '+goodness[0] + ' from '+goodness[4] + ' ('+goodness[2]+'%)';\n s += '</li><li>Wrong conversions: '+goodness[1] + ' from '+goodness[4] + ' ('+goodness[3]+'%)';\n s += '</li></ul>';\n if(goodness[2] > 50)\n {\n s += '<span style=\"color:red;font-weight:bold;\">Great, the rules you defined already explain more than half of all words!</span>';\n }\n else\n {\n s += '<span style=\"color:red;font-weight:bold;\">Well, less than half of all words can be explained. Maybe you should try a bit harder...</span>';\n }\n\n // insert the quality of the rules\n s += '<h3>Rule Evaluation</h3><ul>';\n for(rule in applied_rules)\n {\n s += '<li style=\"list-style:circle\"><code>\"'+rule+'\"</code> applies to '+applied_rules[rule]+' words.</li>';\n }\n s += '</ul>';\n\n\t// Set the output field\n\tdocument.getElementById(\"mytext\").innerHTML = s;\n \n}", "function processForm($btn, callback){\n\t// get all the inputs into an array.\n\tvar $form = $btn.parents(\"form\");\n var $inputs = $form.find(':input');\n var $selects = $form.find('select');\n var $textareas = $form.find('textarea');\n var validCheckAmount = 0;\n\n // get an associative array of just the values.\n var data = {};\n if($form.attr('name') == \"/medicijnbeheer/create\"){\n\t data[\"bnf_percentage_id\"] = new Array();\n\t data[\"bnf_value\"] = new Array();\n\t data[\"chem_bonding_id\"] = new Array();\n\t data[\"med_ki_val_id\"] = new Array();\n }\n \n $inputs.each(function() {\n \t\tif ($(this).hasClass(\"valCheckString\")) {\n\t\t\t\tif (!validateString($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckDate\")){\n\t\t\t\tif (!validateDate($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckEmpty\")){\n\t\t\t\tif (!validateInputEmpty($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckEmailAdmin\")){\n\t\t\t\tif (!validateEmailAdmin($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}else if($(this).hasClass(\"valCheckStringAdmin\")){\n\t\t\t\tif (!validateStringAdmin($(this))) {\n\t\t\t\t\t\tvalidCheckAmount ++;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n \t\tif($(this).attr('type')==\"radio\"){\n \t\t\tif($(this).is(':checked'))\n \t\t\t\tdata[this.name] = $(this).val();\n \t\t}else if($(this).attr('name').indexOf(\"bnf_\") > -1){\n \t\t\tdata.bnf_percentage_id.push($(this).attr('id'));\n \t\t\tdata.bnf_value.push($(this).val());\n \t\t}else if($(this).attr('class')!=\"no_process\"){\n \t\t\tdata[this.name] = $(this).val();\n \t\t}\n });\n \n //check the select boxes for their values\n $selects.each(function(){\n \t//the med form has to be treated a little different\n \tif(this.name.indexOf(\"neuro_\") > -1){\n \t\tdata.chem_bonding_id.push($(this).attr('id'));\n \t\tdata.med_ki_val_id.push($(this).find('option:selected').val());\n \t}else{\n \t\tdata[this.name] = $(this).find('option:selected').val();\n \t}\n });\n \n $textareas.each(function(){\n \tdata[this.name] = $(this).val();\n });\n \n if(validCheckAmount == 0){\n\t //the form should have the path as name attribute\n\t var path = $form.attr(\"name\");\n\t //send the data to the database and if successful, show the new patient's page.\n\t callWebservice(data, path, callback);\n }else{\n \tcallback(false);\n }\n}", "function validateAndSubmit() {\r\n var isValid = false;\r\n isValid = validateForm();\r\n if (isValid == true) {\r\n disableButtons() // make sure you can only press the submit button once\r\n document.getElementById('evaluationForm').submit();\r\n }\r\n }", "function validateForm(){\n\t\n\tvar boo1 = validateLabPerson();\n\tvar boo2 = validateBioPerson();\n\tvar boo3 = validatePI();\n\tvar boo4 = validateBillTo();\n\tvar boo5 = validateRunType();\n\n\tvar boo6 = validateAllTables();\n//\tvar boo6 = true;\n\n\tvar boo7 = validateDate();\n\tvar boo8 = validateIAccept();\n\n\tvar boo9 = validateConcentrationUnit();\n\tvar boo10 = validateTubesAndLanes();\n\t\n//\talert(\"boo1 = \" + boo1 + \" boo2 = \" + boo2 + \" boo3 = \" + boo3 + \" boo4 = \" + boo4 +\" boo5 = \" + boo5 +\" boo6 = \" + boo6 + \" boo7 = \" + boo7 + \" boo8 = \" + boo8 + \" boo9 = \" + boo9 + \" boo10 = \" + boo10);\n\tif (boo1 && boo2 && boo3 && boo4 && boo5 && boo6 && boo7 && boo8 && boo9 && boo10){\t\n//\tif(validateLabPerson() && validateBioPerson() && validatePI() && validateBillTo() && validateRunType() && validateTable()){\n\t\t//insert fields used to generate csv\n\t\tinsertTableSize();\t\t\t\t\t// insert size of all table - used when generating csv file\n\t\tgenerateOrderNoteID();\t\t\t\t// insert orderNoteID\n\t\taddPI2TubeTag();\t\t\t\t\t// indsæt \"de tre tegn\" (fra PI) i tubetaggen.\n\t\tsetVersion();\t\t\t\t\t\t// insert the version number in the hidden field.\n\t\treturn true;\n\t} else {\n\t\treturn false;\n\t}\n\t\n\treturn false;\n}", "function evaluateForm(submittedForm) {\n var formValid = true;\n if (submittedForm.store.value == \"\") {\n submittedForm.store.setAttribute(\"class\", \"required\");\n formValid = false;\n }\n if (submittedForm.min.value == \"\") {\n submittedForm.min.setAttribute(\"class\", \"required\");\n formValid = false;\n }\n if (submittedForm.max.value == \"\") {\n submittedForm.max.setAttribute(\"class\", \"required\");\n formValid = false;\n }\n if (submittedForm.avg.value == \"\") {\n submittedForm.avg.setAttribute(\"class\", \"required\");\n formValid = false;\n }\n\n var newStore = submittedForm.store.value;\n var min = parseInt(submittedForm.min.value);\n var max = parseInt(submittedForm.max.value);\n var avg = parseInt(submittedForm.avg.value);\n var storeID = newStore;\n\n if (formValid) {\n console.log(\"tableworks\");\n var displayData = document.getElementById(\"tableSample\");\n cookieAdd.push(new cookieStand(newStore, min, max, avg, 8, storeID));\n cookieAdd[cookieAdd.length-1].addData();\n }\n}", "function results() {\n const high = [\"Great job!\", \"imgs/high.gif\", \"woman waking up happy\"];\n const low = [\"Take a nap and try again\", \"imgs/low.gif\", \"unhappy man\"];\n if (currentScore >= 5) {\n final = high;\n } else {\n final = low;\n }\n return finalResults();\n\n //this function renders the final form, which will display the users results\n function finalResults() {\n return (finalScore = $(\".display\").html(`\n <form class=\"finalForm\">\n <section class=\"quiz-bg\">\n <fieldset class=\"finalForm\">\n <legend class=\"zzz\">zZz</legend>\n <h2 class=\"results-text\">${final[0]}</h2><br>\n <img src=\"${final[1]}\" alt=\"${final[2]}\" class=\"reactions\"> \n <h2 class=\"results-text\">Your score is:<br>${currentScore}/7!</h2>\n <br>\n <button type=\"button\" class=\"restart\">Restart Quiz</button>\n </fieldset>\n </section>\n </form> \n `));\n }\n}", "function displayFinalResult(result){\n document.getElementById(\"inputs\").innerHTML = result;\n}", "function verify_result() {\n grid_end_time = Date.now();\n trial.grid_rt = grid_end_time - grid_start_time;\n\n document.getElementById(\"Verify_Test\").disabled = true;\n var index, tile_value, num_wrong=0;\n\n // count how many of user_input are hits, misses, false alarms\n // var hits=0, false_alarms=0, misses=0;\n for (var i = 0; i < user_input_tile_ids.length; i++) {\n tile_value = Number(user_input_tile_ids[i]);\n index = generated_tile_ids.indexOf(tile_value);\n\n if (index < 0) {\n trial.false_alarms += 1;\n } else {\n trial.hits += 1;\n }\n }\n trial.misses = generated_tile_ids.length - trial.hits;\n\n num_wrong = Math.max(trial.misses, trial.false_alarms);\n if (num_wrong == 0) {\n verdict = 'Right';\n change_score(1);\n } else if (num_wrong == 1) {\n verdict = 'Almost';\n change_score(0.5);\n } else {\n verdict = 'Not Quite';\n change_score(0);\n }\n\n ////////// display Right Almost or Wrong\n // purge everything except input_verdict\n // if (trial.cognitive_loading) {\n // jsPsych.pluginAPI.setTimeout(function() {\n // display_element.querySelector('#debriefing').style.display = 'none';\n // }, 0);\n jsPsych.pluginAPI.setTimeout(function() {\n display_element.querySelector('#board').style.display = 'none';\n }, 0);\n jsPsych.pluginAPI.setTimeout(function() {\n display_element.querySelector('#board-grid-text').style.display = 'none';\n }, 0);\n jsPsych.pluginAPI.setTimeout(function() {\n display_element.querySelector('#Verify_Test').style.display = 'none';\n }, 0);\n // jsPsych.pluginAPI.setTimeout(function() {\n // display_element.querySelector('#jspsych-html-button-response-prompt').style.display = 'none';\n // }, 0);\n // jsPsych.pluginAPI.setTimeout(function() {\n // display_element.querySelector('#jspsych-html-button-response-rating').style.display = 'none';\n // }, 0);\n // jsPsych.pluginAPI.setTimeout(function() {\n // display_element.querySelector('#verdict').style.display = 'block';\n // }, 0);\n // }\n //\n document.getElementById('input_verdict').innerHTML = verdict ;//+ \"<br/>score: \" + num_correct + \"<br/>num_total: \" + num_total;\n\n jsPsych.pluginAPI.setTimeout(end_trial, 1000); //verdict_feedback_time\n }", "function submission() {\n\tvalidateHouseNumber();\n\tvalidateStreetName();\n\tvalidateZipCode();\n\tvalidatePhoneNumber();\n\tvalidateFirstName();\n\tvalidateLastName();\n\tvalidateCardNumber();\n\tvalidateExpiryDate();\n\tvalidateCvv();\n\tvar errorString = document.getElementById(p1).innerHTML + document.getElementById(p2).innerHTML + quantityErrorString();\n\terrorString = errorString.replace(/<br>/g,\"\\n\");\n\tif(errorString.length > 0 ) {\n\t\twindow.alert(\"Please correct these errors\\n\" + errorString);\n\t} else if (calculateTotal() == 0) {\n\t\twindow.alert(\"Choose atleast one item\");\n\t}\n\telse {\n\t\tclearInterval(interval);\n\t document.getElementById(\"bd\").innerHTML=\"<p>Order Successfully placed</p>\";\n\t}\n}", "function showResults() {\r\n // make sure the calculation is correct.\r\n step = 6;\r\n calculateCompletion();\r\n previousAction = actions.activityTaxStep;\r\n nextAction = \"\";\r\n\r\n if (parseboolean(registrations.isTFN)) {\r\n $('#resultTable tr:last').after(getResult(\"Tax File Number (TFN)\", \"tfn\", true, \"\", \"Free\", 1));\r\n }\r\n if (parseboolean(registrations.isCompany)) {\r\n $('#resultTable tr:last').after(getResult(\"Company\", \"co\", true, \"\", \"up to $463 for 1 year\", 2));\r\n }\r\n if (parseboolean(registrations.isBusinessName)) {\r\n $('#resultTable tr:last').after(getResult(\"Business name\", \"bn\", true, \"\", \"$34 for 1 year or $79 for 3 years\", 3));\r\n }\r\n if (parseboolean(registrations.isPAYG)) {\r\n $('#resultTable tr:last').after(getResult(\"Pay As You Go (PAYG) Withholding\", \"payg\", true, \"\", \"Free\", 4));\r\n }\r\n if (parseboolean(registrations.isFBT)) {\r\n $('#resultTable tr:last').after(getResult(\"Fringe Benefits Tax (FBT)\", \"fbt\", true, \"\", \"Free\", 5));\r\n }\r\n var needGST = (parseboolean(applicationType.taxi) || parseboolean(applicationType.turnOver75k) || parseboolean(applicationType.limo));\r\n if (needGST) {\r\n $('#resultTable tr:last').after(getResult(\"Goods &amp; Services Tax (GST)\", \"gst\", true, \"\", \"Free\", 6));\r\n }\r\n if (parseboolean(registrations.isLCT) && needGST) {\r\n $('#resultTable tr:last').after(getResult(\"Luxury Car Tax (LCT)\", \"lct\", true, \"\", \"Free\", 7));\r\n }\r\n if (parseboolean(registrations.isFTC) && needGST) {\r\n $('#resultTable tr:last').after(getResult(\"Fuel Tax Credits (FTC)\", \"ftc\", true, \"\", \"Free\", 8));\r\n }\r\n if (parseboolean(registrations.isWET) && needGST) {\r\n $('#resultTable tr:last').after(getResult(\"Wine Equalisation Tax (WET)\", \"wet\", true, \"\", \"Free\", 9));\r\n }\r\n if (!needGST) {\r\n $(\"#gstRecommend\").show();\r\n $(\"#ckGstRecommend\").click(function () {\r\n if ($(this).prop('checked')) {\r\n $(\"#lctOptional\").prop('checked', true);\r\n $(\"#wetOptional\").prop('checked', true);\r\n $(\"#ftcOptional\").prop('checked', true);\r\n\r\n }\r\n else {\r\n $(\"#lctOptional\").prop('checked', false);\r\n $(\"#wetOptional\").prop('checked', false);\r\n $(\"#ftcOptional\").prop('checked', false);\r\n }\r\n });\r\n\r\n if (parseboolean(registrations.isLCT)) {\r\n $(\"#lctOptionalRow\").show();\r\n $(\"#lctOptional\").click(function () {\r\n if ($(this).prop('checked')) {\r\n $(\"#ckGstRecommend\").prop('checked', true);\r\n }\r\n });\r\n }\r\n if (parseboolean(registrations.isWET)) {\r\n $(\"#wetOptionalRow\").show();\r\n $(\"#wetOptional\").click(function () {\r\n if ($(this).prop('checked')) {\r\n $(\"#ckGstRecommend\").prop('checked', true);\r\n }\r\n });\r\n }\r\n if (parseboolean(registrations.isFTC)) {\r\n $(\"#ftcOptionalRow\").show();\r\n $(\"#ftcOptional\").click(function () {\r\n if ($(this).prop('checked')) {\r\n $(\"#ckGstRecommend\").prop('checked', true);\r\n }\r\n });\r\n }\r\n }\r\n \r\n setTimeout(showRegistrationsHelpContent, 1);\r\n\r\n}", "function displayResultsField() {\n var celebBirthDate;\n var celebBirthMonth;\n var celebBirthYear;\n var celebName;\n \n // **FOR DEMONSTRATIVE PURPOSES (comment out or delete later)** // \n celebName = \"Starlet O'Hara\";\n celebBirthDate = 13;\n celebBirthMonth = \"May\";\n\n // displays HORIZONTAL RULE to separate search from result:\n $(\"form\").after(\"<hr>\");\n // makes DISPLAY CARD visible:\n $(\"#results\").prop(\"hidden\", false);\n\n // displays name of celebrity with link to IMDb or Wikipedia:\n function displayCelebName() {\n var celebURL;\n \n // **FOR DEMONSTRATIVE PURPOSES (comment out or delete later)** // \n celebURL = \"https://www.dictionary.com/browse/starlet\";\n \n var displayName = \"<a href='\" + celebURL + \"' target='_blank'>\" + celebName + \"</a>\";\n $(\"#celebResult\").html(displayName);\n };\n displayCelebName();\n\n // displays full date of birth (if available):\n function displayDOB() {\n \n // **FOR DEMONSTRATIVE PURPOSES (comment out or delete later)** // \n celebBirthYear = 1996;\n \n var celebDOB = celebBirthDate + \" \" + celebBirthMonth + \" \" + celebBirthYear;\n $(\"#celebDOB\").text(celebDOB);\n }\n displayDOB();\n\n // displays birhplace (if available):\n function displayBirthplace() {\n var celebBirthplace;\n\n // **FOR DEMONSTRATIVE PURPOSES (comment out or delete later)** // \n celebBirthplace = \"Area 51\";\n $(\"#celebBirthplace\").text(celebBirthplace);\n };\n displayBirthplace();\n \n // calculates and displays celebrity's zodiac sign:\n function displayZodiac() {\n // astrological sign variables:\n var aquarius = \"Aquarius <span class='unicodePad'>&#9810;</span>\";\n var aries = \"Aries <span class='unicodePad'>&#9800;</span>\";\n var cancer = \"Cancer <span class='unicodePad'>&#9803;</span>\";\n var capricorn = \"Capricorn <span class='unicodePad'>&#9809;</span>\";\n var gemini = \"Gemini <span class='unicodePad'>&#9802;</span>\";\n var leo = \"Leo <span class='unicodePad'>&#9804;</span>\";\n var libra = \"Libra <span class='unicodePad'>&#9806;</span>\";\n var pisces = \"Pisces <span class='unicodePad'>&#9811;</span>\";\n var sagittarius = \"Sagittarius <span class='unicodePad'>&#9808;</span>\";\n var scorpio = \"Scorpio <span class='unicodePad'>&#9807;</span>\";\n var taurus = \"Taurus <span class='unicodePad'>&#9801;</span>\";\n var virgo = \"Virgo <span class='unicodePad'>&#9805;</span>\";\n // other variables:\n var zodiacDate = celebBirthDate;\n var zodiacMonth = celebBirthMonth;\n var zodiacName;\n\n // determines zodiac sign based on birth date ranges:\n if ((zodiacMonth === \"March\" && zodiacDate >= 21) || (zodiacMonth === \"April\" && zodiacDate < 20)) {\n zodiacName = aries;\n } else if ((zodiacMonth === \"April\" && zodiacDate >= 20) || (zodiacMonth === \"May\" && zodiacDate < 21)){\n zodiacName = taurus;\n } else if ((zodiacMonth === \"May\" && zodiacDate >= 21) || (zodiacMonth === \"June\" && zodiacDate < 21)){\n zodiacName = gemini;\n } else if ((zodiacMonth === \"June\" && zodiacDate >= 21) || (zodiacMonth === \"July\" && zodiacDate < 23)) {\n zodiacName = cancer;\n } else if ((zodiacMonth === \"July\" && zodiacDate >= 23) || (zodiacMonth === \"August\" && zodiacDate < 23)) {\n zodiacName = leo;\n } else if ((zodiacMonth === \"August\" && zodiacDate >= 23) || (zodiacMonth === \"September\" && zodiacDate < 23)) {\n zodiacName = virgo;\n } else if ((zodiacMonth === \"September\" && zodiacDate >= 23) || (zodiacMonth === \"October\" && zodiacDate < 23)) {\n zodiacName = libra;\n } else if ((zodiacMonth === \"October\" && zodiacDate >= 23) || (zodiacMonth === \"November\" && zodiacDate < 22)) {\n zodiacName = scorpio;\n } else if ((zodiacMonth === \"November\" && zodiacDate >= 22) || (zodiacMonth === \"December\" && zodiacDate < 22)) {\n zodiacName = sagittarius;\n } else if ((zodiacMonth === \"December\" && zodiacDate >= 22) || (zodiacMonth === \"January\" && zodiacDate < 20)) {\n zodiacName = capricorn;\n } else if ((zodiacMonth === \"January\" && zodiacDate >= 20) || (zodiacMonth === \"February\" && zodiacDate < 19)) {\n zodiacName = aquarius;\n } else if ((zodiacMonth === \"February\" && zodiacDate >= 19) || (zodiacMonth === \"March\" && zodiacDate < 21)) {\n zodiacName = pisces;\n } else {\n return;\n }\n\n $(\"#celebZodiac\").html(zodiacName);\n };\n displayZodiac();\n \n // if birthday available, displays corresponding birthstone:\n function displayBirthstone() {\n // birthstone variables (adjusts color of PNG image to represent birthstone color):\n var amethyst = \"Amethyst <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, amethyst' class='unicodePad' id='febAmethyst'>\";\n var bloodstone = \"Bloodstone <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, bloodstone' class='unicodePad' id='marBloodstone'>\";\n var diamond = \"Diamond <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, diamond' class='unicodePad' id='aprDiamond'>\";\n var emerald = \"Emerald <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, emerald' class='unicodePad' id='mayEmerald'>\";\n var garnet = \"Garnet <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, garnet' class='unicodePad' id='janGarnet'>\";\n var opal = \"Opal <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, opal' class='unicodePad' id='octOpal'>\";\n var pearl = \"Pearl <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, pearl' class='unicodePad' id='junPearl'>\";\n var peridot = \"Peridot <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, peridot' class='unicodePad' id='augPeridot'>\";\n var ruby = \"Ruby <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, ruby' class='unicodePad' id='julRuby'>\";\n var sapphire = \"Sapphire <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, sapphire' class='unicodePad' id='sepSapphire'>\";\n var topaz = \"Topaz <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, topaz' class='unicodePad' id='novTopaz'>\";\n var turquoise = \"Turquoise <img src='./assets/images/gemstone.png' height='21.5px' alt='celebrity birthstone, turquoise' class='unicodePad' id='decTurquoise'>\";\n // other variables:\n var birthMonth = celebBirthMonth;\n var birthstone;\n\n // determines which gem gets linked to which month:\n if (birthMonth === \"January\") {\n birthstone = garnet;\n } else if (birthMonth === \"February\") {\n birthstone = amethyst;\n } else if (birthMonth === \"March\") {\n birthstone = bloodstone;\n } else if (birthMonth === \"April\") {\n birthstone = diamond;\n } else if (birthMonth === \"May\") {\n birthstone = emerald;\n } else if (birthMonth === \"June\") {\n birthstone = pearl;\n } else if (birthMonth === \"July\") {\n birthstone = ruby;\n } else if (birthMonth === \"August\") {\n birthstone = peridot;\n } else if (birthMonth === \"September\") {\n birthstone = sapphire;\n } else if (birthMonth === \"October\") {\n birthstone = opal;\n } else if (birthMonth === \"November\") {\n birthstone = topaz;\n } else if (birthMonth === \"December\") {\n birthstone = turquoise;\n } else {\n return;\n }\n\n $(\"#celebBirthstone\").html(birthstone);\n };\n displayBirthstone();\n }", "function formInput() {\n\tvar bill = document.getElementById('bill').value;\n\tvar tipPercentage = document.getElementById('tipPercentage').value;\n\tbill = parseFloat(bill);\n\ttipPercentage = parseFloat(tipPercentage);\n\tvar tip = (bill) * (tipPercentage /100);\n\tvar totalBill = bill + bill * (tipPercentage / 100);\n\tvar resultInfo = \"<br /><span style='font-style:italic; font-weight:bold; text-decoration:underline;'>Your Tip Info</span><br /><br />\" \n\t+ \"Total Bill Amount: $\" + bill.toFixed(2) + \"<br />Tip Percentage: \" + tipPercentage.toFixed(2) + \"%\" \n\t+ \"<br />Total Tip: $\" + tip.toFixed(2) + \"<br /><span style='font-weight:bold;'>Total Bill: $\" + totalBill.toFixed(2) + \"</span>\";\n\t\n\tdocument.getElementById('results').innerHTML = resultInfo; // Send the result to the results Div.\n\t\n\tclock(); // Call the clock function.\n}", "function results() {\n selectedAnswers = $(displayTest.find(\"input:checked\"));\n //if user is correct\n if (\n selectedAnswers[0].value === testSetup[currentQuestion - 1].questionAnswer\n ) {\n //add to correct score and display on element\n correct++;\n $(\"#correct\").text(\"Answers right: \" + correct);\n } else {\n //if user is wrong then add to wrong score and display on element\n wrong++;\n $(\"#incorrect\").text(\"Wrong answers: \" + wrong);\n }\n //check to see if the user has reached the end of the test\n if (currentQuestion === 10) {\n //toggle finalize modal at end of test to display score\n $(\"#modalMatch\").modal(\"toggle\");\n $(\"#testScore\").text(\n \"End of test! You scored a \" + (parseFloat(correct) / 10) * 100 + \"%\"\n );\n //show postTest element\n $(\"#postTest\").show();\n $(\"#submitTest\").hide();\n }\n }", "function validateForm(e){\n \n /*\n \n This is the most important part of the code because it shows the errors to the user in a listed div\n \n */\n \n /* Here, I am \"inside\" the HTML in the document and I'm going to add the <li> items according to the errors */\n\t\terror.innerHTML = \"\";\n\t\terrors = [];\n \n //Then I call the functions\n\t\tvalidateName(e);\n\t\tvalidateEmail(e);\n checkTerms(e);\n\t\tvalidateMessage(e);\n \n //This conditional means that if the array I created is empty (meaning there are no errors in the form), it will not show anything and the form will be submitted \n\t\tif(errors.length == 0) {\n\t\t\tform.submit();\n\t\t} else{\n //But if it finds any error, they will be displayed as the result of an array \n\t\t\terror.style.display = \"block\";\n\t\t\tfor (i=0; i<errors.length; i++) {\n\t\t\t\terror.innerHTML += errors[i]; \n\t\t\t}\n\t\t}\n\t\t\n} //End validateForm//", "function processForm() {\n //getting all the cookies numbers of different types from the form //after the form is being submitted\n var small = document.getElementById('treatSmall').value;\n \n var medium = document.getElementById('treatMedium').value;\n \n var large = document.getElementById('treatLarge').value;\n \n \n //to calculate the happiness score\n //to convert string to integer used parseInt\n var happinessScore = (parseInt(1*small) + parseInt(2*medium) + parseInt(3*large));\n console.log(happinessScore);\n \n //now, if the one or more of cookies numbers is not entered or is //not an number print error message\n // if all are good, then give the result for Barley's mood.\n if(!small || !medium || !large || isNaN(small) || isNaN(medium) ||isNaN(large)){\n document.getElementById(\"error\").innerHTML = \"Please enter all valid postive intgers.\";\n }else if(happinessScore < 10) {\n document.getElementById(\"result\").innerHTML = \"sad\";\n }\n else{\n document.getElementById(\"result\").innerHTML = \"happy\";\n }\n return false;\n }", "function showResults() {\r\n $(\"#optimalSolutionPanel\").hide();\r\n \r\n $('#results').show();\r\n experimentComplete();\r\n// enablePlayAgain();\r\n \r\n if (numRoundsWithStar >= 3) {\r\n writeAward(\"No Instruction Needed\");\r\n payAMT(true,0.20); \r\n } else {\r\n payAMT(true,0.0); \r\n }\r\n \r\n// quit();\r\n \r\n}", "function submitForm(){\n var spanObject = document.getElementById(\"productError\");\n spanObject.style.display = \"block\";\n spanObject.innerHTML = \"Success! Total: $\" + calculateTotal();\n}", "function validateScreenTimeGoalSubmission()\n{\n //get all form fields\n var stGoal = document.getElementById(\"screenTimeGoal\").value; \t\t//screen time goal\n \t \n //flag to ensure all data accurate\n var isValid = true;\n \n //ensure screen time goal is submitted\n if(stGoal === \"\" || isNaN(stGoal) || stGoal<=0)\n {\n //show error message and mark input invalid\n document.getElementById(\"st_error\").style.display = \"block\";\n isValid = false;\n }//end if\n \n\telse\n\t{\n\t\tdocument.getElementById(\"st_error\").style.display = \"none\";\n\t}\n return isValid;\n}//close validateScreenTimeGoalSubmission", "function validate_form_goal()\n{\n\t// season (only need to check if season2 is not empty)\n\tbseason = document.createitem.season2.value != \"\";\n\tif (!bseason)\n\t{\n\t\tdocument.createitem.season.value = 0;\n\t}\n\telse\n\t{\n\t\tdocument.createitem.season.value = document.createitem.season1.value + \"/\" + document.createitem.season2.value\n\t}\n\t\t\n\t\t\n\t// At this point, if bok equals true, then the details have been filled correctly\n\t////////////////////////////////////////////////////////////////////////\n\t\n\t// submit form if it has been correctly populated\n\tshow_topscorers(\"div_topscorer\",\"get_topscorer.php\")\n}", "function validationsOk() {\n\n // Validate if in the HTML document exist a form\n if (formExistence.length === 0) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"Form tag doesn't exist in the html document\"\n return;\n }\n\n // Validate the quantity of labels tags are in the document\n if (labelsQuantity.length !== 4) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of label tags in the document\"\n return;\n }\n\n // Validate the quantity of buttons are in the document\n if (buttonsQuantity.length !== 2) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of button tags in the document\"\n return;\n }\n\n // Validate the quantity of inputs tags are in the document\n if (inputsQuantity.length !== 4) {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"red\"\n infoDiv.innerText = \"There aren't the enoght quantity of inputs tags in the document\"\n return;\n }\n\n // Validate if the email input contains text \n if (emailInput.value === \"\" || emailInput.value === null || !isEmail(emailInput.value)) {\n return;\n }\n if (nameInput.value === \"\" || nameInput.value === null) {\n return;\n }\n // Validate if the password input contains text\n if (passwordInput.value === \"\" || passwordInput.value === null) {\n return;\n }\n // Validate if the confirm-password input contains text\n if (confirmPasswordInput.value === \"\" || confirmPasswordInput.value === null) {\n return;\n }\n // Validate if the confirm-password match with the password\n if (confirmPasswordInput.value !== passwordInput.value) {\n return;\n }\n // all validations passed\n else {\n infoDiv.style.display = \"block\"\n infoDiv.style.color = \"green\"\n infoDiv.innerText = `Registered Succesfully. Your account data is: ${emailInput.value} ${nameInput.value} ${passwordInput.value.type = \"******\"} ${confirmPasswordInput.value.type = \"******\"}`\n return;\n }\n}", "function compute(form) {\n var val1 = parseInt(form.day.value, 10)\n if ((val1 < 0) || (val1 > 31)) {\n alert(\"Day is out of range\")\n }\n var val2 = parseInt(form.month.value, 10)\n if ((val2 < 0) || (val2 > 12)) {\n alert(\"Month is out of range\")\n }\n var val2x = parseInt(form.month.value, 10)\n var val3 = parseInt(form.year.value, 10)\n if (val3 < 1900) {\n alert(\"You're that old!\")\n }\n if (val2 == 1) {\n val2x = 13;\n val3 = val3-1\n }\n if (val2 == 2) {\n val2x = 14;\n val3 = val3-1\n }\n var val4 = parseInt(((val2x+1)*3)/5, 10)\n var val5 = parseInt(val3/4, 10)\n var val6 = parseInt(val3/100, 10)\n var val7 = parseInt(val3/400, 10)\n var val8 = val1+(val2x*2)+val4+val3+val5-val6+val7+2\n var val9 = parseInt(val8/7, 10)\n var val0 = val8-(val9*7)\n form.result1.value = months[val2]+\" \"+form.day.value +\", \"+form.year.value\n form.result2.value = days[val0]\n}", "function submitSearchForm()\n{\n\t// put some loading image\n\tdocument.getElementById('employee-travel-details').innerHTML = '<img src=\"../images/loading.gif\"/>';\n\t// get form elements\n\tvar emp_id \t = document.getElementById('search_emp_id').value;\n\tvar start_timestamp = (document.getElementById('search_timerange').value).toString().substr(1);\n\tvar time_indication = document.getElementById('search_timerange').value[0];\n\t\n\t// we need to calculate time to add based on the indication\n\tvar time_to_add;\n\tswitch(time_indication)\n\t{\n\t\tcase 'D': time_to_add =0; break;\n\t\tcase 'M': time_to_add =31; break;\n\t\tcase 'Y': time_to_add =366; break;\n\t}\n\t// now call the function with the prepared details\n\tgetEmpTravelDetails(start_timestamp,time_to_add,emp_id);\n\t// reset the form\n\tempTravelSearch.reset();\n\treturn false;\n}", "function validateForm() {\n // Retrieving the values of form elements \n var dept_num = document.contactForm.dept_num.value;\n var dept_name = document.contactForm.dept_name.value;\n var dept_leader = document.contactForm.dept_leader.value;\n\t// Defining error variables with a default value\n var deptnumErr = deptnameErr = deptleaderErr = true;\n // Validate name\n if(dept_num == \"\") {\n printError(\"deptnumErr\", \"Please enter Depertment Number\");\n } else {\n printError(\"deptnumErr\", \"\");\n deptnumErr = false;\n }\n // Validate email address\n if(dept_name == \"\") {\n printError(\"deptnameErr\", \"Please enter Depertment Name\");\n } else {\n printError(\"deptnameErr\", \"\");\n deptnameErr = false;\n }\n // Validate mobile number\n if(dept_leader == \"\") {\n printError(\"deptleaderErr\", \"Please enter Depertment Leader\");\n } else {\n printError(\"deptleaderErr\", \"\");\n deptleaderErr = false;\n }\n\n \n // Prevent the form from being submitted if there are any errors\n if((deptnumErr || deptleaderErr || deptnameErr ) == true) {\n return false;\n } else {\n // Creating a string from input data for preview\n var dataPreview = \"You've entered the following details: \\n\" +\n \"Depertment Number: \" + dept_num + \"\\n\" +\n \"Depertment Name: \" + dept_name + \"\\n\" +\n \"Depertment Leader: \" + dept_leader + \"\\n\";\n // Display input data in a dialog box before submitting the form\n alert(dataPreview);\n }\n}", "function calculate() {\n 'use strict';\n \n\t//Set up the array, fill it with months\n\tvar months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n\t\n\t//Return appropriate month based on user submission\n\tvar monthnum = document.getElementById('monthnum').value;\n\tvar result = months[monthnum-1];\n\t\n\t// Output the month name\n\tdocument.getElementById('result').value = result;\n\t\n // Return false to prevent submission:\n return false;\n \n} // End of calculate() function.", "function displayResults() {\n\n // hide time, questions and answers \n $(\"#time\").hide();\n $(\"#question1\").hide();\n $(\"#answer1\").hide();\n $(\"#question2\").hide();\n $(\"#answer2\").hide();\n $(\"#question3\").hide();\n $(\"#answer3\").hide();\n $(\"#question4\").hide();\n $(\"#answer4\").hide();\n $(\"#question5\").hide();\n $(\"#answer5\").hide();\n $(\"#question6\").hide();\n $(\"#answer6\").hide();\n $(\"#question7\").hide();\n $(\"#answer7\").hide();\n $(\"#question8\").hide();\n $(\"#answer8\").hide();\n $(\"#question9\").hide();\n $(\"#answer9\").hide();\n $(\"#question10\").hide();\n $(\"#answer10\").hide();\n $(\"#submit\").hide();\n \n // show results of correctAnswers, incorrectAnswers and unanswered.\n $(\"#resultsMessage\").html(\"<h3>Done!</h3>\");\n $(\"#correct\").html(\"Correct Answers: \" + correctAnswers);\n $(\"#incorrect\").html(\"Incorrect Answers: \" + incorrectAnswers);\n $(\"#unanswered\").html(\"Unanswered: \" + unanswered);\n}", "function secondView() {\n document.getElementById(\"content\").innerHTML = \"\";\n //Create heading\n document.getElementById(\"heading\").innerHTML = \"Fufill the form\";\n //Create Form-element\n const content = document.getElementById(\"content\");\n const form = document.createElement(\"form\");\n form.setAttribute(\"id\", \"form\");\n content.appendChild(form);\n //Create run-input\n var div1 = document.createElement(\"div\");\n var input1 = document.createElement(\"input\");\n input1.setAttribute(\"id\", \"input1\");\n var i1l = document.createElement(\"label\");\n i1l.setAttribute(\"for\", \"input1\");\n i1l.innerHTML = \"How many kilometers you did run?\";\n div1.appendChild(i1l);\n input1.setAttribute(\"type\", \"number\");\n input1.setAttribute(\"placeholder\", \"kilometers\");\n div1.appendChild(input1);\n form.appendChild(div1);\n //Create walk-input\n var div2 = document.createElement(\"div\");\n var input2 = document.createElement(\"input\");\n input2.setAttribute(\"id\", \"input2\");\n var i2l = document.createElement(\"label\");\n i2l.setAttribute(\"for\", \"input2\");\n i2l.innerHTML = \"How many kilometers you did walk?\";\n div2.appendChild(i2l);\n input2.setAttribute(\"type\", \"number\");\n input2.setAttribute(\"placeholder\", \"kilometers\");\n div2.appendChild(input2);\n form.appendChild(div2);\n //Create run-input\n var div3 = document.createElement(\"div\");\n var input3 = document.createElement(\"input\");\n input3.setAttribute(\"id\", \"input3\");\n var i3l = document.createElement(\"label\");\n i3l.setAttribute(\"for\", \"input3\");\n i3l.innerHTML = \"How many hours you have slept?\";\n div3.appendChild(i3l);\n input3.setAttribute(\"type\", \"number\");\n input3.setAttribute(\"placeholder\", \"hours\");\n div3.appendChild(input3);\n form.appendChild(div3);\n //Create submit\n var div4 = document.createElement(\"div\");\n var subm = document.createElement(\"input\");\n subm.setAttribute(\"type\", \"submit\");\n subm.setAttribute(\"value\", \"Send data\");\n subm.onclick = sendData;\n div4.appendChild(subm);\n form.appendChild(div4);\n}", "function compute(form) {\n var val1 = parseInt(form.day.value, 10)\n if ((val1 < 0) || (val1 > 31)) {\n alert(\"Day is out of range\")\n }\n var val2 = parseInt(form.month.value, 10)\n if ((val2 < 0) || (val2 > 12)) {\n alert(\"Month is out of range\")\n } \n var val2x = parseInt(form.month.value, 10)\n var val3 = parseInt(form.year.value, 10)\n if (val3 < 1900) {\n alert(\"You're that old!\")\n }\n if (val2 == 1) {\n val2x = 13;\n val3 = val3-1\n }\n if (val2 == 2) {\n val2x = 14;\n val3 = val3-1\n }\n var val4 = parseInt(((val2x+1)*3)/5, 10)\n var val5 = parseInt(val3/4, 10)\n var val6 = parseInt(val3/100, 10)\n var val7 = parseInt(val3/400, 10)\n var val8 = val1+(val2x*2)+val4+val3+val5-val6+val7+2\n var val9 = parseInt(val8/7, 10)\n var val0 = val8-(val9*7)\n form.result1.value = months[val2]+\" \"+form.day.value +\", \"+form.year.value\n form.result2.value = days[val0]\n \n }", "function calculatePrice() {\n validateForm(document.getElementById(\"numDaysInput\")); // calls validateForm to check for positive values\n\n let carPriceFinal = calcCarChoice();\n let optionCostsFinal = calculateOptionsCosts();\n let ageCosts = calculateAgeCost();\n let returnDate = calculateReturnDate();\n\n let surcharge = ageCosts * carPriceFinal;\n document.getElementById(\"underOutput\").value = surcharge.toFixed(2); // Age surcharge\n\n document.getElementById(\"carRentalPmtTotal\").value = carPriceFinal.toFixed(2); // Car Rental Output\n document.getElementById(\"carOptionPmtTotal\").value = optionCostsFinal.toFixed(2); // Car Options\n \n let totalCosts = carPriceFinal + surcharge + optionCostsFinal;\n\n let totalDueField = document.getElementById(\"pmtTotalDue\");\n totalDueField.value = totalCosts.toFixed(2);\n\n let returnDateField = document.getElementById(\"returnDateOutput\");\n returnDateField.value = returnDate.toDateString();\n\n // If any changes to input form, remove error message\n document.getElementById(\"car-Rental\").onchange = function() {\n doReset();\n }\n}", "function validateSearch(form) {\n var alertMsg = \"\"; // Stores the message to display to user indicating which fields are entered incorrectly\n var checkEntry = true; // Is true if all fields are entered correctly, set to false if a field is entered incorrectly\n\n if (!validatePrice(form.pricemin.value) && form.pricemin.value != \"\") {\n //checks to see if Min Price entry is in the appropriate format\n var el = document.getElementsByName(\"pricemin\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Minimum Price must contain only digits, a single decimal point and up to 2 digits following the decimal point.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"pricemin\")[0].style.backgroundColor = \"white\";\n }\n if (!validatePrice(form.pricemax.value) && form.pricemax.value != \"\") {\n //checks to see if Max Price entry is in the appropriate format\n var el = document.getElementsByName(\"pricemax\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Maximum Price must contain only digits, a single decimal point and up to 2 digits following the decimal point.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"pricemax\")[0].style.backgroundColor = \"white\";\n }\n if (\n !validatePostalCode(form.postalcode.value) &&\n form.postalcode.value != \"\"\n ) {\n //checks to see if Postal Code entry is in the appropriate format\n var el = document.getElementsByName(\"postalcode\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Postal Code must be in the Canadian Postal Code format: A0A 0A0\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"postalcode\")[0].style.backgroundColor = \"white\";\n }\n if (!validateCoordinate(form.long.value) && form.long.value != \"\") {\n //checks to see if Longittude entry is in the appropriate format\n var el = document.getElementsByName(\"long\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Longittude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"long\")[0].style.backgroundColor = \"white\";\n }\n\n if (!validateCoordinate(form.latt.value) && form.latt.value != \"\") {\n //checks to see if Lattitude entry is in the appropriate format\n var el = document.getElementsByName(\"latt\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n \"Lattitude must contain at least 1 and up to 3 digits optionally followed by a decimal point and any number of digits.\\n\";\n checkEntry = false;\n } else {\n document.getElementsByName(\"latt\")[0].style.backgroundColor = \"white\";\n }\n\n if (!validateDistance(form.distance.value) && form.distance.value != \"\") {\n //checks to see if Distance entry is in the appropriate format\n var el = document.getElementsByName(\"distance\")[0]; //if entry is incorrect restyles the input element\n el.style.backgroundColor = \"#f5f5f5\";\n alertMsg += \"Distance must contain a positive integer or decimal number.\\n\"; //if entry is incorrect adds an error message for the field to the message that will be displayed to the user\n checkEntry = false;\n } else {\n document.getElementsByName(\"distance\")[0].style.backgroundColor = \"white\";\n }\n if (!checkEntry) {\n //if any of the input fields have an entry in an incorrect format\n window.alert(alertMsg); //displays an error message for each incorrect field to user\n return false; //the validate function returns fa;se\n }\n\n return true; //All input fields contain values in the correct format so the validate function returns true\n}", "function process() {\n\t\n// DECLARE GLOBAL VARIABLES //\t\n// DECLARE GLOBAL VARIABLES //\t\n\tvar allInputs = document.getElementsByTagName('input');\n\tvar textBlock = \"\";\n\t\n\t\tfor (i = 0; i<(allInputs.length); i++) {\n\t\t\ttextBlock += allInputs[i].value + \" <br />\";\n\t\t}\n\t\n\t// declare variables based on all 8 INITIAL inputs\n\tvar currentAge = allInputs[0].value;\n\tvar \tinflationRate\t=\tallInputs[1].value;\n\tvar \tyearsToRetirement\t=\tallInputs[2].value;\n\tvar \ttodaysDollars\t=\tallInputs[3].value;\n\t\n\t\n\t// BELOW TO BE PLACED IN SEPARATE CALCULATION X\n\t//var \tamountInvesting\t=\tallInputs[4].value;\n\t\n\t\n\tvar \ttargetRetirementAge\t=\tallInputs[4].value;\n\tvar \tlengthOfRetirement\t=\tallInputs[5].value;\n\tvar \ttargetInterestRateToNest\t=\t(allInputs[6].value/100);\n\tvar \ttargetRetirementIncomePercentage\t=\t(allInputs[7].value/100);\n\t\n\t// declare variables based on 3 Results - A outputs\n\tvar \ttargetNestAmount\t=\tdocument.getElementById(\"target nest amount\");\n\tvar \tfutureDollars\t=\tdocument.getElementById(\"future dollars\");\n\tvar \tcurrentInvestmentReturn\t=\tdocument.getElementById(\"amount in present time for investment % return per year\");\n\t\n\t// delcare variables based on tabulated Results - B output columns\n\tvar rb01 = document.getElementById(\"rb01\");\n\tvar rb2 = document.getElementById(\"rb2\");\n\tvar rbStart = document.getElementById(\"rbStart\");\n\tvar rbEnd = document.getElementById(\"rbEnd\");\n\tvar rbAge = document.getElementById(\"rbAge01\");\n\t//var allRBAge = document.getElementsByClassName(\"rbAge\");\n\tvar rbIncome = document.getElementById(\"rbIncome01\");\n\t//var allRBIncome = document.getElementsByClassName(\"rbIncome\");\n\tvar rbInterest = document.getElementById(\"rbInterest01\");\n\t//var allRBInterest = document.getElementsByClassName(\"rbInterest\");\n\tvar rbBalance = document.getElementById(\"rbBalance01\");\n\t//var allRBBalance = document.getElementsByClassName(\"rbBalance\");\n\t\n\t// declaring/computing nestAmount\n\tvar nestAmountP1 = todaysDollars*yearsToRetirement;\n\tvar nestAmountP2 = (1 + (inflationRate/100));\n\tvar nestAmountP3 = Math.pow(nestAmountP2, yearsToRetirement);\n\tvar rawNestAmount = (nestAmountP1*nestAmountP3).toFixed(2);\n\tvar nestAmount;\n\tvar totalNestAmount;\n\t\t\t\t\t\n\n// END GLOBAL VARIABLES //\n// END GLOBAL VARIABLES //\n\n\n\n\n\n\t// PRE: CLEAR THE FORM //\n\t\tfunction cleanUp(){\t\t\n\t\t\t\trbStart.innerHTML ='';\n\t\t}\n\t\tcleanUp();\n\t\n\n\t// END PRE //\n\n\n\t// FUNCTION 01: TARGET NEST AMOUNT //\n\t// FUNCTION 01: TARGET NEST AMOUNT //\n\tfunction calcNestAmount() {\n\t\t// the below method was taken from \thttp://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript\n\t\tvar nestAmount = rawNestAmount.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t//alert(\"$\" + nestAmount);\n\t\n\t\t// write nestAmount to appropriate column\n\t\t\n\t\ttargetNestAmount.innerText = \"$\" + nestAmount;\n\t\ttotalNestAmount = targetNestAmount.innerText;\n\t\treturn rawNestAmount;\n\t\treturn totalNestAmount;\n\t\treturn nestAmount;\n\t}\n\tcalcNestAmount();\n\t\n\t// END FUNCTION 01 //\n\t// END FUNCTION 01 //\n\t\n\t\n\t\n\t\n\t\n\t\n\t\n\t// FUNCTION 02: TARGET YEARLY INCOME (FUTURE DOLLARS) //\n\t// FUNCTION 02: TARGET YEARLY INCOME (FUTURE DOLLARS) //\n\tfunction calcFutureDollars() {\n\t\tvar rawFutureIncomeStart = rawNestAmount*targetRetirementIncomePercentage;\n\t\tvar futureIncomeStart = \"$\" + rawFutureIncomeStart.toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\n\t\t// write futureDollars to appropriate column\n\t\tfutureDollars.innerText = futureIncomeStart;\n\t\treturn futureDollars;\n\t\treturn futureIncomeStart;\n\t\treturn rawFutureIncomeStart;\n\t}\n\tcalcFutureDollars();\n\t\n\t// END FUNCTION 02 //\n\t// END FUNCTION 02 //\n\t\n\n\t\n\t\n\t// FUNCTION 03: POPULATE TABULATED RESULTS (FIRST LINE) //\n\t// FUNCTION 03: POPULATE TABULATED RESULTS (FIRST LINE) //\n\t\n\tfunction calcResults() {\n\t\trbAge.innerText = parseInt(currentAge)+parseInt(yearsToRetirement);\n\t\trbIncome.innerText = rawNestAmount*targetRetirementIncomePercentage;\n\t\trbInterest.innerText = (rawNestAmount-(rawNestAmount*targetRetirementIncomePercentage))*targetInterestRateToNest;\n\t\trbBalance.innerText = (rawNestAmount-(rawNestAmount*targetRetirementIncomePercentage))+(rawNestAmount-(rawNestAmount*targetRetirementIncomePercentage))*targetInterestRateToNest;\n\t}\n\tcalcResults();\n\t\n\t\n\t// END FUNCTION 03 //\n\t// END FUNCTION 03 //\n\t\n\t\n\t\n\t\n\t\n\t\n\t// FUNCTION 04: CREATE TABLE //\n\t// FUNCTION 04: CREATE TABLE //\n\t\n\t\n\tfunction createTable(i){\n\t\t//alert('Calculating the remaining...')\n\t\t\n\t\tfor(i=0; i < parseInt(lengthOfRetirement); i++){\n\t\t\t\n\t\t\tvar newRow = document.createElement(\"TR\");\n\t\t\t\n\t\t\tvar newAgeCol = document.createElement(\"TD\");\n\t\t\tnewAgeCol.className = \"rbAge\";\n\t\t\t//newAgeCol.id = \"rbAge\" + i;\n\t\t\tvar newIncomeCol = document.createElement(\"TD\");\n\t\t\tnewIncomeCol.className = \"rbIncome\";\n\t\t\t//newIncomeCol.id = \"rbIncome\" + i;\n\t\t\tvar newInterestCol = document.createElement(\"TD\");\n\t\t\tnewInterestCol.className = \"rbInterest\";\n\t\t\t//newInterestCol.id = \"rbInterest\" + i;\n\t\t\tvar newBalanceCol = document.createElement(\"TD\");\n\t\t\tnewBalanceCol.className = \"rbBalance\";\n\t\t\t//newBalanceCol.id = \"rbBalance\" + i;\n\t\t\t\n\t\t\tnewRow.appendChild(newAgeCol);\n\t\t\tnewRow.appendChild(newIncomeCol);\n\t\t\tnewRow.appendChild(newInterestCol);\n\t\t\tnewRow.appendChild(newBalanceCol);\n\t\t\t\n\t\t\t\n\t\t\trbStart.insertBefore(newRow, rbStart.childNodes[1]);\n\n\t\t\t\n\t\t}\n\t\t\n\t}\n\tcreateTable();\n\t\n\t// END FUNCTION 04 //\n\t// END FUNCTION 04 //\n\t\n\t\n\t\n\t\n\t// FUNCTION 05: POPULATE TABULATED RESULTS (THE REST) //\n\t// FUNCTION 05: POPULATE TABULATED RESULTS (THE REST) //\n\t\n\t\n\tfunction calcRemaining(i){\n\t\t\n\t\tfor(i=0; i < 8; i++){\n\t\t\t\n\t\t\tvar allAge = rbStart.querySelectorAll(\".rbAge\");\n\t\t\tvar allIncome = rbStart.querySelectorAll(\".rbIncome\");\n\t\t\tvar allInterest = rbStart.querySelectorAll(\".rbInterest\");\n\t\t\tvar allBalance = rbStart.querySelectorAll(\".rbBalance\");\n\t\t\t\n\t\t\t// SET ID'S\n\t\t\tallAge[i].id = \"rbAge0\" + (i+parseInt(2));\n\t\t\tallIncome[i].id = \"rbIncome0\" + (i+parseInt(2));\n\t\t\tallInterest[i].id = \"rbInterest0\" +(i+parseInt(2));\n\t\t\tallBalance[i].id = \"rbBalance0\" + (i+parseInt(2));\n\t\t\t\n\t\t\t// CALCULATE REMAINING CELLS\n\t\t\tallAge[i].innerText = parseInt(rbAge.innerText)+i+parseInt(1);\n\t\t\tallIncome[i].innerText = parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText*(targetRetirementIncomePercentage));\n\t\t\tallInterest[i].innerText = (parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) * targetInterestRateToNest;\n\t\t\tallBalance[i].innerText = (parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) + parseFloat(allInterest[i].innerText);\n\t\t\n\t\t\t\n\t\t}\n\t\t\n\t\tfor(i=8; i < 9; i++){\n\t\t\t\n\t\t\tvar allAge = rbStart.querySelectorAll(\".rbAge\");\n\t\t\tvar allIncome = rbStart.querySelectorAll(\".rbIncome\");\n\t\t\tvar allInterest = rbStart.querySelectorAll(\".rbInterest\");\n\t\t\tvar allBalance = rbStart.querySelectorAll(\".rbBalance\");\n\t\t\t\t\t\n\t\t\t// SET ID'S\n\t\t\tallAge[i].id = \"rbAge\" + (i+parseInt(2));\n\t\t\tallIncome[i].id = \"rbIncome\" + (i+parseInt(2));\n\t\t\tallInterest[i].id = \"rbInterest\" +(i+parseInt(2));\n\t\t\tallBalance[i].id = \"rbBalance\" + (i+parseInt(2));\n\t\t\t\n\t\t\t// CALCULATE REMAINING CELLS\n\t\t\tallAge[i].innerText = parseInt(rbAge.innerText)+i+parseInt(1);\n\t\t\tallIncome[i].innerText = parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText*(targetRetirementIncomePercentage));\n\t\t\tallInterest[i].innerText = (parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) * targetInterestRateToNest;\n\t\t\tallBalance[i].innerText = (parseFloat(document.getElementById(\"rbBalance0\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) + parseFloat(allInterest[i].innerText);\n\t\t\n\t\t}\n\t\t\n\t\tfor(i=9; i < 10; i++){\n\t\t\t\n\t\t\tvar allAge = rbStart.querySelectorAll(\".rbAge\");\n\t\t\tvar allIncome = rbStart.querySelectorAll(\".rbIncome\");\n\t\t\tvar allInterest = rbStart.querySelectorAll(\".rbInterest\");\n\t\t\tvar allBalance = rbStart.querySelectorAll(\".rbBalance\");\n\t\n\t\t\t// SET ID'S\n\t\t\tallAge[i].id = \"rbAge\" + (i+parseInt(2));\n\t\t\tallIncome[i].id = \"rbIncome\" + (i+parseInt(2));\n\t\t\tallInterest[i].id = \"rbInterest\" +(i+parseInt(2));\n\t\t\tallBalance[i].id = \"rbBalance\" + (i+parseInt(2));\n\t\t\t\n\t\t\t// CALCULATE REMAINING CELLS\n\t\t\tallAge[i].innerText = parseInt(rbAge.innerText)+i+parseInt(1);\n\t\t\tallIncome[i].innerText = parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText*(targetRetirementIncomePercentage));\n\t\t\tallInterest[i].innerText = (parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) * targetInterestRateToNest;\n\t\t\tallBalance[i].innerText = (parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) + parseFloat(allInterest[i].innerText);\n\t\t\t\n\t\t}\n\t\t\n\t\tfor(i=10; i < parseInt(lengthOfRetirement); i++){\n\t\t\t\n\t\t\tvar allAge = rbStart.querySelectorAll(\".rbAge\");\n\t\t\tvar allIncome = rbStart.querySelectorAll(\".rbIncome\");\n\t\t\tvar allInterest = rbStart.querySelectorAll(\".rbInterest\");\n\t\t\tvar allBalance = rbStart.querySelectorAll(\".rbBalance\");\n\t\t\t\t\n\t\t\t// SET ID'S\n\t\t\tallAge[i].id = \"rbAge\" + (i+parseInt(2));\n\t\t\tallIncome[i].id = \"rbIncome\" + (i+parseInt(2));\n\t\t\tallInterest[i].id = \"rbInterest\" +(i+parseInt(2));\n\t\t\tallBalance[i].id = \"rbBalance\" + (i+parseInt(2));\n\t\t\t\n\t\t\t// CALCULATE REMAINING CELLS\n\t\t\tallAge[i].innerText = parseInt(rbAge.innerText)+i+parseInt(1);\n\t\t\tallIncome[i].innerText = parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText*(targetRetirementIncomePercentage));\n\t\t\tallInterest[i].innerText = (parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) * targetInterestRateToNest;\n\t\t\tallBalance[i].innerText = (parseFloat(document.getElementById(\"rbBalance\"+(parseInt(1)+i)).innerText) - parseFloat(allIncome[i].innerText)) + parseFloat(allInterest[i].innerText);\n\n\t\t}\n\t\t\n\t}\n\tcalcRemaining();\n\t\n\t\n\t\n\t// END FUNCTION 05 //\n\t// END FUNCTION 05 //\n\t\n\n\n\n\n\n\t// NEW GLOBAL VARIABLES BASED ON DYNAMIC RESULTS\n\t\n\t\t// declaring dynamic tabulated results\n\t\tvar allAge = rbStart.querySelectorAll(\".rbAge\");\n\t\tvar allIncome = rbStart.querySelectorAll(\".rbIncome\");\n\t\tvar allInterest = rbStart.querySelectorAll(\".rbInterest\");\n\t\tvar allBalance = rbStart.querySelectorAll(\".rbBalance\");\n\t\n\t// END NEW GLOBAL VARIABLES //\n\t\n\t\n\t\n\t// FUNCTION 06: FORMAT TABULATED RESULTS //\n\t// FUNCTION 06: FORMAT TABULATED RESULTS //\n\t\n\tfunction formatTable(i) {\n\t\t\n\t\t\n\t\t// FORMAT 1ST ROW RB1\n\t\t\n\n\t\tvar rbIncomeFormatted = \"$\" + parseFloat(rbIncome.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbIncome.innerText = rbIncomeFormatted;\n\t\tvar rbInterestFormatted = \"$\" + parseFloat(rbInterest.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbInterest.innerText = rbInterestFormatted;\n\t\tvar rbBalanceFormatted = \"$\" + parseFloat(rbBalance.innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\trbBalance.innerText = rbBalanceFormatted;\n\t\t\n\t\t\n\t\t// FORMAT DYNAMIC RESULTS RB2+\n\t\tfor(i=0; i < parseInt(lengthOfRetirement) ; i++){\n\t\t\t\n\t\t\tallIncome[i].innerText = \"$\" + parseFloat(allIncome[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\tallInterest[i].innerText = \"$\" + parseFloat(allInterest[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\tallBalance[i].innerText = \"$\" + parseFloat(allBalance[i].innerText).toFixed(2).toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n\t\t\t\n\t\t}\n\t\t\n\t}\n\tformatTable();\n\t\n\t\n\t// END FUNCTION 06 //\n\t// END FUNCTION 06 //\n\t\n\t\n\t\n\t// FUNCTION 07: ADJUST TABULATED RESULTS CONTAINER HEIGHT //\n\t// FUNCTION 07: ADJUST TABULATED RESULTS CONTAINER HEIGHT //\n\t\n\t/*function adjustRBContainer(){\n\t\tvar sec4 = document.getElementById(\"sec4\");\n\t\t//var sec4ComputedStyle = window.getComputedStyle(sec4);\n\t\t//var sec4Height = sec4ComputedStyle.getPropertyValue(\"height\");\n\t\tvar sec1 = document.getElementById(\"sec1\");\n\t\tvar sec1ComputedStyle = window.getComputedStyle(sec1);\n\t\tvar sec1Height = sec1ComputedStyle.getPropertyValue(\"height\");\n\t\t\n\t\tvar rb = document.getElementById(\"rbStart\");\n\t\tvar rbComputedStyle = window.getComputedStyle(rb);\n\t\tvar rbHeight = rbComputedStyle.getPropertyValue(\"height\");\n\t\t\n\t\t\n\t\t//ADJUST SIZE FOR LESS RESULTS THAN INITIAL\n\t\t/*if(Number(rbHeight.replace(\"px\", \"\")) < Number(sec1Height.replace(\"px\", \"\"))){\n\t\t\tsec4.style.height = Number(screen.height*(65/100)) + \"px\";\n\t\t}*/\n\t\t\n\t\t\n\t\t//Number(sec1Height.replace(\"px\", \"\")) + \"px\";\n\t\t\n\t\t//RESIZE FOR MORE RESULT THAN INITIAL\n\t/*\tif(Number(rbHeight.replace(\"px\", \"\")) > Number(sec1Height.replace(\"px\", \"\")*(65/100))){\n\t\t\t//sec4.style.height = Number(rbHeight.replace(\"px\", \"\")/(13)) + \"em\";\n\t\t\tsec4.style.height = Number(rbHeight.replace(\"px\", \"\")) + Number(sec1Height.replace(\"px\", \"\")*(50/100)) + \"px\";\n\t\t}\n\t\tif(Number(rbHeight.replace(\"px\", \"\")) < Number(sec1Height.replace(\"px\", \"\")*(65/100))){\n\t\t\tsec4.style.height = sec1Height;\t\n\t\t}\n\t\t\n\t\t\n\t}\n\tadjustRBContainer();*/\n\t\n\t// END FUNCTION 07 //\n\t// END FUNCTION 07 //\n\t\n\t\n}", "function getFormValues(form) \r\n{\r\n\t//initialize vars\r\n\tvar locationOption = \"\";\r\n\tvar groupOption = \"\";\r\n var metricOption = \"\";\r\n var yearOption = \"\";\r\n var gpaOption = \"\";\r\n var mathOption = \"\";\r\n var verbalOption = \"\";\r\n var genderOption = \"\";\r\n \r\n //for each element in the form...\r\n for (var i = 0; i < form.elements.length; i++ ) {\r\n \t\r\n \t//get which location the user has selected\r\n \tif (form.elements[i].name == \"Location\") {\r\n \tlocationOption += form.elements[i].value;\r\n }\r\n \t\r\n \t//get which \"group\" button is checked\r\n if (form.elements[i].name == \"groups\") {\r\n if (form.elements[i].checked == true) {\r\n groupOption += form.elements[i].value;\r\n }\r\n }\r\n \r\n //and which \"metric\" button is checked\r\n if (form.elements[i].name == \"metrics\") {\r\n if (form.elements[i].checked == true) {\r\n metricOption += form.elements[i].value;\r\n }\r\n }\r\n \r\n //get the metric drop-down-menu values\r\n if (form.elements[i].name == \"gpaSelector\") {\r\n \tgpaOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"satMathSelector\") {\r\n \tmathOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"satVerbalSelector\") {\r\n \tverbalOption += form.elements[i].value;\r\n }\r\n \r\n if (form.elements[i].name == \"genderSelector\") {\r\n \tgenderOption += form.elements[i].value;\r\n }\r\n \r\n //and which \"year\" button is checked\r\n if (form.elements[i].name == \"years\") {\r\n if (form.elements[i].checked == true) {\r\n yearOption += form.elements[i].value;\r\n }\r\n }\r\n }\r\n \r\n //update globals\r\n selectedLocation = locationOption;\r\n selectedGroup = groupOption;\r\n selectedMetric = metricOption;\r\n selectedYear = yearOption;\r\n selectedGPA = gpaOption;\r\n\tselectedMath = mathOption;\r\n\tselectedVerbal = verbalOption;\r\n\tselectedGender = genderOption;\r\n\t\r\n\t//we only care about the drop-down associated with the selected metric\r\n\tswitch(selectedMetric)\r\n\t{\r\n\t\tcase \"None\":\r\n\t\t\timportantMetric = \"None\";\r\n\t\t\tbreak;\r\n\t\tcase \"GPA\":\r\n\t\t\timportantMetric = selectedGPA;\r\n\t\t\tbreak;\r\n\t\tcase \"SAT Math\":\r\n\t\t\timportantMetric = selectedMath;\r\n\t\t\tbreak;\r\n\t\tcase \"SAT Verbal\":\r\n\t\t\timportantMetric = selectedVerbal;\r\n\t\t\tbreak;\r\n\t\tcase \"Male / Female\":\r\n\t\t\timportantMetric = selectedGender;\r\n\t\t\tbreak;\r\n\t\tcase \"Visited\":\r\n\t\t\timportantMetric = \"Visited\";\r\n\t\t\tbreak;\r\n\t\tdefault:\r\n\t\t\timportantMetric = \"ERROR\";\r\n\t}\r\n \r\n //create associative array\r\n\tvar optionSettings = {};\r\n\toptionSettings['location'] = selectedLocation;\r\n\toptionSettings['group'] = selectedGroup;\r\n\toptionSettings['metric'] = selectedMetric;\r\n\toptionSettings['year'] = selectedYear;\r\n\toptionSettings['dropVal'] = importantMetric;\r\n\t\r\n\treturn optionSettings; \r\n}//end getValues", "function validate() {\n\t\t//Invaild entry responces.\n\t\tvar nameConf = \"Please provide your Name.\";\n\t\tvar emailConf = \"Please provide your Email.\";\n\t\tvar phoneConf = \"Please provide a valid Phone Number.\";\n\t\t\n\t\t//Regular Expression validation.\n\t\tvar phoneNumber = /^\\d{10}$/; //validate that the user enters a 10 digit phone number\n\t\n\t if(document.myForm.name.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = nameConf;\n\t document.myForm.name.focus();\n\t return false;\n\t }\n\t \n\t if(document.myForm.email.value === \"\" ) {\n\t document.getElementById(\"valConf\").innerHTML = emailConf;\n\t document.myForm.email.focus();\n\t return false;\n\t }\n\t \n\t \tif(document.myForm.phone.value.match(phoneNumber) ) {\n\t document.getElementById(\"valConf\").innerHTML = phoneConf;\n\t document.myForm.phone.focus();\n\t return false;\n\t }\n\t} //form validation to confirm the form isn't empty ", "function Validate(e) {\n\n error_list.innerHTML = \"\"; // empty the list to avoid repetition\n var myForm = e.currentTarget;\n\n let li; // variable to hold an error list-item\n\n // in case of error create li and inject msg\n if (myForm[0].value == \"\") {\n li = document.createElement(\"li\");\n li.innerHTML += \"Select a proper room number.\";\n error_list.appendChild(li);\n roomOK = false;\n\n }else {\n roomOK = true;\n }\n\n // check if the time interval is valid\n if (myForm[2].value >= myForm[3].value) {\n li = document.createElement(\"li\");\n li.innerHTML += \"End time must be after the start time\";\n error_list.appendChild(li);\n timeIntervalOK = false;\n\n } else {\n timeIntervalOK = true;\n }\n\n // in case the error flag is set, show to error summary\n error = !(roomOK && dateOK && startTimeOK && endTimeOK && timeIntervalOK);\n if(error) {\n document.querySelector(\"#err_mod\").classList.replace(\"invisible\", \"visible\");\n document.querySelector(\"#succ_mod\").classList.replace(\"visible\", \"invisible\");\n \te.preventDefault();\n\treturn false;\n// or show success msg\n }else{\n document.querySelector(\"#err_mod\").classList.replace(\"visible\", \"invisible\");\n document.querySelector(\"#succ_mod\").classList.replace(\"invisible\", \"visible\");\n return true;\n }\n}", "function start() {\n // so we can test the calcMonthlyPayment independently of all the\n // HTML, only do the rest if this is run on a page with the form\n if (!calcForm) return;\n\n setInitialValues();\n \n calcForm.addEventListener(\"submit\", function (evt) {\n evt.preventDefault();\n getFormValuesAndDisplayResults();\n });\n}", "function handle_form(form_name, submit_name, result_tgt) {\n var submit_action = function(e) {\n e.preventDefault();\n $.ajax({\n url: $(form_name).attr('action'),\n method: $(form_name).attr('method'),\n data: $(form_name).serialize(),\n beforeSend: spinner(result_tgt),\n }).done(function(data){$(result_tgt).empty().html(data);});\n };\n $(form_name).submit(submit_action);\n $(submit_name).click(submit_action);\n}", "function validateResult(result, numFiles) {\n console.log(result);\n // Should have 3 rows: request id, lines written in database, and files saved\n var results = result.split(\"\\n\");\n if (results.length != 3) {\n $(\"#cpBody\").hide();\n $(\"#cpError\").show().append(document.createTextNode(\"submitCP - \" + result));\n return;\n }\n var reqId = results[0].split(\":\")[1];\n //var requestdID = reqId.split(\"_\")[0]; // Chris added 20150924 // Jonathan changed back 20151221\n if (reqId == \"0\" || results[1].charAt(0) != \"1\" || results[2].charAt(0) != numFiles) {\n $(\"#cpBody\").hide();\n $(\"#cpError\").show().append(document.createTextNode(\"submitCP - Request processed incorrectly\"));\n return;\n }\n var alertMsg = \"<div class=\\\"alert alert-success\\\" role=\\\"alert\\\" id=\\\"alertSuccess\\\">\";\n alertMsg += \"<a href=\\\"#\\\" class=\\\"close\\\" data-dismiss=\\\"alert\\\" aria-label=\\\"close\\\">&times;</a>\";\n alertMsg += \"Request Submitted Successfully! Your Request ID is: <b>\" + reqId + \"</b></div>\"; // Chris commented out 20150924 // Jonathan changed back 20151221\n //alertMsg += \"Request Submitted Successfully! Your Request ID is: <b>\" + requestdID + \"</b></div>\"; // Chris added to fix this Success Message: \"Request Submitted Successfully! Your Request ID is: 9696_New Account Info.txtRequest ID\" to only show 9696 // Jonathan changed back 20151221\n var alert = $(alertMsg);\n alert.prependTo(\"#cp\");\n $(\"#alertSuccess\").alert();\n }", "function start() {\n // so we can test the calcMonthlyPayment independently of all the\n // HTML, only do the rest if this is run on a page with the form\n if (!calcForm) return;\n\n setInitialValues();\n\n calcForm.addEventListener(\"submit\", function (evt) {\n evt.preventDefault();\n getFormValuesAndDisplayResults();\n });\n}", "calculateForm(){\n\t\tlet instance = this;\n\n\t\tif(instance.hasErrorInTheForm()) return;\n\t\t\n\t\tinstance.debt = instance.calculateDebt({\n\t\t\tamount: instance.calculatorData,\n\t\t\tinterest: instance.dropdownData.interest,\n\t\t\tmonths: instance.dropdownData.months\n\t\t});\n\n\t\tinstance.element.querySelector('#input-total').placeholder = `R$: ${instance.debt}`;\n\t\tinstance.element.querySelector('.get-quot').removeAttribute('disabled');\n\t}", "function validateForm() {\n // Clear before use.\n $('#table > tbody').empty();\n var topic = $('#topic-input').val().trim();\n console.log(\"Topic: \", topic);\n var city = $('#city-input').val().trim();\n console.log(\"City: \", city);\n var state = $('#state-input').val().trim();\n console.log(\"State: \", state);\n // Confirm everything is filled out.\n if (topic == \"\" || city == \"\" || state == \"\") {\n $(\"#search-results\").append('<div id=\"error\"> Please fill out the appropriate sections. </div>');\n }\n else {\n $(\"#error\").empty();\n initMap();\n getData();\n }\n}", "function validateForm() {\n\n\tvar emaildMandatory = \"\";\n\tvar passwordMandatory = \"\";\n\tvar countryMandatory = \"\";\n\tvar lScoreMandatory = \"\";\n\tvar sScoreMandatory = \"\";\n\tvar wScoreMandatory = \"\";\n\tvar rScoreMandatory = \"\";\n\tvar genderMandatory = \"\";\n\tvar lDateMandatory = \"\";\n\tvar dobMandatory = \"\";\n\tvar proMandatory = \"\"\n\tvar credentialMandatory = \"\"\n\tvar isFormValid = true;\n\tvar crsScoreMandatory = \"\";\n\n\tif (String(document.getElementById(\"email\").value).length == 0) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory = \"*Email is Mandatory\";\n\t\tisFormValid = false;\n\t} else if (!validateEmail(document.getElementById(\"email\").value)) {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'red');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t\temaildMandatory += \"*Entered Email is invalid\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#email\").css('width', '935px');\n\t\t$(\"#email\").css('border-right-style', 'solid');\n\t\t$(\"#email\").css('border-right-color', 'green');\n\t\t$(\"#email\").css('border-right-width', '15px');\n\t\t$(\"#email\").css('border-radius', '3px');\n\t}\n\n\tif (!validateGender()) {\n\t\tgenderMandatory += \"*Gender is Mandatory\";\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'red');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#malediv\").css('width', '935px');\n\t\t$(\"#malediv\").css('border-radius', '3px');\n\t\t$(\"#malediv\").css('border-right-style', 'solid');\n\t\t$(\"#malediv\").css('border-right-color', 'green');\n\t\t$(\"#malediv\").css('border-right-width', '15px');\n\t}\n\n\tif (!validateCountry()) {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'red');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t\tcountryMandatory += \"*Country is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#coc\").css('border-right-style', 'solid');\n\t\t$(\"#coc\").css('border-right-color', 'green');\n\t\t$(\"#coc\").css('border-right-width', '15px');\n\t\t$(\"#coc\").css('border-radius', '3px');\n\t}\n\n\tif (!validateCRS()) {\n\t\tif ($('#calButton').is(':visible')) {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*You should calculate the CRS Score. Please click 'Calculate' button\";\n\t\t\t$(\"#calButton\").click(function() {\n\t\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t\t$(\"#crs\").css('border-right-color', 'green');\n\t\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\t\tcrsScoreMandatory = \"\";\n\t\t\t})\n\t\t} else {\n\t\t\t$(\"#crs\").css('width', '935px');\n\t\t\t$(\"#crs\").css('border-radius', '3px');\n\t\t\t$(\"#crs\").css('border-right-style', 'solid');\n\t\t\t$(\"#crs\").css('border-right-color', 'red');\n\t\t\t$(\"#crs\").css('border-right-width', '15px');\n\t\t\tcrsScoreMandatory += \"*Make sure proper IELTS score is provided.\";\n\t\t}\n\t\tisFormValid = false;\n\t}\n\n\tif (!validateCredential()) {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'red');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t\tcredentialMandatory += \"*Educational Credential is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#edu\").css('border-right-style', 'solid');\n\t\t$(\"#edu\").css('border-right-color', 'green');\n\t\t$(\"#edu\").css('border-right-width', '15px');\n\t\t$(\"#edu\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLScore()) {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'red');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t\tlScoreMandatory += \"*Listening Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#lscore\").css('border-right-style', 'solid');\n\t\t$(\"#lscore\").css('border-right-color', 'green');\n\t\t$(\"#lscore\").css('border-right-width', '15px');\n\t\t$(\"#lscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateRScore()) {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'red');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t\trScoreMandatory += \"*Reading Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#rscore\").css('border-right-style', 'solid');\n\t\t$(\"#rscore\").css('border-right-color', 'green');\n\t\t$(\"#rscore\").css('border-right-width', '15px');\n\t\t$(\"#rscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateWScore()) {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'red');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t\twScoreMandatory += \"*Writing Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#wscore\").css('border-right-style', 'solid');\n\t\t$(\"#wscore\").css('border-right-color', 'green');\n\t\t$(\"#wscore\").css('border-right-width', '15px');\n\t\t$(\"#wscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateSScore()) {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'red');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t\tsScoreMandatory += \"*Speaking Score is Mandatory\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#sscore\").css('border-right-style', 'solid');\n\t\t$(\"#sscore\").css('border-right-color', 'green');\n\t\t$(\"#sscore\").css('border-right-width', '15px');\n\t\t$(\"#sscore\").css('border-radius', '3px');\n\t}\n\n\tif (!validateDob()) {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'red');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t\tdobMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#dob\").css('width', '935px');\n\t\t$(\"#dob\").css('border-right-style', 'solid');\n\t\t$(\"#dob\").css('border-right-color', 'green');\n\t\t$(\"#dob\").css('border-right-width', '15px');\n\t\t$(\"#dob\").css('border-radius', '3px');\n\t}\n\n\tif (!validateLDate()) {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'red');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t\tlDateMandatory += \"*Please enter a valid date\";\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#ldate\").css('width', '935px');\n\t\t$(\"#ldate\").css('border-right-style', 'solid');\n\t\t$(\"#ldate\").css('border-right-color', 'green');\n\t\t$(\"#ldate\").css('border-right-width', '15px');\n\t\t$(\"#ldate\").css('border-radius', '3px');\n\t}\n\n\tif (!validateProvince()) {\n\t\tproMandatory += \"*Please select atleast one province\";\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'red');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t\tisFormValid = false;\n\t} else {\n\t\t$(\"#proinpdiv\").css('width', '935px');\n\t\t$(\"#proinpdiv\").css('border-radius', '3px');\n\t\t$(\"#proinpdiv\").css('border-right-style', 'solid');\n\t\t$(\"#proinpdiv\").css('border-right-color', 'green');\n\t\t$(\"#proinpdiv\").css('border-right-width', '15px');\n\t}\n\n\tif (isFormValid) {\n\t\tshowSuccess();\n\t}\n\n\tdocument.getElementById('emailinvalid').innerHTML = emaildMandatory;\n\tdocument.getElementById('dobinvalid').innerHTML = dobMandatory;\n\tdocument.getElementById('cocinvalid').innerHTML = countryMandatory;\n\tdocument.getElementById('lscoreinvalid').innerHTML = lScoreMandatory;\n\tdocument.getElementById('sscoreinvalid').innerHTML = sScoreMandatory;\n\tdocument.getElementById('wscoreinvalid').innerHTML = wScoreMandatory;\n\tdocument.getElementById('rscoreinvalid').innerHTML = rScoreMandatory;\n\tdocument.getElementById('ldateinvalid').innerHTML = lDateMandatory;\n\tdocument.getElementById('provinceinvalid').innerHTML = proMandatory;\n\tdocument.getElementById('genderinvalid').innerHTML = genderMandatory;\n\tdocument.getElementById('eduinvalid').innerHTML = credentialMandatory;\n\tdocument.getElementById('crsinvalid').innerHTML = crsScoreMandatory;\n}", "function renderExamResult() {\n console.log('renderExamResult() has been used.');\n \n hideElements(['challenge', 'progress', 'timer']);\n \n showElement('.result');\n\n\n var summary = validateExamAnswers();\n var score = summary.score;\n var title;\n var subtitle;\n var image;\n\n var html = '';\n\n subtitle = getMessage('result_score', 'Your score is ${score}.', ['<strong>'+score+'%</strong>']) + ' ';\n\n if (score == 100) {\n title = getMessage('result_perfect', 'Perfect');\n subtitle += getMessage('result_perfect_details', 'Will you repeat this?');\n image = 'passed';\n }\n if (score >= 80 && score < 100) {\n title = getMessage('result_great', 'Great');\n subtitle += getMessage('result_great_details', 'You would pass exam.');\n image = 'passed';\n }\n if (score >= 50 && score < 80) {\n title = getMessage('result_not_good', 'Not good');\n subtitle += getMessage('result_not_good_details', 'You can do it better.');\n image = 'failed';\n }\n if (score < 50) {\n title = getMessage('result_poor', 'Poor');\n subtitle += getMessage('result_poor_details', 'You have to do it better.');\n image = 'failed';\n }\n if (score == 0) {\n title = getMessage('result_terrible', 'Terrible');\n subtitle += getMessage('result_terrible_details', 'Start to learn wise.');\n image = 'epic-fail';\n }\n\n html += '<div class=\"row\">';\n html += '<div class=\"col mb-3\">';\n html += '<div class=\"card text-center result-box\">';\n // html += '<div class=\"card text-center col-sm-6 col-md-6 col-lg-8 col-xl-12\">';\n html += ' <div class=\"card-header\">';\n // html += allExams[exam].exam.toUpperCase() + ' exam result';\n html += getMessage('exam_result_header', '${name} exam result', [allExams[exam].description]);\n // html += ' Service Mapping exam result';\n html += ' </div>';\n html += ' <a href=\"#\" onclick=\"javascript:renderExamResultDetails();\">';\n html += ' <div class=\"card-body\">';\n html += ' <div class=\"col-sm-6 result-image '+image+'\"></div>';\n html += ' <h1 class=\"card-title\">'+title+'</h1>';\n html += ' <p class=\"card-text\">'+subtitle.replace('%d%', '<strong>'+score+'%</strong>')+'</p>';\n // html += '<a href=\"#\" class=\"btn btn-primary\">Go somewhere</a>';\n html += ' </div>';\n html += ' </a>';\n html += '</div>';\n html += '</div>';\n html += '</div>';\n\n html += '<div class=\"row row-cols-1 row-cols-md-2\">';\n html += ' <div class=\"col mb-3 col-sm-6 col-md-6\">';\n html += ' <div class=\"card h-100 text-center text-success border-success result-box\">';\n html += ' <a href=\"#\" onclick=\"javascript:renderExamResultDetails(\\'correct\\');\">';\n html += ' <div class=\"card-body\">';\n html += ' <h1 class=\"card-title\">'+summary.correct.length+'</h1>';\n html += ' <p class=\"card-text\">' + getMessage('exam_result_correct', 'Questions answered correctly.') + '</p>';\n html += ' </div>';\n html += ' </a>';\n html += ' </div>';\n html += ' </div>';\n html += ' <div class=\"col mb-3 col-sm-6 col-md-6\">';\n html += ' <div class=\"card h-100 text-center text-danger border-danger result-box\">';\n html += ' <a href=\"#\" onclick=\"javascript:renderExamResultDetails(\\'wrong\\');\">';\n html += ' <div class=\"card-body\">';\n html += ' <h1 class=\"card-title\">'+summary.wrong.length+'</h1>';\n html += ' <p class=\"card-text\">' + getMessage('exam_result_incorrect', 'Questions with incorrect or missing answer.') + '</p>';\n html += ' </div>';\n html += ' </a>';\n html += ' </div>';\n html += ' </div>';\n html += '</div>';\n\n // html += '<div class=\"row\">';\n // html += ' <div class=\"col text-center mt-3 mb-3\">';\n // html += '<button id=\"repeat-exam\" onclick=\"javascript:repeatExam();\" class=\"btn btn-secondary\">Repeat same questions</button>';\n // html += '<button id=\"retry-exam\" onclick=\"javascript:retryExam();\" class=\"btn btn-primary\">Retry new questions</button>';\n // html += ' </div>';\n // html += '</div>';\n\n html += '<div class=\"row row-cols-1 row-cols-md-2\">';\n html += ' <div class=\"col text-center mb-3 col-sm-6 col-md-6\">';\n html += ' <button id=\"retry-exam\" onclick=\"javascript:retryExam();\" class=\"btn btn-primary\">' + getMessage('retry_exam', 'Retry new questions') + '</button>';\n html += ' </div>';\n html += ' <div class=\"col text-center mb-3 col-sm-6 col-md-6\">';\n html += ' <button id=\"repeat-exam\" onclick=\"javascript:repeatExam();\" class=\"btn btn-secondary\">' + getMessage('repeat_exam', 'Repeat same questions') + '</button>';\n html += ' </div>';\n html += '</div>';\n \n\n // renderElement('.result', result + '<p class=\"advice\">' + advice + '</p>' + html);\n renderElement('.result', html);\n\n state = 'exam_result_rendered';\n}", "function DailyRunForm(props) {\n const [formObject, setFormObject] = useState({\n pace: 0,\n distance: 0,\n date: new Date(),\n totalTime: 0,\n });\n const { date } = formObject;\n const formEl = useRef(null);\n const alert = useAlert();\n\n function handleInputChange(event) {\n const { name, value } = event.target;\n setFormObject({ ...formObject, [name]: value });\n }\n\n function onDateChange(name, value) {\n setFormObject({ ...formObject, [name]: value });\n }\n\n function handleFormSubmit(event) {\n event.preventDefault();\n const formatteddate = moment(date).format('YYYY-MM-DD');\n const validParams = validateRun(\n formObject.distance,\n formatteddate,\n formObject.totalTime\n );\n if (validParams) {\n if (formObject.distance && formObject.totalTime) {\n API.saveRunningStat({\n distance: formObject.distance,\n date: formatteddate,\n totalTime: formObject.totalTime,\n })\n .then((res) => {\n formEl.current.reset();\n formObject.distance = '';\n formObject.totalTime = '';\n alert.success('Race Saved!');\n props.handleBarChart();\n })\n .catch((err) => console.log(err));\n }\n } else {\n alert.error('Please enter valid input');\n }\n }\n //returns race run form\n return (\n <>\n <form ref={formEl}>\n <Row>\n <Col size=\"3\">\n <div className=\"radio\">\n <label htmlFor=\"5k\">\n <Input\n type=\"radio\"\n value=\"5\"\n name=\"distance\"\n onChange={handleInputChange}\n id=\"5k\"\n />\n 5K\n </label>\n </div>\n </Col>\n <Col size=\"3\">\n <div className=\"radio\">\n <label htmlFor=\"10k\">\n <Input\n type=\"radio\"\n value=\"10\"\n name=\"distance\"\n onChange={handleInputChange}\n id=\"10k\"\n />\n 10K\n </label>\n </div>\n </Col>\n <Col size=\"3\">\n <div className=\"radio\">\n <label htmlFor=\"21k\">\n <Input\n type=\"radio\"\n value=\"21\"\n name=\"distance\"\n onChange={handleInputChange}\n id=\"21k\"\n />\n Half Marathon\n </label>\n </div>\n </Col>\n <Col size=\"3\">\n <div className=\"radio\">\n <label htmlFor=\"42k\">\n <Input\n type=\"radio\"\n value=\"42\"\n name=\"distance\"\n onChange={handleInputChange}\n id=\"42k\"\n />\n Marathon\n </label>\n </div>\n </Col>\n </Row>\n <div className=\"form-group\">\n <DatePicker\n onChange={(date) => onDateChange('date', date)}\n name=\"date\"\n className=\"form-control\"\n selected={date}\n placeholder=\"Date (required)\"\n />\n </div>\n <Input\n onChange={handleInputChange}\n name=\"totalTime\"\n placeholder=\"Total Time (required)\"\n />\n <FormBtn\n disabled={!(formObject.distance && formObject.totalTime)}\n onClick={handleFormSubmit}\n >\n {' '}\n <i className=\"fa fa-floppy-o\" aria-hidden=\"true\"></i> Submit race\n </FormBtn>\n <button\n type=\"button\"\n className=\"btn btn-secondary\"\n data-dismiss=\"modal\"\n >\n Cancel\n </button>\n </form>\n </>\n );\n}", "function postRenderValidation(result) {\n // make sure we did not break anything\n validateRequest(\"render\", result);\n\n let errors = validate(result, {\n \"canvas.geometry\": {presence: true, isNotEmpty: true},\n \"canvas.geometry.x\": {presence: true, isNumber: true},\n \"canvas.geometry.y\": {presence: true, isNumber: true},\n \"canvas.geometry.w\": {presence: true, isNumber: true},\n \"canvas.geometry.h\": {presence: true, isNumber: true},\n \"canvas.sections\": {\n sectionValidator: {\n \"#.geometry\": {presence: true, isNotEmpty: false},\n \"#.geometry.x\": {presence: true, isNumber: true},\n \"#.geometry.y\": {presence: true, isNumber: true},\n \"#.geometry.w\": {presence: true, isNumber: true},\n \"#.geometry.h\": {presence: true, isNumber: true},\n }\n }\n });\n if (errors) {\n throw errors;\n }\n}", "function validateForm(e) {\n e.preventDefault();\n let rateValue = ratingSelected;\n let satValue = document.forms[\"surveyForm\"][\"satisfaction\"].value;\n if (rateValue == \"\" || rateValue == null) {\n alert(\"Provide rating for the survey\");\n return false;\n } else if (satValue == \"\") {\n alert(\n \"Tell us how satisfied you are with this survey, select option accordingly\"\n );\n return false;\n } else if (!isValidDescription()) {\n alert(\"Select at least one description for our product\");\n return false;\n } else {\n //Hide the container and show success alert div\n let containerDiv = document.getElementById(\"container\");\n setTimeout(function() {}, 500);\n containerDiv.style.display = \"none\";\n let sucessDiv = document.getElementById(\"success\");\n sucessDiv.classList.remove(\"success-hide\");\n sucessDiv.classList.add(\"success-alert\");\n return true;\n }\n}", "function gradeSubmission() {\n $(\"#submittedCodePRE\").html(htmlspecialchars($(\"#actualCodeInput\").val()));\n\n for (var i = 0; i < tests.length; i++) {\n var res = testResults[i];\n\n $(\"#gradeMatrix tbody#gradeMatrixTbody\").append('<tr class=\"gradeMatrixRow\"></tr>');\n\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"testInputCell\"></td>');\n\n // input_val could be null if there's a REALLY bad error :(\n if (res.input_globals) {\n var curCell = $(\"#gradeMatrix tr.gradeMatrixRow:last td.testInputCell:last\");\n\n curCell.append('<table class=\"testInputTable\"></table>');\n\n // print out all non-function input global variables in a table\n for (k in res.input_globals) {\n var v = res.input_globals[k];\n if (isPrimitiveType(v) || v[0] != 'function') {\n curCell.find('table.testInputTable').append('<tr class=\"testInputVarRow\"></tr>');\n\n curCell.find('table.testInputTable tr.testInputVarRow:last').append('<td class=\"testInputVarnameCell\">' + k + ':</td>');\n\n curCell.find('table.testInputTable tr.testInputVarRow:last').append('<td class=\"testInputValCell\"></td>');\n renderData(v, curCell.find('table.testInputTable td.testInputValCell:last'), true /* ignoreIDs */);\n }\n }\n }\n\n if (res.status == 'error') {\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"testOutputCell\"><span style=\"color: ' + darkRed + '\">' + res.error_msg + '</span></td>');\n }\n else {\n assert(res.status == 'ok');\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"testOutputCell\"></td>');\n\n var curCell = $(\"#gradeMatrix tr.gradeMatrixRow:last td.testOutputCell:last\");\n curCell.append('<table><tr class=\"testOutputVarRow\"></tr></table>');\n\n curCell.find('tr.testOutputVarRow:last').append('<td class=\"testOutputVarnameCell\">' + res.output_var_to_compare + ':</td>');\n\n curCell.find('tr.testOutputVarRow:last').append('<td class=\"testOutputValCell\"></td>');\n renderData(res.test_val, curCell.find('td.testOutputValCell:last'), true /* ignoreIDs */);\n }\n\n\n if (res.passed_test) {\n var happyFaceImg = '<img style=\"vertical-align: middle;\" src=\"yellow-happy-face.png\"/>';\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"statusCell\">' + happyFaceImg + '</td>');\n\n // add an empty 'expected' cell\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"expectedCell\"></td>');\n }\n else {\n var sadFaceImg = '<img style=\"vertical-align: middle; margin-right: 8px;\" src=\"red-sad-face.jpg\"/>';\n\n var debugBtnID = 'debug_test_' + i;\n var debugMeBtn = '<button id=\"' + debugBtnID + '\" class=\"debugBtn\" type=\"button\">Debug me</button>';\n var expectedTd = '<td class=\"expectedCell\">Expected: </td>';\n\n $(\"#gradeMatrix tr.gradeMatrixRow:last\").append('<td class=\"statusCell\">' + sadFaceImg + debugMeBtn + '</td>' + expectedTd);\n\n renderData(res.expect_val,\n $(\"#gradeMatrix tr.gradeMatrixRow:last td.expectedCell:last\"),\n true /* ignoreIDs */);\n\n $('#' + debugBtnID).unbind(); // unbind it just to be paranoid\n $('#' + debugBtnID).click(genDebugLinkHandler(i));\n }\n }\n\n\n var numPassed = 0;\n for (var i = 0; i < tests.length; i++) {\n var res = testResults[i];\n if (res.passed_test) {\n numPassed++;\n }\n }\n\n if (numPassed < tests.length) {\n $(\"#gradeSummary\").html('Your submitted answer passed ' + numPassed + ' out of ' + tests.length + ' tests. Try to debug the failed tests!');\n }\n else {\n assert(numPassed == tests.length);\n $(\"#gradeSummary\").html('Congrats, your submitted answer passed all ' + tests.length + ' tests!');\n }\n\n}", "function formSubmit(){\n\n return true; // uncomment this line to bypass the validations\n\n // Fetch all user inputs\n var name = document.getElementById('name').value;\n var email = document.getElementById('email').value;\n var password = document.getElementById('password').value;\n var confirmPassword = document.getElementById('confirmPassword').value;\n var mouse = document.getElementById('mouse').value;\n var ram = document.getElementById('ram').value;\n var ssd = document.getElementById('ssd').value;\n var creditCard = document.getElementById('creditCard').value;\n var province = document.getElementById('province').value;\n var city = document.getElementById('city').value;\n var address = document.getElementById('address').value;\n var paperReceiptRadios = document.getElementsByName('paperReceipt');\n var taxRate;\n\n // Calculate total price\n var sum = mouse * mousePrice + ram * ramPrice + ssd * ssdPrice;\n\n //Identify the selected radios input and assign it to \"paperReceipt\" \n var paperReceipt;\n for(var i = 0; i < paperReceiptRadios.length; i++) {\n if(paperReceiptRadios[i].checked) {\n paperReceipt = paperReceiptRadios[i].value;\n }\n }\n\n // add error if any input is empty\n var error = '';\n if(name == '') {\n error += 'Name is required. <br>';\n }\n if(email == '') {\n error += 'Email is required. <br>';\n }\n\n // add error if email is in wrong format\n if(!emailRegex.test(email)) {\n error += 'Email is in wrong format. <br>';\n }\n\n if(password == '') {\n error += 'Password is required. <br>';\n }\n if(confirmPassword == '') {\n error += 'Confirm Password is required. <br>';\n }\n\n // add error if password is in wrong format\n if(!passwordRegex.test(password)) {\n error += 'Password length must be at least 8 alphanumeric characters. <br>';\n } \n\n // add error if two passwords don't match\n if(password != confirmPassword) {\n error += \"Two passwords don't match. <br>\";\n } \n \n if(creditCard == '') {\n error += 'Credit Card is required. <br>';\n }\n if(province == '') {\n error += 'Province is required. <br>';\n }\n if(city == '') {\n error += 'City is required. <br>';\n }\n if(address == '') {\n error += 'Address is required. <br>';\n }\n\n // add error if total cost is less than $10\n if(sum < 10) {\n error += 'You must at least by $10 worth products. <br>';\n }\n\n // add error if credit card is in wrong format\n if(!creditCardRegex.test(creditCard)) {\n error += \"The credit card should be in the format xxxx-xxxx-xxxx-xxxx with all numerical values. <br>\";\n }\n\n // show a message if there is any error\n if(error != '') {\n document.getElementById('error').innerHTML = error;\n } else {\n document.getElementById('error').innerHTML = '';\n \n // Set tax rate by province\n switch(province) {\n case 'Alberta':\n case 'Northwest Territories':\n case 'Nunavut':\n case 'Yukon':\n taxRate = 0.05;\n break;\n case 'British Columbia':\n case 'Manitoba':\n taxRate = 0.12;\n break;\n case 'New Brunswick':\n case 'Newfoundland and Labrador':\n case 'Nova Scotia':\n case 'Prince Edward Island':\n taxRate = 0.15;\n break;\n case 'Ontario':\n taxRate = 0.13;\n break;\n case 'Quebec':\n taxRate = 0.14975;\n break;\n case 'Saskatchewan':\n taxRate = 0.11;\n break;\n\n // The default should never be excuted, but set it in case it runs\n default:\n taxRate = 9999;\n break;\n }\n\n // Generate a receipt to user\n document.getElementById('receipt').innerHTML = `------------Your receipt------------\n Name: ${name}<br>\n Email: ${email}<br>\n Password: ${password}<br>\n ${mouse ? 'Bluetooth mouse * ' + mouse + '<br>' : ''}\n ${ram ? '8GB RAM * ' + ram + '<br>' : ''}\n ${ssd ? '500GB SSD * ' + ssd + '<br>' : ''}\n Credit card number:<br> ${creditCard}<br>\n Province: ${province}<br>\n City: ${city}<br>\n Address: ${address}<br>\n Paper receipt: ${paperReceipt}<br>\n Total cost(without tax): $${sum}<br>\n Total tax: $${sum * taxRate}<br>\n Total cost(including tax): $${(sum * (1 + taxRate)).toFixed(2)}<br>\n ------------End of receipt------------\n `;\n }\n\n // Stop redirecting to next page.\n return false;\n}", "function validateForms() {\n var typedForms = document.querySelectorAll('input');\n var designMenu = document.getElementById('design');\n var designLabel = document.querySelector('.shirt').lastElementChild;\n var designChoice = designMenu.options[designMenu.selectedIndex].text;\n var paymentMethod = document.getElementById('payment');\n var paymentForm = paymentMethod.options[paymentMethod.selectedIndex].text;\n if (designChoice == 'Select Theme') {\n addErrorIndication('Please select a theme', designLabel);\n }\n if ($(\"[type=checkbox]:checked\").length < 1) {\n var activityList = document.querySelectorAll('.activities label')\n var str = 'Please select at least one activity';\n addErrorIndication(str, activityList[activityList.length-1]);\n }\n if (paymentForm == 'Select Payment Method') {\n addErrorIndication('Please select a payment method', paymentMenu);\n }\n for (let i = 0; i < typedForms.length; i++) {\n var currentForm = typedForms[i];\n if (currentForm.id == 'name' && currentForm.value.length < 1) {\n var str = 'Please enter a name';\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'mail' && checkFormat(currentForm) == false) {\n var str = 'Please enter an email address';\n addErrorIndication(str, currentForm);\n } else if (paymentForm == 'Credit Card' && checkFormat(currentForm) == false) {\n if (currentForm.id == 'cc-num') {\n var str = 'Please enter a credit card number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is between 13 and 16 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'zip') {\n var str = 'Please enter a zip number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 5 digits long';\n }\n addErrorIndication(str, currentForm);\n } else if (currentForm.id == 'cvv') {\n var str = 'Please enter a CVV number';\n if (currentForm.value.length > 0) {\n str = 'Please enter a number that is exactly 3 digits long';\n }\n addErrorIndication(str, currentForm);\n }\n }\n }\n}", "function validate() {\n let formLeft = document.forms[\"travel-left-form\"];\n let formRight = document.forms[\"travel-right-form\"];\n let destination = formRight[\"destination\"].value;\n let start = formLeft[\"start_date\"].value;\n let end = formRight[\"end_date\"].value;\n let origin = formLeft[\"origin\"].value;\n let price = formLeft[\"price_limit\"].value;\n let passengers = formRight[\"passengers\"].value;\n let successful = true;\n let today = new Date();\n // Set today's time to midnight\n today.setHours(0,0,0,0);\n\n // Check if the user entered a destination\n if (!destination) {\n $(\".destination-error\").show();\n successful = false;\n }\n\n // Check if the user entered an origin\n if (!origin) {\n $(\".origin-error\").show();\n successful = false;\n }\n\n // Check if the start or end dates are null\n if (!start || !end) {\n $(\".start-error\").show();\n $(\".end-error\").show();\n successful = false;\n }\n // Check if departure date is <= arrival date and that departure date is\n // no earlier than today's date\n else {\n // Add 1 day to the dates because Javascript is weird\n let startDate = new Date(start);\n startDate.setDate(startDate.getDate() + 1);\n let endDate = new Date(end);\n endDate.setDate(endDate.getDate() + 1);\n\n if (startDate > endDate || startDate < today) {\n $(\".start-error\").show();\n $(\".end-error\").show();\n successful = false;\n }\n }\n\n // Check if the price is at least 0\n if (!price || price < 0) {\n $(\".price-error\").show();\n successful = false;\n }\n // Check if the number of passengers is at least 1\n if (!passengers || passengers < 1) {\n $(\".passengers-error\").show();\n successful = false;\n }\n // Successfully validated, so submit the form\n if (successful) {\n // Hide any errors\n $(\".form-error\").hide();\n submit();\n }\n }", "function processForm(e) {\n if (e.preventDefault) e.preventDefault();\n var num1 = document.getElementById('num1').value;\n var num2 = document.getElementById('num2').value;\n var num3 = document.getElementById('num3').value;\n var num4 = document.getElementById('num4').value;\n generateTable(num1, num2, num3, num4);\n return false;\n}", "function calculateSheets(calcLength, calcWidth) {\n //Set the first parameter the value of the length input field\n calcLength = drywallForm.wallLength.value;\n\n //Parse the length to a float\n parseFloat(calcLength);\n\n //Set the second parameter to the value of the width input field\n calcWidth = drywallForm.wallWidth.value;\n\n //Parse the width to a float\n parseFloat(calcWidth);\n\n //If these conditions fail, return and focus on the proper field.\n if (calcLength <= 0 || calcLength === null || calcLength === undefined || calcLength === \"\" || isNaN(calcLength)) {\n\n //Focus on the length input field\n focus(drywallForm.wallLength);\n\n //Change the background color to pink\n drywallForm.wallLength.style.backgroundColor = \"pink\";\n\n //Stop the form from sending\n return;\n\n //If these conditions also fail,\n } else if ( calcWidth <= 0 || calcWidth === null || calcWidth === undefined || isNaN(calcWidth)) {\n\n //Focus on the width input field\n focus(drywallForm.wallWidth);\n\n //Set the width input field background color to pink\n drywallForm.wallWidth.style.backgroundColor = \"pink\";\n\n //Stop the form from sending\n return;\n\n //If it passes those conditions,\n } else {\n //Calculate the square footage of the wall\n var wallSqFootage = (calcLength * calcWidth);\n console.log(`${wallSqFootage}sqFt`);\n\n //Calculate the amount of sheets needed\n var amountOfSheets = wallSqFootage / 32;\n console.log(`${amountOfSheets} sheets`);\n\n //Hard coded string with amount of sheets needed\n var sheetString = `${Math.ceil(amountOfSheets)} sheets of drywall are needed for this wall`;\n\n //Display the hidden <div></div>\n hiddenContent.style.display = \"inline\";\n //Set the div's innerHTML to the sheetString\n hiddenContent.innerText = sheetString;\n console.log(sheetString);\n\n //Change the text of the button to \"Refresh\"\n submitBtn.innerHTML = \"Refresh\";\n\n //When the refresh button is clicked, fire the refreshPage() function\n submitBtn.addEventListener(\"click\", refreshPage);\n\n //Refresh the page after 0milliseconds\n function refreshPage() {\n setTimeout(\"location.reload(true);\",0);\n }\n\n //Stop the form from submitting\n return;\n }\n }", "function initiateFormValidation() {\n var $form = $(\"#\" + formID);\n $form.submit(function(e) {\n \t// remove all error stylings\n\t\t$(\".\" + errorClass).removeClass(errorClass);\n\t\t$(\".\" + errorMsgClass).css('display', 'none');\n\n\t\t// get user input\n \tvar distanceInput = getInput(distanceName).val();\n \tvar address1Input = getInput(address1Name).val();\n\n \t// show errors if there are any\n if ((distanceInput.length === 0) || isNaN(distanceInput) || (parseInt(distanceInput) <= 0)){\n \te.preventDefault();\n \tshowError(distanceName);\n }\n if (address1Input.length == 0){\n \te.preventDefault();\t\n \tshowError(address1Name);\n }\n });\n}", "function validateForm(event) {\n // Prevent the browser from reloading the page when the form is submitted\n event.preventDefault();\n\n // Validate that the name has a value\n const name = document.querySelector(\"#name\");\n const nameValue = name.value.trim();\n const nameError = document.querySelector(\"#nameError\");\n let nameIsValid = false;\n\n if (nameValue) {\n nameError.style.display = \"none\";\n nameIsValid = true;\n } else {\n nameError.style.display = \"block\";\n nameIsValid = false;\n }\n\n // Validate that the answer has a value of at least 10 characters\n const answer = document.querySelector(\"#answer\");\n const answerValue = answer.value.trim();\n const answerError = document.querySelector(\"#answerError\");\n let answerIsValid = false;\n\n if (checkInputLength(answerValue, 10) === true) {\n answerError.style.display = \"none\";\n answerIsValid = true;\n } else {\n answerError.style.display = \"block\";\n answerIsValid = false;\n }\n\n // Validate that the email has a value and a valid format\n const email = document.querySelector(\"#email\");\n const emailValue = email.value.trim();\n const emailError = document.querySelector(\"#emailError\");\n const invalidEmailError = document.querySelector(\"#invalidEmailError\");\n let emailIsValid = false;\n\n if (emailValue) {\n emailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n emailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n if (checkEmailFormat(emailValue) === true) {\n invalidEmailError.style.display = \"none\";\n emailIsValid = true;\n } else {\n invalidEmailError.style.display = \"block\";\n emailIsValid = false;\n }\n\n // Validate that the answer has a value of at least 15 characters\n const address = document.querySelector(\"#address\");\n const addressValue = address.value.trim();\n const addressError = document.querySelector(\"#addressError\");\n addressIsValid = false;\n\n if (checkInputLength(addressValue, 15) === true) {\n addressError.style.display = \"none\";\n addressIsValid = true;\n } else {\n addressError.style.display = \"block\";\n addressIsValid = false;\n }\n\n // Display form submitted message if all fields are valid\n if (\n nameIsValid === true &&\n answerIsValid === true &&\n emailIsValid === true &&\n addressIsValid === true\n ) {\n submitMessage.style.display = \"block\";\n } else {\n submitMessage.style.display = \"none\";\n }\n}", "function processForm() {\n createHighScoreObject();\n if (newHighScore.name && newHighScore.game && newHighScore.score) {\n printToTable();\n $(\".new\").css('display', 'none');\n $(\".old\").css('display', 'inline-block');\n }\n}", "function displayResult (changesObj,arr){\r\n if(changesObj['status'] === 'OPEN'){\r\n document.getElementById(\"contOp\").style.visibility = 'visible';\r\n document.getElementById(\"pOutput\").innerHTML =\r\n `<b style=\"color:darkgreen\">Open register.</br> Return ${displayChanges(changesObj['change'])}</b></br>\r\n <b style=\"color:darkgreen;\">Transaction Successful!</b>`;\r\n //Set new values to read-only fields\r\n document.getElementById(\"pennyNew\").value = Math.round(arr[0][1] / 0.01);\r\n document.getElementById(\"nickelNew\").value = Math.round(arr[1][1] / 0.05);\r\n document.getElementById(\"dimeNew\").value = Math.round(arr[2][1] / 0.1);\r\n document.getElementById(\"quarterNew\").value = Math.round(arr[3][1] / 0.25);\r\n document.getElementById(\"oneNew\").value = Math.round(arr[4][1] / 1);\r\n document.getElementById(\"fiveNew\").value = Math.round(arr[5][1] / 5);\r\n document.getElementById(\"tenNew\").value = Math.round(arr[6][1] / 10);\r\n document.getElementById(\"twentyNew\").value = Math.round(arr[7][1] / 20);\r\n document.getElementById(\"oneHundredNew\").value = Math.round(arr[8][1] / 100);\r\n }\r\n else{\r\n document.getElementById(\"contOp\").style.visibility = 'hidden';\r\n\r\n if(changesObj['status'] === 'INSUFFICIENT_FUNDS'){\r\n document.getElementById(\"pOutput\").innerHTML = `<b style=\"color:darkred;\">Transaction Failed! Insufficient Funds!</b>`;\r\n }\r\n else if (changesObj['status'] === 'CLOSED'){\r\n document.getElementById(\"pOutput\").innerHTML =\r\n `<b style=\"color:darkgreen\">Open register</br> Return ${displayChanges(changesObj['change'])}</b></br>\r\n <b style=\"color:brown;\">Transaction Completed! Register Closed! All changes spent!</b>`;\r\n document.getElementById(\"pennyNew\").value = 0;\r\n document.getElementById(\"nickelNew\").value = 0;\r\n document.getElementById(\"dimeNew\").value = 0;\r\n document.getElementById(\"quarterNew\").value = 0;\r\n document.getElementById(\"oneNew\").value = 0;\r\n document.getElementById(\"fiveNew\").value = 0;\r\n document.getElementById(\"tenNew\").value = 0;\r\n document.getElementById(\"twentyNew\").value = 0;\r\n document.getElementById(\"oneHundredNew\").value = 0;\r\n }\r\n else if (changesObj['status'] === 'INSUFFICIENT_CASH'){\r\n document.getElementById(\"pOutput\").innerHTML =\r\n `<b style=\"color:darkred\">Transaction Failed! Insuffient cash given!</b>`;\r\n document.getElementById(\"pennyNew\").value = document.getElementById(\"penny\").value;\r\n document.getElementById(\"nickelNew\").value = document.getElementById(\"nickel\").value;\r\n document.getElementById(\"dimeNew\").value = document.getElementById(\"dime\").value;\r\n document.getElementById(\"quarterNew\").value = document.getElementById(\"quarter\").value;\r\n document.getElementById(\"oneNew\").value = document.getElementById(\"one\").value;\r\n document.getElementById(\"fiveNew\").value = document.getElementById(\"five\").value;\r\n document.getElementById(\"tenNew\").value = document.getElementById(\"ten\").value;\r\n document.getElementById(\"twentyNew\").value = document.getElementById(\"twenty\").value;\r\n document.getElementById(\"oneHundredNew\").value = document.getElementById(\"oneHundred\").value;\r\n }\r\n }\r\n \r\n}", "function formSubmitted(){\n getCurrentNumbers();\n setConfirmationMessage();\n}", "function grades()\n{\n\tvar hwavg, mtexam, finalexam, acravg, finalavg, grade;\n\t\n\tvar errorMessage = \"<span style='color: #000000; background-color: #FF8199;\" + \n\t\t\t\t\t\t\"width: 100px;font-weight: bold; font-size: 14px;'>\" +\n\t\t\t\t\t\t\"Input must be integers between 0 and 100</span>\";\n\n\thwavg = document.forms[\"myform\"].elements[\"hwavg\"].value;\n\tmtexam = document.forms[\"myform\"].elements[\"midterm\"].value;\n\tfinalexam = document.forms[\"myform\"].elements[\"finalexam\"].value;\n\tacravg = document.forms[\"myform\"].elements[\"acravg\"].value;\n\n\thwnum = parseInt(hwavg, 10);\n\tmtnum = parseInt(mtexam, 10);\n\tfinnum = parseInt(finalexam, 10);\n\tacrnum = parseInt(acravg, 10);\n\n\n\tif( isNaN(hwnum) || isNaN(mtnum) || isNaN(finnum) || isNaN(acrnum) || \n\t\thwnum < 0 || mtnum < 0 || finnum < 0 || acrnum < 0 || \n\t\thwnum > 100 || mtnum > 100 || finnum > 100 || acrnum > 100)\n {\n \tdocument.getElementById(\"errorMsg\").innerHTML = errorMessage; \n }\n \telse \n \t{\n\n\t\tfinalavg = (.5 * hwnum) + (.2 * mtnum) + (.2 * finnum) + (.1 * acrnum);\n\n\t\tif(finalavg >= 90) \n\t\t\t{grade = \"A\";}\n\t\telse if (finalavg >= 80 && finalavg < 90) \n\t\t\t{grade = \"B\";}\n\t\telse if (finalavg >= 70 && finalavg < 80) \n\t\t\t{grade = \"C\";}\n\t\telse if (finalavg >= 60 && finalavg < 70) \n\t\t\t{grade = \"D \\nStudent will need to retake the course\";}\n\t\telse if (finalavg < 60)\n\t\t\t{grade = \"F \\nStudent will need to retake the course\";}\n \n \tdocument.forms[\"myform\"].elements[\"result\"].value = ( \"Final Average: \" + finalavg.toFixed(0) +\n \t\t\"\\nFinal Grade: \" + grade);\n }\n\n \n\t\n}", "function calculateFormScore() {\r\n\r\n //higligt selected values from previously submitted entry\r\n $(\"input:hidden[name$='_hidden']\").each(function() { // only chose hidden inputs with postfix _hidden\r\n \r\n // aquire form category\r\n var category = $(this).attr(\"name\");\r\n category = category.replace(\"_hidden\", \"\");\r\n\r\n // update score calculation overview\r\n var score = 0; // category score\r\n score = roundToDecimalPlace(calculateCategory(category), 2);\r\n var scoreDiv = '#' + category + '_score';\r\n\r\n $(scoreDiv).html(\"Einkunn - \" + score); // display the score on the page\r\n $(scoreDiv).attr(\"data-score\", score); // store the score\r\n \r\n // always finish by calculating current total score\r\n var totalScore = performScoreCalculation();\r\n $('#totalScoreHeader').html(\"Heildarskor - \" + totalScore);\r\n $('input[name=totalScoreHidden]').val(totalScore);\r\n });\r\n }", "function validate(){\n\nvar errMsg = \"\"; /* stores the error message */\nvar result = true; /* assumes no errors */\n\n/*get values from the form*/\n\nvar fName = document.getElementById(\"fname\").value;\nvar lName = document.getElementById(\"lname\").value;\nvar dob = document.getElementById(\"dob\").value;\nvar streetAddr = document.getElementById(\"streetaddr\").value;\nvar suburb = document.getElementById(\"suburb\").value;\nvar postcode = document.getElementById(\"postcode\").value;\nvar phoneNo = document.getElementById(\"phnno\").value;\nvar state = document.getElementById(\"state\").value;\nvar otherSkill = document.getElementById(\"skill\").value;\nvar email = document.getElementById(\"emailid\").value;\nvar skill = document.getElementById(\"skill\").value;\n\n/*get status from the form*/\n\nvar microsoftOffice = document.getElementById(\"microsoftoffice\").checked;\nvar touchTyping = document.getElementById(\"touchtyping\").checked;\nvar documentationSkill = document.getElementById(\"documentationskill\").checked;\nvar web = document.getElementById(\"web\").checked;\nvar dotNet = document.getElementById(\"dotnet\").checked;\nvar java = document.getElementById(\"java\").checked;\nvar otherSkills = document.getElementById(\"otherskills\").checked;\n\n/*store value in the variable*/\nvar letter = /^[A-Za-z]+$/;\nvar number = /^[0-9]+$/;\nvar date = dob.split(\"/\");\n\n/*Validate first name */\n\nif(fName.match(letter)){ /*for alphabet*/\nif((fName.length) <= 15){ /*for length*/\n}else{\nerrMsg =errMsg.concat(\"First Name Should not contain more than 15 characters!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"First Name Should contain only alphabets!\\n\");\nresult = false;\n}\n\n/*Validate Second name*/\n\nif(lName.match(letter)){ /*for alphabet*/\nif((lName.length) <= 25){ /*for length*/\n}else{\nerrMsg =errMsg.concat(\"Last Name Should not contain more than 25 characters!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"Last Name Should contain only alphabets!\\n\");\nresult = false;\n}\n\n/*Validate date*/\n\n\tif(date[0] <=31 && date[0] >= 1 && date[1] >= 1 && date[1] <= 12 && date[2] >= 1 && date[2] <= 2014 ){\t\t\n\t}else{errMsg +=\"Wrong date.\\n\";\n\t\tresult = false;}\n\t\t\n/*Validate Adders*/\n\nif((streetAddr.length) > 50){ /*for length*/\nerrMsg =errMsg.concat(\"Street Address should not contain for than 50 characters.\\n\");\nresult = false;\n}\n\nif((suburb.length) > 25){ /*for length*/\nerrMsg =errMsg.concat(\"Suburb/Town Address should not contain for than 25 characters.\\n\");\nresult = false;\n}\n\nif(postcode.match(letter)){ /*for letter*/\nerrMsg = errMsg.concat(\"postcode must be integer.\\n\");\nresult = false;\n\n}\n\nif((postcode.length) != 4){ /*for length*/\nerrMsg = errMsg.concat(\"postcode should contain exactly 4 characters .\\n\");\nresult = false;\n}\n\n/*Now validate state and postcode depending upon the first digit entered in postcode*/\n\nif(state == \"vic\"){\nif(postcode[0] == 3 || postcode[0] == 8){\n}else\n{errMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;}\n}\n\n\nif(state == \"nsw\"){\nif(postcode[0] == 1 || postcode == 2){\n}else{\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\n\nif(state == \"qld\"){\nif(postcode[0] == 4 || postcode[0] == 9){\n}else{\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\nif(state == \"nt\" || state == \"act\"){\nif(postcode[0] != 0){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one\\n\");\nresult = false;\n}\n}\n\nif(state == \"wa\"){\nif(postcode[0] != 6){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nif(state == \"sa\"){\nif(postcode[0] != 5){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nif(state == \"tas\"){\nif(postcode[0] != 7){\nerrMsg = errMsg.concat(\"Wrong Postcode or state select the correct one!\\n\");\nresult = false;\n}\n}\n\nemailFormat = /^[A-Za-z]+@[A-Za-z]+.[A-Za-z]+$/;\nif(email.match(!(emailFormat))){\nerrMsg = errMsg.concat(\"Wrong email!\\n\");\nresult = false;\n}\n\n\nif(phoneNo.match(number)){\nif((phoneNo.length) == 10){\n}else{\nerrMsg =errMsg.concat(\"Phone Number Should contain 10 digits!\\n\");\nresult = false;\n}\n}else{\nerrMsg =errMsg.concat(\"Phone No should not contain alphabets!\\n\");\nresult = false;\n}\n\nif(!microsoftOffice && !touchTyping && !documentationSkill && !web && !dotNet && !java && !otherSkills)\n{\nerrMsg = errMsg.concat(\"At-least select 1 skill!\\n\");\nresult = false;\n}\n\nif(otherSkills == true){\nif(skill.trim().length < 1 ){\nerrMsg = errMsg.concat(\"Please type other skills possessed by you in text area\\n\");\nresult = false;\n\n}\n}\n\n/*if conditions not matched then execute this */\n\nif (result == false){\nalert(errMsg);\n}\n\nreturn result;\n}", "function validForm(...results) {\n let result = true;\n console.log('checking if the form is valid');\n results.forEach((cur) => {\n // console.log(cur.length);\n if (cur.length < 3) {\n console.log(`${cur} is not valid`);\n result = false;\n }\n });\n return result;\n }", "function computeBMI() {\r\n clearAll(true);\r\n\r\n // obtain user inputs\r\n var height = Number(document.getElementById(\"height\").value);\r\n var weight = Number(document.getElementById(\"weight\").value);\r\n var unittype = document.getElementById(\"unittype\").selectedIndex;\r\n\r\n if (height === 0 || isNaN(height) || weight === 0 || isNaN(weight)) {\r\n setAlertVisible(\"error-bmi-output\", ERROR_CLASS, true);\r\n document.getElementById(\"error-bmi-output\").innerHTML = errorString;\r\n } else { // convert\r\n // Perform calculation\r\n var BMI = calculateBMI(height, weight, unittype);\r\n\r\n // Display result of calculation\r\n var result = \" Your BMI index are <strong>\" + BMI + \"</strong>.\";\r\n var warning = true;\r\n if (BMI < BMI_LOWINDEX)\r\n result = \"<strong>Underweight!!</strong>\" + result + \" C'mon, McDonald is near by then.\";\r\n else if (BMI >= BMI_LOWINDEX && BMI <= BMI_HIGHINDEX) {\r\n warning = false;\r\n result = \"<strong>Normal!</strong>\" + result + \" Good exercises!\";\r\n }\r\n else // BMI > 25\r\n result = \"<strong>Overweight!!!</strong>\" + result + \" Recreation center welcome you !!\";\r\n\r\n // if we need to show warning so we show alert with warning, otherwise we show success message.\r\n if (warning) {\r\n setAlertVisible(\"warning-bmi-output\", WARNING_CLASS, true);\r\n document.getElementById(\"warning-bmi-output\").innerHTML = result;\r\n } else {\r\n setAlertVisible(\"normal-bmi-output\", SUCCESS_CLASS, true);\r\n document.getElementById(\"normal-bmi-output\").innerHTML = result;\r\n }\r\n }\r\n}", "function validation() {\t\t\t\t\t\r\n\t\t\t\t\tvar frmvalidator = new Validator(\"app2Form\");\r\n\t\t\t\t\tfrmvalidator.EnableOnPageErrorDisplay();\r\n\t\t\t\t\tfrmvalidator.EnableMsgsTogether();\r\n\r\n\t\t\t\t\tif (document.getElementById('reasonForVisit').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitPatientReason\",\"req\",\"Please enter your reason For Visit\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitPatientReason_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (document.getElementById('visitYes').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitNewpatient\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\tif (document.getElementById('visitNo').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"visitNewpatient\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitNewpatient_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visitPrDocYes').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"hasPhysian\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\tif (document.getElementById('visitPrDocNo').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"hasPhysian\",\"selone\",\"Please select an option 'Yes or No'\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_hasPhysian_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('emailAddress').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitEmail\",\"req\", \"Email is required\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitEmail\",\"email\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitEmail_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientFirstName').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientFirstName\",\"req\",\"Please enter your First Name\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientFirstName_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientLastName').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientLastName\",\"req\",\"Please enter your Last Name\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientLastName_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('pdob').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"pdob\",\"\",\"DOB is required\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_pdob_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('phoneNumber').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"req\",\"Phone Number is required\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"numeric\",\"numbers only\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientPhoneNumber\",\"minlen=10\",\"not enough numbers\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientPhoneNumber_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visitGender').value==\"0\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"visitGender\",\"dontselect=0\",\"Please select an option 'Male or Female'\");\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_visitGender_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('patientZipCode').value==\"\"){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"numeric\",\"numbers only\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"minlen=5\",\"not a valid zipcode\");\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"patientZipCode\",\"req\",\"zip code is required\");\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_patientZipCode_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (document.getElementById('visit_terms_911').checked==false){\r\n\t\t\t\t\t\tfrmvalidator.addValidation(\"agreeTerms\",\"selmin=2\",\"please check all boxes to continue\");\r\n\t\t\t\t\t\tif (document.getElementById('visit_custom_terms').checked==false){\r\n\t\t\t\t\t\t\tfrmvalidator.addValidation(\"agreeTerms\",\"selmin=2\",\"please check all boxes to continue\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else {\r\n\t\t\t\t\t\tdocument.getElementById('app2Form_agreeTerms_errorloc').innerHTML=\"\"; // CLEARING THE error message\r\n\t\t\t\t\t}\r\n \r\n}", "function validateForm() {\r\n var YES_RADIO_VALUE = 0;\r\n var NO_RADIO_VALUE = 1;\r\n\r\n // check if all fences have been checked yes or no\r\n $(\"input[name^=fence_\").each(function() {\r\n fenceIsChecked = $(this).is(\"checked\"); // is the fence radio button checked?\r\n\r\n // fences are mandatory\r\n if (fenceIsChecked == false) {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara Já eða Nei í öllum girðingum!</p>\");\r\n return false;\r\n }\r\n });\r\n\r\n // all evaluation questions have to be answered but only if all fences have been passed\r\n if(passesFences() == true) {\r\n\r\n var evaluationValue;\r\n $(\"input:hidden[name$='_hidden']\").each(function() {\r\n evaluationValue = $(this).attr(\"value\");\r\n if (evaluationValue == null || evaluationValue == \"\" || evaluationValue == \" \") {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara öllum matsspurningum</p>\");\r\n return false;\r\n }\r\n });\r\n\r\n var review = document.forms[\"EvaluationPaper\"][\"review\"].value;\r\n\r\n // review is mandatory\r\n if (review == null || review == \"\" || review == \" \") {\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Það þarf að skrifa texta í reit fyrir mat!</p>\");\r\n return false;\r\n }\r\n\r\n // propose_acceptance is mandatory\r\n var propose_acceptance = document.forms[\"EvaluationPaper\"][\"propose_acceptance\"].value;\r\n if (propose_acceptance == null || propose_acceptance == \"\" || propose_acceptance == \" \"){\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara hvort að mælt sé með að umsókn verði styrkt!</p>\");\r\n return false;\r\n }\r\n\r\n // proposal_discussion is mandatory\r\n var proposal_discussion = document.forms[\"EvaluationPaper\"][\"proposal_discussion\"].value;\r\n if (proposal_discussion == null || proposal_discussion == \"\" || proposal_discussion == \" \"){\r\n $(\"#form_field_error\").html(\"<p style='color:red'>Verður að svara hvort að matsmaður vilji að umsóknin verði rædd á matsfundi</p>\");\r\n return false;\r\n }\r\n }\r\n\r\n $(\"#form_field_error\").html(\" \");\r\n return true;\r\n }", "function validation() {\r\n\t\tif ((circleRecipe.checked == true && recipeCircleArea() > 0) || (rectangleRecipe.checked == true && returnValue(lengthARecipe) > 0 && returnValue(lengthBRecipe) > 0)) {\r\n\t\t\tif ((circleUser.checked == true && userCircleArea() > 0) || (rectangleUser.checked == true && returnValue(lengthAUser) > 0 && returnValue(lengthBUser) > 0)) {\r\n\t\t\t\tconvertAlert.innerHTML = '';\r\n\t\t\t\tconvert();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tconvertAlert.innerHTML = '<p>You must define what kind of baking mold you use and inscribe its dimensions before convert!</p>';\r\n\t\t\t}\r\n\t\t}\r\n\t\telse {\r\n\t\t\tconvertAlert.innerHTML = '<p>You must define what kind of baking mold is used in the recipe and inscribe its dimensions before convert!</p>';\r\n\t\t}\r\n\t}", "function formSubmit(){\r\n // find all the input field\r\n // if the field's value is null give a thief warning and set the errorCount's value isn't 0\r\n var inputs = document.getElementsByTagName(\"input\");\r\n for(var i = 0; i < inputs.length; i += 1){\r\n var onblur = inputs[i].getAttribute(\"onblur\");\r\n if(onblur != null){\r\n if(inputs[i].value == \"\" || inputs[i].value == null){\r\n var errorType = onblur.split(\",\")[1].substring(2, onblur.split(\",\")[1].lastIndexOf(\")\") - 1);\r\n var configId = 0;\r\n for(var j = 0; j < validateConfig.length; j += 1){\r\n if(errorType == validateConfig[j].name){\r\n configId = j;\r\n }\r\n }\r\n var warning = inputs[i].parentNode.nextElementSibling || inputs[i].parentNode.nextSibling;\r\n var borderStyle = errorStyle[0];\r\n inputs[i].style.border = borderStyle.style;\r\n warning.innerHTML = validateConfig[configId].message;\r\n warning.style.color = \"red\";\r\n errorCount =+ 1;\r\n }\r\n }\r\n }\r\n \r\n if(errorCount > 0){\r\n var thief = document.getElementById(\"thief_warning\");\r\n thief.style.color = \"red\";\r\n thief.innerHTML = \"You must finish all the field...\";\r\n return false;\r\n } else {\r\n return true;\r\n }\r\n}", "function formValidator(d) {\nd.preventDefault();\n\t// Create 2 empty 'buckets', one for collecting data and \n\t// the other for error-messages\n\tlet data = {};\n// data.prop = 'Test property';\n\tlet errors = [];\n\t\n\t// 1. Validating fullname\n\tif (fn.value) {\n\t\tdata.fullname = fn.value;\n\t} else {\n\t\terrors.push('First name has to be added!');\n\t}\n\t\n\t// 2. Validating email\n\t\n \tif (em.value) {\n if (pattern.test(em.value)) { \n\t\t\n \n \n data.email = em.value;\n\t} else {\n error.push('Invalid email!');\n }\n \n \n } else {\n\t\terrors.push('Email has to be added!');\n\t}\n\t\n // 1. Validating email\n\tif (msg.value) {\n\t\tdata.message = msg.value;\n\t} else {\n\t\terrors.push('Message has to be added!');\n\t}\n \n \n \n \n\t// 3. Handle the feedback\n if (errors.length === 0)\n\t{\n// Print the data obect inside the console \nconsole.log(data);\n\n document.getElementById(\"htmlform\").reset();\n }\n else {\nconsole.log(errors); \n }\n\n \n\n}", "function calculate() {\r\n\t//get initial input data\r\n\tmaxScore = document.getElementById(\"maxScore\");\r\n\tstudentScore = document.getElementById(\"studentScore\");\r\n\t//make sure the input is valid\r\n\tif (isNaN(maxScore.value) || isNaN(studentScore.value) || maxScore.value == \"\" || studentScore.value == \"\") {\r\n\t\talert(\"You must enter numbers only, and all fields must be filled.\");\r\n\t}\r\n\telse {\r\n\t\t//update decimal spaces\r\n\t\tvar selector = document.getElementById(\"decimalChooser\");\r\n\t\tdecimalSpaces = selector.options[selector.selectedIndex].value;\r\n\t\t//display the result\r\n\t\tpercentScore = roundTo((studentScore.value/maxScore.value)*100,decimalSpaces);\r\n\t\tdocument.getElementById(\"results\").innerHTML = \"Percent Score: \" + percentScore + \"%\";\r\n\t\tdocument.getElementById(\"operation\").innerHTML = \"( \" + studentScore.value + \" / \" + maxScore.value + \" )\"\r\n\t\t//update score array\r\n\t\tscores.unshift(percentScore);\r\n\t\t//update previous scores\r\n\t\tupdatePreviousScores();\r\n\t\t//update the score count display\r\n\t\tdocument.getElementById(\"scoreCounter\").innerHTML = scores.length.toString();\r\n\t\t//reset the student score\r\n\t\tstudentScore.value = null;\r\n\t\t//calculate stats\r\n\t\tcalculateStats(scores);\r\n\t\t//display or dont display the stats values based on whether the user has toggled them shown or hidden\r\n\t\tif (statsShown) {\r\n\t\t\tdisplayStats();\r\n\t\t}\r\n\t}\r\n}", "function processEntries() {\n\tlet investmentValue = parseFloat($('investment').value);\n\tlet rate = parseFloat($('rate').value);\n\tlet years = parseFloat($('years').value);\n\tlet errorMessage;\n\tif (!$('investment').value || !$('rate').value || !$('investment').value) {\n\t\talert(\"All fields are required\");\n\t}\n\telse if(isNaN(investmentValue) || isNaN(rate) || isNaN(years)) {\n\t\talert(\"All entries must be numeric\");\n\t}\n\telse if \t(investmentValue <= 0 || investmentValue > 100000){\n\t\terrorMessage = \"Investment must be a number greater than 0 and less than or equal to 100,000.\"\n\t\talert(errorMessage);\n\t\t$('investment').focus();\n\t}\n\telse if (rate <= 0 || rate > 15) {\n\t\terrorMessage = \"Investment rate must be greater than 0 and less than or equal to 15%.\"\n\t\talert(errorMessage);\n\t\t$('rate').focus();\n\t}\n\telse if (years <= 0 || years > 50 || years % 1 !== 0) {\n\t\terrorMessage = \"Number of years must be a positive integer of 50 or less\";\n\t\talert(errorMessage);\n\t\t$('years').focus();\n\t}\n\telse {\n\t\tfuture_value.value = calculateFV(investmentValue, rate, years).toFixed(2);\n\t}\t\n}", "function formSubmitDataEntry() {\r\n\t// Disable the onbeforeunload so that we don't get an alert before we leave\r\n\twindow.onbeforeunload = function() { }\r\n\t// Before finally submitting the form, execute all calculated fields again just in case someone clicked Enter in a text field\r\n\tcalculate();\r\n\t// REQUIRED FIELDS: Loop through table and remove form elements from html that are hidden due to branching logic \r\n\t// (so user is not prompted to enter values for invisible fields).\r\n\t$(\"#form_table tr\").each(function() {\r\n\t\t// Is it a required field?\r\n\t\tif ($(this).attr(\"req\") != null) {\r\n\t\t\t// Is the req field hidden (i.e. on another survey page)?\r\n\t\t\tif ($(this).css(\"display\") == \"none\") {\r\n\t\t\t\t// Only remove field from form if does not already have a saved value (i.e. has 'hasval=1' as row attribute)\r\n\t\t\t\tif ($(this).attr(\"hasval\") != \"1\") {\r\n\t\t\t\t\t$(this).html('');\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t});\r\n\t// For surveys only\r\n\tif (page == 'surveys/index.php') {\r\n\t\t// If using \"save and return later\", append to form action to point to new place\r\n\t\tif ($('#submit-action').val() == \"submit-btn-savereturnlater\") {\r\n\t\t\t$('#form').attr('action', $('#form').attr('action')+'&__return=1' );\r\n\t\t}\r\n\t\t// If using \"previous page\" button, append to form action to point to new place\r\n\t\tif ($('#submit-action').val() == \"submit-btn-saveprevpage\") {\r\n\t\t\t$('#form').attr('action', $('#form').attr('action')+'&__prevpage=1' );\r\n\t\t}\r\n\t}\r\n\t// Disable all buttons on page when submitting to prevent double submission\r\n\tsetTimeout(function(){ $('#form :button').prop('disabled',true); },10);\r\n\t// Submit form (finally!)\r\n\tdocument.form.submit();\r\n}", "function form_verify_result(same_hash) {\n const result_div = document.getElementById('verify_form_result');\n const form = document.getElementById('form_verify');\n const diplom = form.diplom.value.split(' --- ')[0];\n if (same_hash) {\n if (result_div.classList.contains('alert-danger')) {\n result_div.classList.remove('alert-danger');\n result_div.classList.add('alert-success');\n }\n result_div.innerHTML = `${form.student_name.value} has been certified to be \"${diplom}\" on ${form.awarding_year.value}`;\n } else {\n if (result_div.classList.contains('alert-success')) {\n result_div.classList.remove('alert-succes');\n result_div.classList.add('alert-danger');\n }\n result_div.innerHTML = `${form.student_name.value} has not been certified to be \"${diplom}\". Please double check the inputs.`; \n }\n result_div.style.display = 'block';\n}", "function CheckInputs(){\n //get values from inputs and gets rid of spaces\n const emailValue = email.value.trim();\n const subjectValue = subject.value.trim();\n const messageValue = message.value.trim();\n\n //used to check if form is valid. if by then end it doesnt equlat three then return false\n var score = 0;\n\n //CHECK EMAIL\n //checks if email is empty\n if(emailValue ===''){\n SetErrorFor(email,'Email can not be blank');\n }\n //checks if email is correct form\n else if(!IsEmail(emailValue)){\n SetErrorFor(email,'Email is not valid');\n }\n\n else{\n SetSuccessFor(email);\n score+=1;\n }\n\n //CHECK SUBJECT\n //checks if subject is empty\n if(subjectValue ===''){\n SetErrorFor(subject,'Subject can not be blank');\n }\n else{\n SetSuccessFor(subject);\n score+=1;\n }\n\n //CHECK MESSAGE\n //checks if subject is empty\n if(messageValue ===''){\n SetErrorFor(message,'Message can not be blank');\n }\n else{\n SetSuccessFor(message);\n score+=1;\n }\n\n if(score===3){\n return true;\n }\n\n else{\n return false;\n }\n\n \n}", "function formValidation(user_name, last_Name, user_email, user_password, user_confirm_password){ \n var user_name = getInputVal(\"firstName\");\n var last_Name = getInputVal(\"userLastName\");\n var user_email = getInputVal(\"userEmail\"); \n var user_password = getInputVal(\"user_Password\");\n var user_confirm_password = getInputVal(\"user_Confirm_Password\"); \n\n if(user_name) {\n document.getElementById(\"firstNameError\").innerHTML = \"\"; \n }\n if(last_Name) {\n document.getElementById(\"firstLastError\").innerHTML = \"\"; \n }\n if(user_email) {\n document.getElementById(\"firstEmailError\").innerHTML = \"\"; \n }\n if(user_password) {\n document.getElementById(\"password_Error\").innerHTML = \"\"; \n }\n if(user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\"; \n }\n else if(user_password != user_confirm_password) {\n document.getElementById(\"confirm_password_Error\").innerHTML = \"\";\n }\n }", "function displayResults() {\n var res = \"\";\n if (sStatement.length > 0 ) {\n res += \"Successfully posted: \" + sStatement + \"\\n\";\n }\n if (fStatement.length > 0 ) {\n res += \"Unsuccessfully posted: \" + fStatement;\n }\n\n nDlg.show($scope, res)\n .then(function() {\n $state.go(\"term-edit\", {id : $scope.termID});\n });\n }", "function calculate() {\n\t\t\tlet age = document.getElementById(\"inputAge\").value;\n let sex = document.getElementById(\"selectSex\").value;\n let pregnantOrLactating = document.getElementById(\"selectPregnantLactating\").value;\n\t\t\tlet height = document.getElementById(\"inputHeight\").value;\n let weight = document.getElementById(\"inputWeight\").value;\n let lifestyle = document.getElementById(\"selectLifestyle\").value;\n\n //Inicializing activity coeficient (which depend of user's sex) and required calories (which depends of user's age, height, weight, sex, pregnant or lactating and activity)\n let activity = 0;\n let reqCalories = 0; \n\n //Checking if the form is filled\n\t\t\tif (age === \"\" || sex === \"\") {\n\t\t\t\tdocument.getElementById(\"messageFillIn2\").innerHTML = \"Please fill in the required fields.\";\n }\n \n else if ((height === \"\" || weight === \"\") || lifestyle === \"\") {\n\t\t\t\tdocument.getElementById(\"messageFillIn2\").innerHTML = \"Please fill in the required fields.\";\n }\n\n else if (age < 18) {\n document.getElementById(\"messageFillIn2\").innerHTML = \"This app is not for users under 18 years\"; \n }\n\n //If the form is filled, calculate\n else { \n scrollTo(0,0); \n document.getElementById(\"divPersonalInfo\").style.display = \"none\";\n document.getElementById(\"divDailyRequirement\").style.display = \"block\";\n\n //Calculating calories and daily nutrient requirements\n if (sex === \"male\") {\n //Calculating activity coeficient and required daily calories\n switch (lifestyle) {\n case \"sedentary\":\n activity = 1;\n break;\n case \"littleActive\":\n activity = 1.11;\n break;\n case \"active\":\n activity = 1.25;\n break;\n case \"veryActive\":\n activity = 1.48;\n break;\n }\n\n reqCalories = 662 - (9.53 * age) + activity * ( (15.91 * weight) + (539.6 * height / 100) );\n\n //Asigning age specific nutrient requirements for male users\n if (18 <= age <= 30) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq18\"];\n }\n else if (31 <= age <= 50) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq31\"];\n }\n else if (51 <= age <= 70) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq51\"];\n }\n else if (age >= 71) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"maleReq71\"];\n }\n }\n\n else if (sex === \"female\") {\n //Calculating activity coeficient and required daily calories\n switch (lifestyle) {\n case \"sedentary\":\n activity = 1;\n break;\n case \"littleActive\":\n activity = 1.12;\n break;\n case \"active\":\n activity = 1.27;\n break;\n case \"veryActive\":\n activity = 1.45;\n break;\n }\n\n reqCalories = 354 - (6.91 * age) + activity * ( (9.36 * weight) + (726 * height / 100) );\n \n //Calculating calories & nutrient requirements when the user is pregnant or lactating\n if (pregnantOrLactating !== \"\") {\n switch (pregnantOrLactating) {\n case \"pregnant2\":\n reqCalories += 340;\n break;\n case \"pregnant3\":\n reqCalories += 452;\n break;\n case \"lactating1\":\n reqCalories += 330;\n break;\n case \"lactating2\":\n reqCalories += 400;\n break;\n }\n\n switch (pregnantOrLactating) {\n case \"pregnant1\":\n case \"pregnant2\":\n case \"pregnant3\":\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femalePregnant\"];\n break;\n case \"lactating1\":\n case \"lactating2\":\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleLactating\"];\n break;\n }\n }\n else {\n //Asigning age specific nutrient requirements for female users\n if (18 <= age <= 30) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq18\"];\n }\n else if (31 <= age <= 50) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq31\"];\n }\n else if (51 <= age <= 70) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq51\"];\n }\n else if (age >= 71) {\n userNutReq = USERS_NUTRIENT_REQUIRMENTS[\"femaleReq71\"];\n }\n } \n }\n\n //Adding calories property to user's object with nutrient requrements\n userNutReq[\"reqCalories\"] = reqCalories.toFixed(0);\n \n //Filling the table \"Daily Requirement\"\n let tableReq = document.getElementById(\"tableDailyRequirement\");\n let cellReqId = \"\";\n\n for (let rowIndex = 0; rowIndex < tableReq.rows.length; rowIndex++) {\n if (rowIndex == 6 || rowIndex == 19) {\n }\n else {\n cellReqId = tableReq.rows.item(rowIndex).cells[1].id;\n tableReq.rows.item(rowIndex).cells[1].innerHTML = userNutReq[cellReqId];\n }\n }\n }\n \n\t\t}" ]
[ "0.7274176", "0.6891208", "0.68455535", "0.6758833", "0.6714852", "0.667124", "0.66194046", "0.66145086", "0.65784657", "0.6570059", "0.6562505", "0.6532438", "0.651918", "0.6418197", "0.63812256", "0.63282543", "0.63188857", "0.6238029", "0.62064457", "0.6204553", "0.6203649", "0.6202043", "0.6191681", "0.6139745", "0.61294913", "0.61236334", "0.6083613", "0.6082501", "0.60751194", "0.607359", "0.6073357", "0.60715157", "0.6063344", "0.60597736", "0.6056396", "0.60555935", "0.6041951", "0.6041504", "0.6038071", "0.6022456", "0.60066", "0.6006573", "0.5998492", "0.5988126", "0.5982344", "0.59791726", "0.59782976", "0.5952696", "0.5939496", "0.59379596", "0.59277976", "0.59273434", "0.59270114", "0.592596", "0.59093904", "0.5907424", "0.5899723", "0.589529", "0.58897483", "0.5888323", "0.58872277", "0.58806866", "0.5879133", "0.58754283", "0.58743817", "0.5868597", "0.5861555", "0.5860177", "0.5854271", "0.58522874", "0.58508486", "0.5842437", "0.583029", "0.5822253", "0.5820397", "0.5813824", "0.581273", "0.58091265", "0.58036625", "0.5802856", "0.5801582", "0.5799394", "0.57981", "0.579717", "0.5792508", "0.57906026", "0.57861954", "0.57794726", "0.57778543", "0.5773654", "0.57706654", "0.5768887", "0.5764719", "0.57557154", "0.5755487", "0.57547176", "0.5752647", "0.57492256", "0.5748726", "0.5746764" ]
0.7807186
0
add getters to be able redraw item on scroll
get parentTop () { return self.parentRect.top }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "update() {\n\t\tthis.scroll.update();\n\t}", "updateData() {\n this._heightSetter.style.height = this.students.length * ITEM_HEIGHT + 'px';\n this._hideItems();\n this.changeFocus(null)\n }", "onScroll_() {\n const scrollTop = this.scrollTop;\n if (scrollTop > 0 && this.instances_.length !== this.items.length) {\n if (this.fillViewHeight_(scrollTop + this.maxHeight)) {\n this.updateHeight_();\n }\n }\n }", "cacheItems() {\n this.items = getDirectChildren(this.slider);\n }", "get [scrollTarget]() {\n return this[ids].grippedContent;\n }", "get scrolledIntoView() {\n return (this.updated & UPDATED_SCROLL) > 0;\n }", "componentDidUpdate () {\n this.setHeight();\n this.scrollList();\n }", "elementScrolled() {\n return this._elementScrolled;\n }", "onItemsChanged_() {\n if (this.domRepeat_ && this.items) {\n const domItemAvgHeight = this.domItemAverageHeight_();\n const aboveScrollTopItemCount = domItemAvgHeight !== 0 ?\n Math.round(this.$.container.scrollTop / domItemAvgHeight) :\n 0;\n\n this.domRepeat_.set('items', []);\n this.ensureDomItemsAvailableStartingAt_(aboveScrollTopItemCount);\n this.updateScrollerSize_();\n }\n }", "get _itemHeight() {\n return this._list.selectedItem.clientHeight;\n }", "_refreshLayout() {\n const that = this;\n const source = that._items;\n\n that.__scrollHeight = null;\n that.__scrollWidth = null;\n that._height = null;\n\n if (!that._scrollView) {\n that._scrollView = new JQX.Utilities.Scroll(that, that.$.horizontalScrollBar, that.$.verticalScrollBar);\n }\n\n that.$itemsContainer.removeClass('hscroll');\n that.$itemsContainer.removeClass('vscroll');\n\n if (!source || source === null || source.length === 0) {\n that.scrollWidth = 0;\n that.scrollHeight = 0;\n that.$filterInputContainer.removeClass('vscroll');\n that.$placeholder.removeClass('jqx-hidden');\n\n if (that.isVirtualized) {\n that._recycle();\n }\n\n return;\n }\n\n that.$placeholder.addClass('jqx-hidden');\n\n const horizontalOffset = 2 * (parseInt(getComputedStyle(that.$.itemsInnerContainer).getPropertyValue('--jqx-list-item-horizontal-offset')) || 0);\n\n let hScrollWidth = that._scrollWidth - that.$.itemsContainer.offsetWidth - horizontalOffset;\n let vScrollHeight = that._scrollHeight;\n\n that._refreshHorizontalScrollBarVisibility(hScrollWidth);\n that._refreshVerticalScrollBarVisibility(vScrollHeight);\n\n\n if (that.horizontalScrollBarVisibility === 'hidden') {\n that.$.itemsInnerContainer.style.width = that.$.itemsContainer.offsetWidth - horizontalOffset;\n }\n else {\n that.$.itemsInnerContainer.style.width = Math.max(that.$.itemsContainer.offsetWidth - horizontalOffset, -horizontalOffset + that.__scrollWidth) + 'px';\n }\n\n if (that.computedVerticalScrollBarVisibility) {\n hScrollWidth = that._scrollWidth - that.$.itemsContainer.offsetWidth - that._scrollView.vScrollBar.offsetWidth;\n that._refreshHorizontalScrollBarVisibility(hScrollWidth);\n\n if (that.horizontalScrollBarVisibility !== 'hidden') {\n that.$.itemsInnerContainer.style.width = Math.max(that.$.itemsContainer.offsetWidth - horizontalOffset, -horizontalOffset + that.__scrollWidth - that._scrollView.vScrollBar.offsetWidth) + 'px';\n }\n\n if (that.computedHorizontalScrollBarVisibility) {\n if (!(that.horizontalScrollBarVisibility === 'visible' && that.scrollWidth === 0)) {\n that.__scrollHeight += that._scrollView.hScrollBar.offsetHeight;\n }\n else if (that.horizontalScrollBarVisibility === 'visible') {\n that.__scrollHeight += that._scrollView.hScrollBar.offsetHeight;\n }\n\n that.scrollHeight = that.__scrollHeight;\n }\n\n if (that.isVirtualized) {\n that._recycle();\n }\n\n return;\n }\n\n hScrollWidth = that._scrollWidth - that.$.itemsContainer.offsetWidth - horizontalOffset;\n that._refreshHorizontalScrollBarVisibility(hScrollWidth);\n\n if (that.computedHorizontalScrollBarVisibility) {\n that.scrollHeight = that._scrollHeight;\n that._refreshVerticalScrollBarVisibility(that.scrollHeight);\n\n //Resize event not thrown after 'bottom-corner' is applied\n if (that._scrollView.vScrollBar.$.hasClass('bottom-corner')) {\n that._scrollView.vScrollBar.refresh();\n }\n }\n\n if (that.isVirtualized) {\n that._recycle();\n }\n\n const isIE = /Trident|Edge/.test(navigator.userAgent);\n if (!that.isRefreshing && isIE) {\n setTimeout(function () {\n that.isRefreshing = true;\n that._refreshLayout();\n that.isRefreshing = false;\n }, 50);\n }\n }", "updateHeight_() {\n const estScrollHeight = this.items.length > 0 ?\n this.items.length * this.domItemAverageHeight_() :\n 0;\n this.$.container.style.height = estScrollHeight + 'px';\n }", "get scrollDistance() { return this._scrollDistance; }", "get _scrollBottom(){return this._scrollPosition+this._viewportHeight;}", "get scrollTop() {\n return 0;\n }", "function updateScroll(){if(!elements.li[0])return;var height=elements.li[0].offsetHeight,top=height*ctrl.index,bot=top+height,hgt=elements.scroller.clientHeight,scrollTop=elements.scroller.scrollTop;if(top<scrollTop){scrollTo(top);}else if(bot>scrollTop+hgt){scrollTo(bot-hgt);}}", "initScroll() {\n this.libraryView.effetLibrarySelect.scrollTop += 1;\n this.libraryView.exempleLibrarySelect.scrollTop += 1;\n this.libraryView.intrumentLibrarySelect.scrollTop += 1;\n }", "onListChange() {\n this.refs.scrollbar.updatePositions()\n }", "render(){\n this.sbh.reportRendering();\n const { init, end, itemsContainer_hg, ghostView_hg, viewport_hg } = this.sbh;\n\n const visibleItems = this.state.items.slice( init, end ).map( ( obj, index )=> {\n return this.props.renderFunc( obj, index );\n } );\n console.log( 'style', { position:'relative', ...this.props.style } );\n return (\n <Scrollbars2 onScrollFrame={this.onScrollFrame} thumbMinSize={30}>\n <div className=\"ghostViewTop\" ref=\"ghostViewTop\" style={{ ...this.ghostStyle }} />\n <div ref=\"itemsContainer\" style={{ position:'relative', ...this.props.style }}\n className={this.props.className} >\n {visibleItems}\n </div>\n <div className=\"ghostViewBottom\" ref=\"ghostViewBottom\" style={{ ...this.ghostStyle }} />\n </Scrollbars2>\n );\n }", "updateScrollerSize_() {\n if (this.$.selector.items.length !== 0) {\n const estScrollHeight = this.items.length * this.domItemAverageHeight_();\n this.$.items.style.height = estScrollHeight + 'px';\n }\n }", "componentDidUpdate () {\n this.fixSectionItemMeasure()\n }", "get data() { return this.item.data; }", "refresh () {\n this._initMapPoints()\n this._setMapPointStyles()\n\n if (this._isScrollElementEnabled) {\n this._setScrollElementStyle()\n }\n }", "get scroller() {\n return this.getScrollerForMode(this.mode);\n }", "onLoad () {\n this.content = this.scrollView.content;\n //this.populateList();\n }", "draw()\n\t{\n\t\t// if the scrollbar's marker position has changed then the layout must be updated:\n\t\tif (this._scrollbar.markerPos !== this._prevScrollbarMarkerPos)\n\t\t{\n\t\t\tthis._prevScrollbarMarkerPos = this._scrollbar.markerPos;\n\t\t\tthis._needUpdate = true;\n\t\t}\n\n\t\t// draw the decorations:\n\t\tsuper.draw();\n\n\t\t// draw the stimuli:\n\t\tfor (let i = 0; i < this._items.length; ++i)\n\t\t{\n\t\t\tif (this._visual.visibles[i])\n\t\t\t{\n\t\t\t\tconst textStim = this._visual.textStims[i];\n\t\t\t\ttextStim.draw();\n\n\t\t\t\tconst responseStim = this._visual.responseStims[i];\n\t\t\t\tif (responseStim)\n\t\t\t\t{\n\t\t\t\t\tresponseStim.draw();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// draw the scrollbar:\n\t\tthis._scrollbar.draw();\n\t}", "function update() {\n var scrollTop = element.pageYOffset || element.scrollTop,\n \tscrollBottom = scrollTop + listHeight;\n\n var elemObj = weakmap.get(element);\n\n // quit if nothing changed.\n if( scrollTop != elemObj.lastTop ) {\n\t elemObj.lastTop = scrollTop;\n\n\t var items = elemObj.items;\n\n\t // one loop to get the offsets from the DOM\n\t for( var i = 0, len = items.length; i < len; i++ ) {\n\n\t // this offsetTop call is the perf killer.\n\t weakmap.set( items[i], {\n\t offset : items[i].offsetTop\n\t } );\n\t }\n\n\t // one loop to make our changes to the DOM\n\t for( var j = 0, len = items.length; j < len; j++ ) {\n\t\t\t\t\t\tvar item = items[j],\n\t offsetTop = weakmap.get( item ).offset;\n\n\t if( offsetTop + itemHeight < scrollTop ) {\n\t item.classList.add('past');\n\t } \n\t else if( offsetTop > scrollBottom ) {\n\t item.classList.add('future');\n\t } \n\t else {\n\t item.classList.remove('past');\n\t item.classList.remove('future');\n\t }\n\t }\n\t }\n }", "get item(){\n return items[this.itemID]\n }", "refresh() {\n // console.log('### XfControl.refresh on : ', this);\n // this.modelItem = modelItem;\n this.applyProperties();\n }", "addEvents() {\n addEventListener('scroll', () => {\n\n //nurodom kurios sekcijos vietos reikia sulaukti\n const numbersDOM = document.querySelectorAll('.achievements .item > .number');\n \n for(let i=0; i<this.validUsedData.length; i++) {\n this.animateNumber(i, numbersDOM[I]);\n }\n\n })\n }", "function updateScroll () {\n if (!elements.li[0]) return;\n if (mode === MODE_STANDARD) {\n updateStandardScroll();\n } else {\n updateVirtualScroll();\n }\n }", "refresh() {\n this.item.refresh();\n }", "get item() {\n return this._item;\n }", "redraw() {\n this.itemSet && this.itemSet.markDirty({refreshItems: true});\n this._redraw();\n }", "get item() {\r\n return this.i.item;\r\n }", "get scrollShrink(){\n return SCROLLSHRINK.get(this);\n }", "get _scrollBottom(){return this._scrollPosition+this._viewportHeight}", "_onRenderedDataChange() {\n if (!this._renderedRange) {\n return;\n }\n this._renderedItems = this._data.slice(this._renderedRange.start, this._renderedRange.end);\n if (!this._differ) {\n // Use a wrapper function for the `trackBy` so any new values are\n // picked up automatically without having to recreate the differ.\n this._differ = this._differs.find(this._renderedItems).create((index, item) => {\n return this.cdkVirtualForTrackBy ? this.cdkVirtualForTrackBy(index, item) : item;\n });\n }\n this._needsUpdate = true;\n }", "_refreshVerticalScrollBarVisibility(scrollHeight) {\n const that = this;\n\n that.scrollHeight = scrollHeight;\n\n if (that.computedVerticalScrollBarVisibility) {\n that.$itemsContainer.addClass('vscroll');\n that.$filterInputContainer.addClass('vscroll');\n\n }\n else {\n that.$itemsContainer.removeClass('vscroll');\n that.$filterInputContainer.removeClass('vscroll');\n }\n }", "function ListView_UpdateScrollBars(theObject)\n{\n\t//content exits?\n\tif (theObject.Content && theObject.Content.Item_Panel)\n\t{\n\t\t//set scrollbars\n\t\ttheObject.Content.Item_Panel.style.overflowX = Get_Bool(theObject.Properties[__NEMESIS_PROPERTY_HORIZONTAL_SCROLL_BAR], true) ? \"auto\" : \"hidden\";\n\t\ttheObject.Content.Item_Panel.style.overflowY = Get_Bool(theObject.Properties[__NEMESIS_PROPERTY_VERTICAL_SCROLL_BAR], true) ? \"auto\" : \"hidden\";\n\t\t//has vertical scroll position?\n\t\tvar vertical = Get_String(theObject.Properties[__NEMESIS_PROPERTY_VERTICAL_SCROLL_POS], null);\n\t\t//and horizontal\n\t\tvar horizontal = Get_String(theObject.Properties[__NEMESIS_PROPERTY_HORIZONTAL_SCROLL_POS], null);\n\t\t//at least one is valid?\n\t\tif (vertical != null || horizontal != null)\n\t\t{\n\t\t\t//vertical?\n\t\t\tif (vertical != null)\n\t\t\t{\n\t\t\t\t//set vertical\n\t\t\t\ttheObject.Content.Item_Panel.scrollTop = vertical * theObject.Content.Item_Height;\n\t\t\t}\n\t\t\t//has horizontal\n\t\t\tif (horizontal != null)\n\t\t\t{\n\t\t\t\t//set horizontal\n\t\t\t\ttheObject.Content.Item_Panel.scrollLeft = horizontal;\n\t\t\t\t//has header panel?\n\t\t\t\tif (theObject.Content.Header_Panel)\n\t\t\t\t{\n\t\t\t\t\t//match scroll pos\n\t\t\t\t\ttheObject.Content.Header_Panel.scrollLeft = theObject.Content.Item_Panel.scrollLeft;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//trigger a repaint\n\t\t\tListView_Paint(theObject);\n\t\t}\n\t}\n}", "get scrollSpeed() {\n return this._scrollSpeed;\n }", "_onRenderedDataChange() {\n if (!this._renderedRange) {\n return;\n }\n\n this._renderedItems = this._data.slice(this._renderedRange.start, this._renderedRange.end);\n\n if (!this._differ) {\n // Use a wrapper function for the `trackBy` so any new values are\n // picked up automatically without having to recreate the differ.\n this._differ = this._differs.find(this._renderedItems).create((index, item) => {\n return this.cdkVirtualForTrackBy ? this.cdkVirtualForTrackBy(index, item) : item;\n });\n }\n\n this._needsUpdate = true;\n }", "update() {\n const items = this.carouselService.settings.items;\n let start = this.carouselService.current(), end = start + items;\n if (this.carouselService.settings.center) {\n start = items % 2 === 1 ? start - (items - 1) / 2 : start - items / 2;\n end = items % 2 === 1 ? start + items : start + items + 1;\n }\n this.carouselService.slidesData.forEach((slide, i) => {\n slide.heightState = (i >= start && i < end) ? 'full' : 'nulled';\n });\n }", "get scrollSpeed() { return this._scrollSpeed; }", "elementScrolled() {\n return this._elementScrolled;\n }", "elementScrolled() {\n return this._elementScrolled;\n }", "onScroll_() {\n if (this.$.container.scrollTop > 0 &&\n this.domRepeat_.items.length !== this.items.length) {\n const aboveScrollTopItemCount =\n Math.round(this.$.container.scrollTop / this.domItemAverageHeight_());\n\n // Ensure we have sufficient items to fill the current scroll position and\n // a full view following our current position.\n if (aboveScrollTopItemCount + this.chunkItemThreshold >\n this.domRepeat_.items.length) {\n this.ensureDomItemsAvailableStartingAt_(aboveScrollTopItemCount);\n }\n }\n }", "function updateScroll () {\n if (!elements.li[0]) return;\n var height = elements.li[0].offsetHeight,\n top = height * ctrl.index,\n bot = top + height,\n hgt = elements.scroller.clientHeight,\n scrollTop = elements.scroller.scrollTop;\n if (top < scrollTop) {\n scrollTo(top);\n } else if (bot > scrollTop + hgt) {\n scrollTo(bot - hgt);\n }\n }", "function updateScroll () {\n if (!elements.li[0]) return;\n var height = elements.li[0].offsetHeight,\n top = height * ctrl.index,\n bot = top + height,\n hgt = elements.scroller.clientHeight,\n scrollTop = elements.scroller.scrollTop;\n if (top < scrollTop) {\n scrollTo(top);\n } else if (bot > scrollTop + hgt) {\n scrollTo(bot - hgt);\n }\n }", "function updateScroll () {\n if (!elements.li[0]) return;\n var height = elements.li[0].offsetHeight,\n top = height * ctrl.index,\n bot = top + height,\n hgt = elements.scroller.clientHeight,\n scrollTop = elements.scroller.scrollTop;\n if (top < scrollTop) {\n scrollTo(top);\n } else if (bot > scrollTop + hgt) {\n scrollTo(bot - hgt);\n }\n }", "function onScroll() {\n var scrollTop = contentEl.prop('scrollTop');\n var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);\n\n // Store the previous scroll so we know which direction we are scrolling\n onScroll.prevScrollTop = scrollTop;\n\n //\n // AT TOP (not scrolling)\n //\n if (scrollTop === 0) {\n // If we're at the top, just clear the current item and return\n setCurrentItem(null);\n return;\n }\n\n //\n // SCROLLING DOWN (going towards the next item)\n //\n if (isScrollingDown) {\n\n // If we've scrolled down past the next item's position, sticky it and return\n if (self.next && self.next.top <= scrollTop) {\n setCurrentItem(self.next);\n return;\n }\n\n // If the next item is close to the current one, push the current one up out of the way\n if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {\n translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));\n return;\n }\n }\n\n //\n // SCROLLING UP (not at the top & not scrolling down; must be scrolling up)\n //\n if (!isScrollingDown) {\n\n // If we've scrolled up past the previous item's position, sticky it and return\n if (self.current && self.prev && scrollTop < self.current.top) {\n setCurrentItem(self.prev);\n return;\n }\n\n // If the next item is close to the current one, pull the current one down into view\n if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {\n translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));\n return;\n }\n }\n\n //\n // Otherwise, just move the current item to the proper place (scrolling up or down)\n //\n if (self.current) {\n translate(self.current, scrollTop);\n }\n }", "function onScroll() {\n var scrollTop = contentEl.prop('scrollTop');\n var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);\n\n // Store the previous scroll so we know which direction we are scrolling\n onScroll.prevScrollTop = scrollTop;\n\n //\n // AT TOP (not scrolling)\n //\n if (scrollTop === 0) {\n // If we're at the top, just clear the current item and return\n setCurrentItem(null);\n return;\n }\n\n //\n // SCROLLING DOWN (going towards the next item)\n //\n if (isScrollingDown) {\n\n // If we've scrolled down past the next item's position, sticky it and return\n if (self.next && self.next.top <= scrollTop) {\n setCurrentItem(self.next);\n return;\n }\n\n // If the next item is close to the current one, push the current one up out of the way\n if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {\n translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));\n return;\n }\n }\n\n //\n // SCROLLING UP (not at the top & not scrolling down; must be scrolling up)\n //\n if (!isScrollingDown) {\n\n // If we've scrolled up past the previous item's position, sticky it and return\n if (self.current && self.prev && scrollTop < self.current.top) {\n setCurrentItem(self.prev);\n return;\n }\n\n // If the next item is close to the current one, pull the current one down into view\n if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {\n translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));\n return;\n }\n }\n\n //\n // Otherwise, just move the current item to the proper place (scrolling up or down)\n //\n if (self.current) {\n translate(self.current, scrollTop);\n }\n }", "function onScroll() {\n var scrollTop = contentEl.prop('scrollTop');\n var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);\n\n // Store the previous scroll so we know which direction we are scrolling\n onScroll.prevScrollTop = scrollTop;\n\n //\n // AT TOP (not scrolling)\n //\n if (scrollTop === 0) {\n // If we're at the top, just clear the current item and return\n setCurrentItem(null);\n return;\n }\n\n //\n // SCROLLING DOWN (going towards the next item)\n //\n if (isScrollingDown) {\n\n // If we've scrolled down past the next item's position, sticky it and return\n if (self.next && self.next.top <= scrollTop) {\n setCurrentItem(self.next);\n return;\n }\n\n // If the next item is close to the current one, push the current one up out of the way\n if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {\n translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));\n return;\n }\n }\n\n //\n // SCROLLING UP (not at the top & not scrolling down; must be scrolling up)\n //\n if (!isScrollingDown) {\n\n // If we've scrolled up past the previous item's position, sticky it and return\n if (self.current && self.prev && scrollTop < self.current.top) {\n setCurrentItem(self.prev);\n return;\n }\n\n // If the next item is close to the current one, pull the current one down into view\n if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {\n translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));\n return;\n }\n }\n\n //\n // Otherwise, just move the current item to the proper place (scrolling up or down)\n //\n if (self.current) {\n translate(self.current, scrollTop);\n }\n }", "function onScroll() {\n var scrollTop = contentEl.prop('scrollTop');\n var isScrollingDown = scrollTop > (onScroll.prevScrollTop || 0);\n\n // Store the previous scroll so we know which direction we are scrolling\n onScroll.prevScrollTop = scrollTop;\n\n //\n // AT TOP (not scrolling)\n //\n if (scrollTop === 0) {\n // If we're at the top, just clear the current item and return\n setCurrentItem(null);\n return;\n }\n\n //\n // SCROLLING DOWN (going towards the next item)\n //\n if (isScrollingDown) {\n\n // If we've scrolled down past the next item's position, sticky it and return\n if (self.next && self.next.top <= scrollTop) {\n setCurrentItem(self.next);\n return;\n }\n\n // If the next item is close to the current one, push the current one up out of the way\n if (self.current && self.next && self.next.top - scrollTop <= self.next.height) {\n translate(self.current, scrollTop + (self.next.top - self.next.height - scrollTop));\n return;\n }\n }\n\n //\n // SCROLLING UP (not at the top & not scrolling down; must be scrolling up)\n //\n if (!isScrollingDown) {\n\n // If we've scrolled up past the previous item's position, sticky it and return\n if (self.current && self.prev && scrollTop < self.current.top) {\n setCurrentItem(self.prev);\n return;\n }\n\n // If the next item is close to the current one, pull the current one down into view\n if (self.next && self.current && (scrollTop >= (self.next.top - self.current.height))) {\n translate(self.current, scrollTop + (self.next.top - scrollTop - self.current.height));\n return;\n }\n }\n\n //\n // Otherwise, just move the current item to the proper place (scrolling up or down)\n //\n if (self.current) {\n translate(self.current, scrollTop);\n }\n }", "data() {\n\t\treturn {\n\t\t\tisVisible: true\n\t\t}\n\t}", "propertyChangedHandler(propertyName, oldValue, newValue) {\n const that = this;\n\n super.propertyChangedHandler(propertyName, oldValue, newValue);\n\n if (propertyName === 'hidden') {\n if (!newValue) {\n that.$.removeClass('jqx-hidden');\n }\n else {\n that.$.addClass('jqx-hidden');\n }\n }\n\n else if (propertyName === 'color') {\n that._setItemColor();\n }\n else if (propertyName === 'displayMode') {\n that._setDisplayMode(newValue);\n }\n else if (propertyName === 'label' || propertyName === 'value') {\n const context = that.context;\n that.context = document;\n\n if (propertyName === 'label') {\n that.innerHTML = newValue;\n }\n\n const listBox = that.getListBox();\n listBox._applyTemplate(that);\n listBox.onItemUpdated(that);\n that.context = context;\n }\n else if (propertyName === 'details') {\n const context = that.context;\n that.context = document;\n that.$.details.innerHTML = newValue;\n\n const listBox = that.getListBox();\n listBox.onItemUpdated(that);\n that.context = context;\n }\n else if (propertyName === 'innerHTML') {\n const listBox = that.getListBox();\n listBox.onItemUpdated(that);\n }\n }", "_onRenderedDataChange() {\n if (!this._renderedRange) {\n return;\n }\n this._renderedItems = this._data.slice(this._renderedRange.start, this._renderedRange.end);\n if (!this._differ) {\n this._differ = this._differs.find(this._renderedItems).create(this.cdkVirtualForTrackBy);\n }\n this._needsUpdate = true;\n }", "get item(){ return this._item || {}; }", "handleScroll() {\n return this.setScrollTop().process();\n }", "get scrollTarget(){return this.$.scrollable}", "propertyChangedHandler(propertyName, oldValue, newValue) {\n super.propertyChangedHandler(propertyName, oldValue, newValue);\n\n const that = this;\n\n if (newValue !== oldValue) {\n switch (propertyName) {\n case 'arrayIndexingMode':\n that.arrayIndexingMode = oldValue; // arrayIndexingMode cannot be changed programmatically\n break;\n case 'columns':\n case 'rows':\n that._changeRowsColumns(propertyName, oldValue, newValue);\n break;\n case 'customWidgetDefaultValue':\n if (that.type === 'custom') {\n that._defaultValue = newValue;\n that._scroll();\n }\n break;\n case 'dimensions':\n that._addRemoveMultipleDimensions(oldValue, newValue);\n break;\n case 'animation':\n case 'disabled':\n for (let j = 0; j < that._indexers.length; j++) {\n that._indexers[j][propertyName] = newValue;\n }\n\n if (that.type !== 'none') {\n const cellWidgets = that.getElementsByClassName('jqx-array-element-' + that._id);\n\n if (that.type !== 'custom') {\n for (let i = 0; i < cellWidgets.length; i++) {\n cellWidgets[i][propertyName] = newValue;\n }\n }\n else {\n if (that.changeProperty) {\n that.changeProperty(propertyName, newValue, cellWidgets);\n }\n else {\n try {\n that.warn(that.localize('callbackFunctionRequired', { callback: 'changeProperty' }));\n }\n catch (err) {\n //\n }\n }\n }\n\n that._scroll();\n }\n\n break;\n case 'elementHeight':\n that.setRowHeight(newValue, true);\n break;\n case 'elementTemplate':\n if (that.type !== 'none') {\n const cellWidgets = that.getElementsByClassName('jqx-array-element-' + that._id);\n\n for (let k = 0; k < cellWidgets.length; k++) {\n let currentWidget = cellWidgets[k];\n\n that.elementTemplate(currentWidget, { x: currentWidget.col, y: currentWidget.row });\n }\n }\n break;\n case 'elementWidth':\n that.setColumnWidth(newValue, true);\n break;\n case 'indexerHeight':\n for (let o = 0; o < that._indexers.length; o++) {\n that._indexers[o].style.height = newValue + 'px';\n }\n\n that._updateWidgetHeight();\n break;\n case 'indexerWidth':\n that.$.indexerContainer.style.width = newValue + 'px';\n that._updateWidgetWidth();\n break;\n case 'showHorizontalScrollbar':\n if (that._oneDimensionSpecialCase === true) {\n that.showHorizontalScrollbar = false;\n return;\n }\n\n that._showHorizontalScrollbar(newValue);\n break;\n case 'showIndexDisplay':\n if (newValue) {\n that.$indexerContainer.removeClass('jqx-hidden');\n }\n else {\n that.$indexerContainer.addClass('jqx-hidden');\n }\n\n that._updateWidgetWidth();\n that._updateWidgetHeight('showIndexDisplay');\n break;\n case 'showSelection':\n if (newValue) {\n that._refreshSelection();\n }\n else {\n that._clearSelection();\n }\n\n break;\n case 'showVerticalScrollbar':\n if (that.dimensions === 1 && that._oneDimensionSpecialCase === false) {\n that.showVerticalScrollbar = false;\n return;\n }\n\n that._showVerticalScrollbar(newValue);\n break;\n case 'type':\n that._getDefaultCellValue();\n\n if (oldValue !== 'none' && newValue !== 'none') {\n that._initializeElements(true);\n that._updateWidgetWidth();\n that._updateWidgetHeight();\n }\n else if (oldValue === 'none') {\n that.value = that._returnEmptyArray();\n\n if (that._structureAdded === true) {\n that._initializeElements(false);\n that._table.classList.remove('jqx-hidden');\n }\n else {\n that._addElementStructure();\n that._structureAdded = true;\n that._initializeElements(false);\n }\n\n that.$.centralContainer.style.width = '';\n that.$.bigContainer.style.width = '';\n that.$.mainContainer.style.height = '';\n that.$.bigContainer.style.height = '';\n\n that._updateWidgetWidth();\n that._updateWidgetHeight();\n that._getInitialFill();\n }\n else if (newValue === 'none') {\n that.reset(true);\n }\n break;\n case 'value':\n if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {\n that._validateValue();\n\n if (JSON.stringify(oldValue) !== JSON.stringify(that.value)) {\n that._scroll();\n that._getInitialFill();\n that.$.fireEvent('change', { 'value': that.value, 'oldValue': oldValue });\n }\n }\n\n break;\n }\n }\n }", "function update() {\n var scrollTop = element.pageYOffset || element.scrollTop,\n scrollBottom = scrollTop + listHeight;\n\n // Quit if nothing changed.\n if (scrollTop == element.lastTop) return;\n\n element.lastTop = scrollTop;\n\n // One loop to make our changes to the DOM\n for (var i = 0, len = items.length; i < len; i++) {\n var item = items[i];\n\n // Above list viewport\n if (item._offsetTop + item._offsetHeight < scrollTop) {\n item.classList.add('past');\n } else if (item._offsetTop > scrollBottom) {\n item.classList.add('future');\n } else {\n item.classList.remove('past');\n item.classList.remove('future');\n }\n }\n }", "_refreshHorizontalScrollBarVisibility(scrollWidth) {\n const that = this;\n\n that.scrollWidth = scrollWidth;\n\n if (that.computedHorizontalScrollBarVisibility) {\n that.scrollLeft = that.$.itemsContainer.scrollLeft;\n that.$itemsContainer.addClass('hscroll');\n }\n else {\n that.$itemsContainer.removeClass('hscroll');\n }\n }", "function adjustObsSetters() {\r\n\r\n }", "arangeItems () {\r\n // TODO: Add code here\r\n }", "_horizontalScrollbarHandler(event) {\n const that = this;\n\n event.stopPropagation();\n\n if (that.isVirtualized) {\n that._recycle();\n }\n else {\n that.$.itemsContainer.scrollLeft = event.detail.value;\n }\n }", "constructor() {\n super();\n this.__aspects = {};\n this.__items = [];\n let target = this.shadowRoot.querySelector(\"#carouselitem\");\n if (this.selected.scroll && target) {\n this._scrollIntoView([this._getParentOffset(target)]);\n if (!this.selected.zoomed) target.focus();\n }\n }", "get itemSize() { return this._itemSize; }", "get itemSize() { return this._itemSize; }", "onPaint() {\n const me = this,\n {\n rowManager,\n store,\n element,\n headerContainer,\n bodyContainer,\n footerContainer\n } = me,\n scrollPad = DomHelper.scrollBarPadElement;\n\n if (me.isPainted) {\n return;\n }\n\n let columnsChanged,\n maxDepth = 0; // See if updateResponsive changed any columns.\n\n me.columns.on({\n change: () => columnsChanged = true,\n single: true\n }); // Cached, updated on resize. Used by RowManager and by the subgrids upon their render\n\n me._bodyRectangle = Rectangle.client(me.bodyContainer);\n const bodyOffsetHeight = me.bodyContainer.offsetHeight; // Apply any responsive configs before rendering rows.\n\n me.updateResponsive(me.width, 0); // If there were any column changes, apply them\n\n if (columnsChanged) {\n me.callEachSubGrid('refreshHeader', headerContainer);\n me.callEachSubGrid('refreshFooter', footerContainer);\n } // Note that these are hook methods for features to plug in to. They do not do anything.\n // SubGrids take care of their own rendering.\n\n me.renderHeader(headerContainer, element);\n me.renderFooter(footerContainer, element); // These padding elements are only visible on scrollbar showing platforms.\n // And then, only when the owning element as the b-show-yscroll-padding class added.\n // See refreshVirtualScrollbars where this is synced on the header, footer and scroller elements.\n\n DomHelper.append(headerContainer, scrollPad);\n DomHelper.append(footerContainer, scrollPad);\n DomHelper.append(me.virtualScrollers, scrollPad);\n\n if (me.autoHeight) {\n me._bodyHeight = rowManager.initWithHeight(element.offsetHeight - headerContainer.offsetHeight - footerContainer.offsetHeight, true);\n bodyContainer.style.height = me.bodyHeight + 'px';\n } else {\n me._bodyHeight = bodyOffsetHeight;\n rowManager.initWithHeight(me._bodyHeight, true);\n }\n\n me.eachSubGrid(subGrid => {\n if (subGrid.header.maxDepth > maxDepth) {\n maxDepth = subGrid.header.maxDepth;\n }\n });\n headerContainer.dataset.maxDepth = maxDepth;\n me.fixSizes();\n\n if (store.count || !store.isLoading) {\n me.renderRows(false, false);\n }\n\n me.initScroll();\n me.initInternalEvents();\n }", "__itemsChanged(e) {\n this.__items = [...e.detail.value];\n }", "propertyChangedHandler(propertyName, oldValue, newValue) {\n super.propertyChangedHandler(propertyName, oldValue, newValue);\n\n const that = this;\n\n switch (propertyName) {\n case 'navigationButtonsPosition':\n that._renderButtons();\n return;\n case 'navigationInputPosition':\n case 'pageSizeSelectorPosition':\n case 'summaryPosition':\n that._renderSettings();\n return;\n }\n\n that._render();\n }", "get styleTableRecords() { \n let ret = Object.assign({}, this.style.table.item);\n ret.scrollbar = Object.assign({}, this.style.table.scrollbar);\n return ret;\n }", "refreshVirtualScrollbars() {\n // NOTE: This was at some point changed to only run on platforms with width-occupying scrollbars, but it needs\n // to run with overlayed scrollbars also to make them show/hide as they should.\n const me = this,\n {\n headerContainer,\n footerContainer,\n virtualScrollers,\n hasVerticalOverflow\n } = me,\n // We need to ask each subGrid if it has horizontal overflow.\n // If any do, we show the virtual scroller, otherwise we hide it.\n hasHorizontalOverflow = Object.values(me.subGrids).some(subGrid => subGrid.overflowingHorizontally),\n method = hasVerticalOverflow ? 'add' : 'remove';\n\n if (hasHorizontalOverflow) {\n virtualScrollers.classList.remove('b-hide-display');\n } else {\n virtualScrollers.classList.add('b-hide-display');\n } // Auto-widthed padding element at end hides or shows to create matching margin.\n\n if (DomHelper.scrollBarWidth) {\n headerContainer.classList[method]('b-show-yscroll-padding');\n footerContainer.classList[method]('b-show-yscroll-padding');\n virtualScrollers.classList[method]('b-show-yscroll-padding');\n } // Change of scrollbar status means height change\n\n me.onHeightChange();\n }", "_refreshScrollerPosition() {\n this.__carouselScrollerWidth = qx.bom.element.Dimension.getWidth(\n this.__carouselScroller.getContentElement()\n );\n\n this._scrollToPage(this.getCurrentIndex());\n }", "componentDidUpdate(){\n console.log(\"UPDATE : \", this.lastMsgRef)\n if(this.lastMsgRef.current !== null && this.lastMsgRef.current !== undefined )\n {this.executeScroll()}\n}", "updateGraphicsData() {\n // override\n }", "function updateCalculations(win, rootElement, targetElement, setName, hasScrolled) {\n\t\tvar inView = isInViewport(win, targetElement);\n\t\tquery('.' + setName, rootElement)[0].value = inView ? 1 : 0;\n\t\tquery('.hasScrolled', rootElement)[0].value = hasScrolled ? 1 : 0;\n\t}", "[symbols.itemsChanged]() {\n if (super[symbols.itemsChanged]) { super[symbols.itemsChanged](); }\n const items = this.items;\n const count = items.length;\n this.$.spreadContainer.style.width = (count * 100) + '%';\n const itemWidth = (100 / count) + \"%\";\n [].forEach.call(items, item => {\n item.style.width = itemWidth;\n });\n }", "scrollIntoView() {\n this.updated |= UPDATED_SCROLL;\n return this;\n }", "function CachedItemPosition() {}", "function CachedItemPosition() {}", "onCustomWidgetBeforeUpdate(changedProperties) {\r\n\r\n\t\t}", "updateScrollIndicators () {\n let container = this.refs.container;\n let up = false;\n let down = false;\n let scrollTop = container.scrollTop;\n let scrollHeight = container.scrollHeight;\n let offsetHeight = container.offsetHeight;\n\n if (scrollTop > 0) {\n up = true;\n }\n\n if (\n scrollHeight > offsetHeight && scrollTop + offsetHeight !== scrollHeight\n ) {\n down = true;\n }\n\n container.className = classNames('scroll-indicator', this.props.className, {\n 'scroll-up': up,\n 'scroll-down': down,\n });\n }", "didRender() {\n super.didRender(...arguments);\n\n if (!get(this, 'isDestroyed') && !get(this, 'isDestroying')) {\n this._syncScroll();\n }\n }", "beforeUpdate() {\n const {\n delta, remain, bench, changeProp, getZone,\n setScrollTop, offset, variable, getVarOffset, size,\n } = this;\n const calcstart = changeProp === 'start' ? this.start : delta.start;\n const zone = getZone(calcstart);\n delta.keeps = remain + (bench || remain);\n // if start, size or offset change, update scroll position.\n if (changeProp && ['start', 'size', 'offset'].includes(changeProp)) {\n let scrollTop = 0;\n if (changeProp === 'offset') {\n scrollTop = offset; // 更新了偏移,直接将偏移设置为滚动距离\n } else {\n const { isLast, start } = zone;\n const { total } = delta;\n if (variable) { // 可变高度,则通过函数来计算距离\n scrollTop = getVarOffset(isLast ? total : start);\n } else if (isLast && (total - calcstart <= remain)) { // 已经滚动到最底\n scrollTop = total * size;\n } else {\n scrollTop = calcstart * size;\n }\n }\n this.$nextTick(setScrollTop.bind(this, scrollTop));\n }\n\n // if points out difference, force update once again.\n if (changeProp || delta.end !== zone.end || calcstart !== zone.start) {\n this.changeProp = '';\n delta.end = zone.end;\n delta.start = zone.start;\n this.forceRender();\n }\n }", "get item() {\n\t\treturn this.__item;\n\t}", "get itemSize() {\n return this._itemSize;\n }", "autobind() {\n\t\tthis.onScroll = this.onScroll.bind(this);\n\t\tthis.onWindowResize = this.onWindowResize.bind(this);\n\t\tthis.updatePosition = this.updatePosition.bind(this);\n\t\tthis.onWindowLoad = this.onWindowLoad.bind(this);\n\t}", "refreshFakeScroll() {\n const me = this,\n {\n element,\n virtualScrollerElement,\n virtualScrollerWidth,\n totalFixedWidth,\n store\n } = me,\n scroller = me.scrollable; // Use a fixed scroll width if grid is empty, to make it scrollable without rows\n // https://app.assembla.com/spaces/bryntum/tickets/7184\n\n scroller.scrollWidth = store && store.count ? null : totalFixedWidth; // Scroller lays out in the same way as subgrid.\n // If we are flexed, the scroller is flexed etc.\n\n virtualScrollerElement.style.width = element.style.width;\n virtualScrollerElement.style.flex = element.style.flex;\n\n if (!me.collapsed) {\n if (me.overflowingHorizontally) {\n virtualScrollerWidth.style.width = `${scroller.scrollWidth}px`;\n me.header.element.classList.add('b-overflowing');\n me.footer && me.footer.element.classList.add('b-overflowing'); // If *any* SubGrids have horizontal overflow, the main grid\n // has to show its virtual horizontal scollbar.\n\n me.grid.virtualScrollers.classList.remove('b-hide-display');\n } else {\n virtualScrollerWidth.style.width = 0;\n me.header.element.classList.remove('b-overflowing');\n me.footer && me.footer.element.classList.remove('b-overflowing');\n }\n }\n }", "onCustomWidgetBeforeUpdate(oChangedProperties) {\n\n \n\n\n }", "function CachedItemPosition() { }", "componentDidUpdate() {\n if (this.props.selected === this.props.featureId) {\n this.itemRef.current.scrollIntoView(true);\n }\n }", "componentDidUpdate(prevProps, prevStates) {\n if (\n this.scrollerDiv.current &&\n this.scrollerDiv.current.scrollHeight !== prevStates.scrollHeight\n ) {\n this.setScrolled();\n }\n }", "updateScroll() {\n\t\t\tthis.scrollPosition = window.scrollY;\n\t\t}", "set scrolling(scrolling) {\n this._scrolling = scrolling;\n }", "_scrollToItem(idx) {\n const item = this.items[idx];\n if (!item) {\n return;\n }\n\n const props = this._vertical ? ['top', 'bottom'] :\n this._isRTL ? ['right', 'left'] : ['left', 'right'];\n\n const scrollerRect = this._scrollerElement.getBoundingClientRect();\n const nextItemRect = (this.items[idx + 1] || item).getBoundingClientRect();\n const prevItemRect = (this.items[idx - 1] || item).getBoundingClientRect();\n\n let scrollDistance = 0;\n if (!this._isRTL && nextItemRect[props[1]] >= scrollerRect[props[1]] ||\n this._isRTL && nextItemRect[props[1]] <= scrollerRect[props[1]]) {\n scrollDistance = nextItemRect[props[1]] - scrollerRect[props[1]];\n } else if (!this._isRTL && prevItemRect[props[0]] <= scrollerRect[props[0]] ||\n this._isRTL && prevItemRect[props[0]] >= scrollerRect[props[0]]) {\n scrollDistance = prevItemRect[props[0]] - scrollerRect[props[0]];\n }\n\n this._scroll(scrollDistance);\n }", "_storeItemsCoordinates() {\n const that = this;\n\n if (that.disabled || !that.reorder) {\n return;\n }\n\n const coordinates = [];\n\n for (let i = 0; i < that._items.length; i++) {\n const currentItemContainer = that._items[i],\n boundingClientRect = currentItemContainer.getBoundingClientRect();\n\n coordinates.push({\n fromY: boundingClientRect.top + (window.scrollY || window.pageYOffset),\n toY: boundingClientRect.bottom + (window.scrollY || window.pageYOffset)\n });\n }\n\n that._itemsCoordinates = coordinates;\n }", "get item () {\n\t\treturn this._item;\n\t}", "setScroll() {\n this.canScroll = true\n }", "_updateRenderedRange() {\n if (!this._viewport) {\n return;\n }\n const renderedRange = this._viewport.getRenderedRange();\n const newRange = { start: renderedRange.start, end: renderedRange.end };\n const viewportSize = this._viewport.getViewportSize();\n const dataLength = this._viewport.getDataLength();\n let scrollOffset = this._viewport.measureScrollOffset();\n // Prevent NaN as result when dividing by zero.\n let firstVisibleIndex = (this._itemSize > 0) ? scrollOffset / this._itemSize : 0;\n // If user scrolls to the bottom of the list and data changes to a smaller list\n if (newRange.end > dataLength) {\n // We have to recalculate the first visible index based on new data length and viewport size.\n const maxVisibleItems = Math.ceil(viewportSize / this._itemSize);\n const newVisibleIndex = Math.max(0, Math.min(firstVisibleIndex, dataLength - maxVisibleItems));\n // If first visible index changed we must update scroll offset to handle start/end buffers\n // Current range must also be adjusted to cover the new position (bottom of new list).\n if (firstVisibleIndex != newVisibleIndex) {\n firstVisibleIndex = newVisibleIndex;\n scrollOffset = newVisibleIndex * this._itemSize;\n newRange.start = Math.floor(firstVisibleIndex);\n }\n newRange.end = Math.max(0, Math.min(dataLength, newRange.start + maxVisibleItems));\n }\n const startBuffer = scrollOffset - newRange.start * this._itemSize;\n if (startBuffer < this._minBufferPx && newRange.start != 0) {\n const expandStart = Math.ceil((this._maxBufferPx - startBuffer) / this._itemSize);\n newRange.start = Math.max(0, newRange.start - expandStart);\n newRange.end = Math.min(dataLength, Math.ceil(firstVisibleIndex + (viewportSize + this._minBufferPx) / this._itemSize));\n }\n else {\n const endBuffer = newRange.end * this._itemSize - (scrollOffset + viewportSize);\n if (endBuffer < this._minBufferPx && newRange.end != dataLength) {\n const expandEnd = Math.ceil((this._maxBufferPx - endBuffer) / this._itemSize);\n if (expandEnd > 0) {\n newRange.end = Math.min(dataLength, newRange.end + expandEnd);\n newRange.start = Math.max(0, Math.floor(firstVisibleIndex - this._minBufferPx / this._itemSize));\n }\n }\n }\n this._viewport.setRenderedRange(newRange);\n this._viewport.setRenderedContentOffset(this._itemSize * newRange.start);\n this._scrolledIndexChange.next(Math.floor(firstVisibleIndex));\n }" ]
[ "0.61827755", "0.6083896", "0.6005804", "0.59467065", "0.59060645", "0.5851346", "0.57493025", "0.5744736", "0.57304657", "0.56875217", "0.5679275", "0.5617453", "0.5568289", "0.55670774", "0.55633044", "0.55514693", "0.5548961", "0.55476177", "0.5539459", "0.55282134", "0.55277824", "0.55101603", "0.5508289", "0.549532", "0.54909426", "0.5467028", "0.5458852", "0.5455328", "0.5453725", "0.5441678", "0.54345924", "0.5412976", "0.5408455", "0.54006076", "0.54005736", "0.53902876", "0.5389728", "0.5385714", "0.53847045", "0.5372654", "0.53469914", "0.5342604", "0.5341634", "0.5335711", "0.53338116", "0.53338116", "0.5321302", "0.53201497", "0.53201497", "0.53201497", "0.5299567", "0.5299567", "0.5299567", "0.5299567", "0.52988887", "0.52933663", "0.5291728", "0.528436", "0.5281686", "0.5278282", "0.5274205", "0.5272588", "0.52717006", "0.52607113", "0.5259952", "0.5254202", "0.5251777", "0.5249248", "0.5249248", "0.5248165", "0.5240372", "0.5239558", "0.5237236", "0.5227159", "0.5224572", "0.5218819", "0.5218363", "0.5211631", "0.5207243", "0.520415", "0.51882625", "0.51882625", "0.5187961", "0.51871717", "0.5186568", "0.5182563", "0.51792234", "0.5176354", "0.51763105", "0.5175339", "0.5174098", "0.5168722", "0.5164602", "0.51644826", "0.5154775", "0.51538277", "0.5153241", "0.51529104", "0.5147878", "0.5147657", "0.5146231" ]
0.0
-1
enqueues a new value at the end of the queue
enqueue(value) { const lastIndex = this._length + this._headIndex; this._storage[lastIndex] = value; this._length++; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "enqueue(val) {\n this._queue.push(val);\n }", "enqueue(value) {\n if (!this.queueIsFull()) {\n this.queue.push(value)\n }\n }", "enQueue(value) {\n this._dataStore.push(value);\n this._length++;\n }", "enqueue(value) {\r\n return this.data.addToBack(value);\r\n }", "enqueue (value) {\n if (this.checkOverflow()) return\n if (this.checkEmpty()) {\n this.front += 1\n this.rear += 1\n } else {\n if (this.rear === this.maxLength) {\n this.rear = 1\n } else this.rear += 1\n }\n this.queue[this.rear] = value\n }", "enqueue(value) {\n // increment the position\n this.position++;\n // storage at position is value\n this.storage[this.position] = value;\n }", "enqueue(value) {\n // Create a new node to store the value\n let node = new _Node(value);\n\n // If the node is the first to be added\n if (this.first === null) {\n this.first = node;\n this.size++;\n }\n\n // Shift existing node in last to the next position in queue\n if (this.last) {\n this.last.next = node;\n }\n\n // Make the new node last\n this.last = node;\n this.size++;\n }", "enqueue(value){\n return this.linkedList.append(value);\n }", "enqueue(val) {\n // Declare our new item\n const node = new _Node(val);\n\n // If we don't have a first item, make this node first\n if ( this.first === null ) {\n this.first = node;\n };\n\n // If we have a last item, point it to this node\n if ( this.last ) {\n this.last.next = node;\n };\n\n // Make the new node the last item on the queue\n this.last = node;\n }", "enqueue(value) {\r\n this.inStack.push(value);\r\n }", "enqueue(value) {\n const node = new NodeDeque(value);\n // only happens under null condition\n if (this.first === null) {\n this.first = node;\n }\n // Add to the end of the queue, because last equals something\n if (this.last) {\n this.last.next = node;\n this.last.prev = this.last;\n }\n //make the new node the last item on the queue\n this.last = node;\n }", "enqueue(item) {\n this.queue.push(item);\n this.size += 1;\n }", "enqueue(number) {\n return this.queue.push(number)\n}", "enqueue( value ) {\n\t\tif ( this._end >= this._MAX - 1 ) {\n\t\t\tconsole.log( \"Queue is Full!\" );\n\t\t\treturn false;\n\t\t}\n\n\t\tif ( this._start == -1 ) {\n\t\t\tthis._start++;\n\t\t}\n\t\tthis._end++;\n\t\tthis._storage[this._end] = value;\n\t\treturn true;\n\t}", "add(value){\n\n this.qLength++;\n\n //as Queue is collection of nodes, create a new node\n //also it's implementation is in FIFO so the new node is to be added at last node\n\n const newNode = {\n before:this.last,\n after:null,\n value:value,\n }\n\n //check if the Queue is empty and then set the new node as first node\n\n if(this.last ===null){\n this.first = newNode;\n } else{ /* if the Queue is not empty then set the after pointer of the last node\n to the new node */\n this.last.after = newNode;\n }\n // set the last pointer to the new node\n this.last = newNode;\n\n }", "function enqueue(newElement){\n queue.push(newElement);\n }", "enqueue(item) {\n queue.unshift(item);\n }", "enqueue(item) {\n queue.unshift(item);\n }", "enqueue(value) {\n this.storage.push(value);\n }", "enqueue(value) {\n\t\tthis.items.push(value);\n\t\treturn this.items.length;\n\t}", "enqueue(value) {\n\t\tthis.items.addToBack(value);\n\t\treturn this.items.length();\n\t}", "enqueue(val) {\n let newVal = new Node(val);\n\n if (!this.first) {\n this.first = newVal;\n this.last = this.first;\n } else {\n this.last.next = newVal;\n this.last = newVal;\n }\n this.size += 1;\n }", "function enqueue(x) {\r\n\tqueue.push(x);\r\n}", "enqueue(val) {\n\n // linkedList\n // this._linkedList.push(val);\n // this.first = this._linkedList.head;\n // this.last = this._linkedList.tail;\n // this.size = this._linkedList.length;\n\n // array\n this._array.push({val});\n this.first = this._array[0];\n this.last = this._array[this._array.length - 1];\n this.size = this._array.length;\n }", "enqueue(value) {\n this.#queue = [value].concat(this.#queue);\n return this.#queue;\n }", "enqueue(value) {\n ListNode.link(this.head, new ListNode(value));\n this.length ++;\n }", "enqueue(values) {\n values.forEach(v => {\n this.queue.binaryTree.push(v);\n this.queue.siftUp(this.queue.size() - 1);\n });\n }", "push(value) {\n if (this.isFull()) {\n throw new RangeError('Ring buffer is full.');\n }\n this.set(this.end, value);\n this.end = this.wrap(this.end + 1);\n }", "enqueue(value){\n const newNode = new Node(value);\n //if queue is empty\n if (this.size === 0) {\n this.first = newNode;\n this.last = newNode;\n // add current first pointer to new first(new node), and make new node new first\n } else {\n this.last.next = newNode;\n this.last = newNode;\n }\n //add 1 to size\n this.size++;\n\n return this;\n }", "enqueue(val) {\n let newNode = new Node(val); // create new node\n\n if (this.front === null) { // if queue is empty\n this.front = newNode; // HEAD\n this.back = newNode; // TAIL\n\n } else { // queue not empty\n this.back.next = newNode;\n this.back = newNode;\n }\n\n this.length++;\n\n return this.length;\n }", "enqueue(val) {\n const newNode = new Node(val)\n this.head === null ? this.head = newNode : this.tail.next = newNode;\n\n this.tail = newNode;\n this.length++;\n }", "enqueue(item) {\n\t\tthis.storage.add_to_tail(item);\n\t\tthis.length++;\n\t}", "enqueue(value) {\n this.storage[value] = value;\n this.count += 1;\n return this.storage;\n }", "enqueue(newItem) {\n this.q.push(newItem)\n }", "enqueue(value) {\n // set value equal to key number for the storage object\n this.storage[this.keyNum] = value;\n // increment the key number\n this.keyNum++;\n //return the storage object\n return this.storage;\n }", "enqueue(val, priority) {\r\n let newNode = new Node(val, priority);\r\n this.values.push(element);\r\n this.bubbleUp();\r\n }", "enqueue(data) {\n if (this.hasRoom()) {\n this.queue.addTail(data);\n this.size++;\n console.log(\n `'${data}' was added to the queue! The queue is now ${this.size}`\n );\n } else throw new Error(`The Queue has no more room to add new data!`)\n }", "enqueue(value) {\n this.list.push(value);\n\n return this;\n }", "enqueue(element) {\n this.items[this.count] = element;\n this.count++;\n }", "push(val) {\n this._storage[this._length] = val; \\\n this._length++;\n }", "enqueue(value){\n const current = new Node(value);\n if (this.length === 0){\n this.first = current;\n this.last = current;\n this.length++;\n return this;\n }else{\n //const holdingPointer = this.last;\n //this.last = current;\n //this.last.next = holdingPointer;\n this.last.next = current;\n this.last =current;\n this.length++;\n return this;\n }\n }", "enqueue(value, priority){\n let newNode = new Node(value, priority);\n this.values.push(newNode);\n this.bubbleUp();\n }", "enqueue(data){\n if(!this.isFull()){\n this.data[this.rear] = data;\n if(this.rear === this.data.length-1){\n this.rear = 0;\n }else{\n this.rear ++;\n }\n }\n }", "enqueue(element) {\n // adding element to the queue \n this.items.push(element);\n }", "enqueue(element) {\n // adding element to the queue \n this.items.push(element);\n }", "enqueue(element) {\n // adding element to the queue \n this.items.push(element);\n }", "enqueue(val) {\n let newQueueNode = new Node(val);\n if(!this.front) {\n this.front = newQueueNode;\n this.back = newQueueNode;\n } else {\n newQueueNode.next = this.front;\n this.front = newQueueNode;\n }\n this.size++;\n return this.size;\n }", "push(val) {\n if (!val) return null; // edge case fo no value passed in\n let newNode = new Node(val); // new object of data structure\n if (!this.first) { // edge case situation for empty queue\n this.first = newNode;\n this.last = this.first;\n } else {\n this.last.next = newNode; // assign newNode to be the next node to the old last\n this.last = newNode; // assign newNode to be new last\n }\n this.size++; // increment size\n return this; // return updated queue\n }", "add(item) {\n\t\tthis.queue.set(item, item);\n\t}", "push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }", "push(element) {\n const oldBack = this._back;\n let newBack = oldBack;\n if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) {\n newBack = {\n _elements: [],\n _next: undefined\n };\n }\n // push() is the mutation most likely to throw an exception, so it\n // goes first.\n oldBack._elements.push(element);\n if (newBack !== oldBack) {\n this._back = newBack;\n oldBack._next = newBack;\n }\n ++this._size;\n }", "enQueue(element){\n return this.items.push(element); //item added to the queue array\n }", "enqueue(value){\n var node = new Node(value)\n if(!this.last){\n this.first = node;\n this.last = node;\n }\n else{\n this.last. next = node;\n this.last = node;\n }\n this.length++\n return this\n }", "add(val) {\n this.buffer.push(val);\n this.buffer = this.buffer.slice(-this.size);\n }", "enqueue(item) {\n this.items.push(item); // adds an item to the queue\n }", "enqueue(element, priority){\n var newElement = new QueueEntry(element, priority);\n var valueExists = false; \n\n for(var i = 0; i < this.items.length; i++){\n if(this.items[i].priority > newElement.priority) {\n this.items.splice(i, 0, newElement);\n valueExists = true; \n break; \n }\n }\n if(!valueExists){\n this.items.push(newElement);\n }\n }", "enqueue(val) {\n let newNode = new Node(val);\n if (!this.first) {\n this.first = newNode;\n this.last = newNode;\n } else {\n this.last.next = newNode;\n this.last = newNode;\n }\n return ++this.size;\n }", "enqueue(element) {\n // adding element to the queue\n this.items.push(element);\n }", "addBack(val) {\n this.size++;\n this.items.push(val);\n this.peekBack();\n }", "insert(val) {\n if (this.storage[0] === null) {\n this.storage[0] = val;\n this.size++;\n return;\n }\n this.storage.push(val);\n this.size++;\n this.bubbleUp(this.size - 1);\n }", "enqueue(value) {\n const newNode = new Node(value);\n\n // 加入東西之前先檢查是否 Queue 是空的\n // 如果 head 都沒東西就表示是空的\n if (this.head === null) {\n // 確定都沒東西的話就把指標同時放在頭跟尾\n this.head = newNode;\n this.tail = newNode;\n // 因為在只有一個 node 存在的情況下、這個node是head也是tail\n } else {\n\n // 當head有資料的時候,只須要操作tail即可\n // (例如: 假設this._tail 是Node A, A.nextNode = nextNode)\n this.tail.nextNode = newNode;\n\n // 把tail指標對應到 目前新增的節點 (例如: 新節點是Node B,等於 tail 就是 節點B 的意思)\n this.tail = newNode;\n }\n this._addNodesCounter();\n return this;\n }", "enqueue(val) {\n let newNode = new Node(val);\n if (!this.first) {\n this.first = newNode;\n this.last = newNode;\n } else {\n let currentTail = this.last;\n currentTail.next = newNode;\n this.last = newNode;\n }\n this.size++;\n return this;\n }", "enqueue(value, priority) {\n const newEntry = new Entry(value, priority);\n this.values.push(newEntry);\n let curr = this.values.length - 1;\n let parent = Math.floor((curr - 1) / 2);\n while (\n curr > 0 &&\n this.values[parent].priority > this.values[curr].priority\n ) {\n const temp = this.values[parent];\n this.values[parent] = this.values[curr];\n this.values[curr] = temp;\n curr = parent;\n parent = Math.floor((curr - 1) / 2);\n }\n }", "enqueue(data) {\n const node = new _Node(data);\n\n if (this.first === null) {\n this.first = node;\n }\n\n if (this.last) {\n this.last.next = node;\n }\n //make the new node the last item on the queue\n this.last = node;\n }", "enqueue(value){\n const newNode = new Node(value);\n if (!this.first) {\n this.first = newNode;\n this.last = newNode;\n }else{\n this.last.next = newNode;\n this.last = newNode;\n }\n this.size++;\n return this;\n }", "enqueue(element) {\n if (this.maxSize){\n if(this.rear+1 == this.maxSize){\n throw Error ('The queue is overflowing.');\n }\n }\n this.rear +=1;\n this.queue[this.rear] =element;\n }", "enqueue(...vals) {\n this.list.append(...vals);\n }", "insert(val) {\n if (typeof val === 'undefined') return;\n this.storage.push(val);\n this.bubbleUp(this.storage.length - 1);\n this.size++;\n // console.log('val: ',val, ' storage: ', this.storage.toString());\n }", "enqueue(data) {\n const node = new _Node(data);\n \n if(this.first === null) {\n this.first = node;\n }\n\n if(this.last) {\n this.last.next = node;\n }\n //make the new node the last item on the queue\n this.last = node;\n }", "enqueue(data) {\n this.append(data)\n }", "enqueue(data){\n const node = new _Node(data);\n\n //makes new node first if null\n if(this.first === null){\n this.first = node;\n }\n\n //moves last node up in the queue\n if(this.last){\n this.last.next = node;\n }\n\n //make new node the last item\n this.last = node;\n }", "function enqueue(queue,update){if(update){queue=queue||[];queue.push(update);}return queue;}", "function enqueue(queue,update){if(update){queue=queue||[];queue.push(update);}return queue;}", "function enqueue(queue,update){if(update){queue=queue||[];queue.push(update);}return queue;}", "enqueue(value) {\n const newNode = new Node(value);\n if(!this.first) {\n this.first = newNode;\n this.last = newNode;\n } else {\n this.last.next = newNode;\n this.last = newNode;\n }\n this.size++;\n return true;\n }", "enqueue(value){\n const newNode = new Node(value); \n if(this.length === 0){\n this.first = newNode; \n this.last = newNode; \n }else{\n this.last.next = newNode; \n this.last = newNode;\n }\n this.length++; \n return this;\n }", "enqueue(val) {\n const node = new Node(val);\n if (!this.first) {\n this.first = node;\n this.last = node;\n } else {\n this.last.next = node;\n this.last = node; // move the pointer\n }\n\n return this.size++;\n }", "push(value){\r\n this.top += 1;\r\n this.storage[this.top] = value;\r\n }", "push(value) {\n this.storage[this.length] = value;\n this.length++;\n }", "enqueue(val) {\n this.stack2 = this.stack1;\n this.stack1 = [];\n this.stack1.push(val);\n for (let i = 0; i < this.stack2.length; i++) {\n this.stack1.push(this.stack2[i]);\n }\n this.stack2 = [];\n return this;\n }", "enqueue(value) {\n const node = new Node(value);\n\n // Assign the Head if first elem (special case)\n if (this.head === null) {\n this.head = node;\n this.tail = node;\n return;\n }\n\n this.tail.next = node;\n this.tail = node;\n }", "enqueue(val, priority) {\n if (!val || priority < 0) return false;\n\n const newNode = new Node(val, priority),\n VALS = this.values;\n\n // new node gets inserted at the end of the queue\n VALS.push(newNode);\n\n // if there's only one item, nothing else needs to be done\n if (VALS.length === 1) return this;\n\n // grab the index of the newly inserted node\n let nIdx = VALS.length - 1;\n\n while (true) {\n // calculate the new node's parent's index\n let pIdx = Math.floor((nIdx - 1) / 2);\n\n // as long as nIdx is greater than zero\n // (to prevent out-of-bound indices)\n // and the priority of the value at nIdx\n // is higher (i.e. the number is smaller)\n if (nIdx && VALS[nIdx].priority < VALS[pIdx].priority) {\n // keep swapping and recalculating indices\n this.swapNodes(pIdx, nIdx);\n nIdx = pIdx;\n } else return this;\n }\n }", "enqueue(value){\r\n // Basically, the goal here is to, one node at a time,\r\n // emtpy stack 1 into stack 2.\r\n while(!this.stack1.isEmpty())\r\n this.stack2.push(this.stack1.pop().value)\r\n\r\n // Then, push the new value into stack 1, putting it at the bottom\r\n // (i.e. adding it to the back of the queue)\r\n this.stack1.push(value);\r\n \r\n // Then empty stack 2 back into stack 1 node by node\r\n while(!this.stack2.isEmpty())\r\n this.stack1.push(this.stack2.pop().value);\r\n \r\n // Finally, return our frankenstack\r\n return this;\r\n }", "enque(ele) {\n if (this.rear == this.capacity - 1) {\n console.log(\"Queue is full\");\n return;\n }\n if (this.front == -1) {\n this.front++;\n\n\n\n }\n this.items[++this.rear] = ele;\n this.Size++;\n }", "dequeue() {\n this._queue.shift();\n }", "enqueue(value) {\n const newNodo = new Node(value);\n if (this.length === 0) {\n this.first = newNodo;\n this.last = newNodo;\n } else {\n //Aquí pega el nodo\n this.last.next = newNodo;\n //Aqui le dice que el ultimo nodo es el nuevo nodo\n this.last = newNodo;\n }\n this.length++;\n return this;\n }", "function enqueue(msg)\n\t {\n\t queue.push(msg);\n\t if (!tickUpcoming) {\n\t setImmediate(tick);\n\t }\n\t }", "function enqueue(msg)\n\t {\n\t queue.push(msg);\n\t if (!tickUpcoming) {\n\t setImmediate(tick);\n\t }\n\t }", "enqueue (item) {\n this.head.push(item)\n }", "enqueue(value) {\n var newNode = new Node(value);\n if (this.size === 0) {\n this.first = newNode;\n this.last = newNode;\n } else {\n // add to the tail\n this.last.next = newNode;\n this.last = newNode;\n }\n ++this.size;\n return this\n }", "updateProgressWithNextThenQueue() {\n // we need to grab the first item in the queue without shifting it off \n // because setState is asyncronous and we rely on the value of\n // `this.state.progress` to determine if we add to the queue or not\n const next = this.queued[0];\n this.setProgress(next, Date.now(), () => {\n this.queued.shift();\n if (this.queued.length === 0) return;\n const minTime = next.minDuration != null ? next.minDuration : this.MIN_TIME_EACH_PROGRESS_UPDATE;\n this.nextProgressUpdateTimer = setTimeout(this.updateProgressWithNextThenQueue, minTime);\n });\n }", "enqueue(val){\n let newNode = new NodeQ(val)\n if(this.head === null){\n this.head = newNode\n this.tail = newNode\n } else {\n let currentTail = this.tail\n currentTail.next = newNode\n this.tail = newNode\n }\n this.length++\n return newNode\n\n}", "enqueue(item) {\n\t\tthis.stack1.add(item);\n\t}", "enqueue(value) {\n const node = new Node(value);\n if (!this.length) {\n this.first = node;\n this.last = node;\n } else {\n this.last.next = node;\n this.last = node;\n }\n this.length += 1;\n return this;\n }", "enqueue(value) {\n\t\tvar new_node = new ListNode(value);\n\n\t\tif (this.head == null) {\n\t\t\tthis.head = new_node;\n\t\t\tthis.tail = new_node;\n\t\t}\n\t\t\n\t\telse {\n\t\t\tnew_node.next = this.head;\n\t\t\tthis.head = new_node;\n\t\t}\n\t}", "async write(value) {\n if (this.queue.length >= this.bounds) {\n await this.writePause();\n this.readResume(value);\n return;\n }\n this.readResume(value);\n }", "add(element) { \n // adding element to the queue \n this.items.push(element); \n }", "push(value) {\n if (this._pending !== undefined) {\n const resolve = this._pending.shift();\n if (resolve !== undefined) {\n resolve(value);\n return;\n }\n }\n if (this._available === undefined) {\n this._available = [];\n }\n this._available.push(Promise.resolve(value));\n }", "expand() {\n this.queue.unshift({\n x: this.x,\n y: this.y\n });\n }", "dequeue() {\n this.queue.shift()\n}" ]
[ "0.8306082", "0.82394886", "0.785545", "0.78353226", "0.780036", "0.7773354", "0.76745576", "0.76106006", "0.7516432", "0.75021976", "0.7462355", "0.7443069", "0.7441978", "0.7441809", "0.741165", "0.7354497", "0.7302385", "0.7302385", "0.7257569", "0.7232349", "0.72298944", "0.7219612", "0.7208541", "0.71974355", "0.7188664", "0.7171395", "0.7148733", "0.71283275", "0.7119288", "0.71145266", "0.70819044", "0.7067575", "0.705347", "0.70511717", "0.70480376", "0.7040914", "0.6998027", "0.6976963", "0.69498295", "0.692994", "0.6906142", "0.68926", "0.6888674", "0.6872245", "0.6872245", "0.6872245", "0.6845688", "0.68429685", "0.68405575", "0.68381757", "0.68381757", "0.6829997", "0.68221897", "0.6816618", "0.6801919", "0.6778012", "0.67765135", "0.67568773", "0.6756133", "0.67456466", "0.6739839", "0.6730322", "0.6712304", "0.6712208", "0.671111", "0.6709145", "0.67084974", "0.6700858", "0.6697182", "0.66758686", "0.6650526", "0.66437936", "0.66437936", "0.66437936", "0.6637564", "0.6635824", "0.65998274", "0.65834004", "0.65739024", "0.6552342", "0.6543265", "0.65424865", "0.6540842", "0.65323836", "0.6504109", "0.6499808", "0.64993167", "0.64993167", "0.64919126", "0.64812195", "0.6479714", "0.6478837", "0.64743584", "0.64732444", "0.64663094", "0.64609605", "0.64556664", "0.64484954", "0.6435631", "0.6435483" ]
0.80286324
2
dequeues the value from the beginning of the queue and returns it
dequeue() { const firstValue = this._storage[this._headIndex]; delete this._storage[this._headIndex]; this._length--; this._headIndex++; return firstValue; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function dequeue(){\n return queue.shift();\n }", "dequeue() {\n try {\n if(this.isEmpty) return null\n\n const firstValue = this._storage[this._head]\n delete this._storage[this._head]\n this._head++\n this._length--\n return firstValue\n } catch(err) {\n throw new Error(err)\n }\n }", "dequeue() {\n\t\t// the first item in the queue\n\t\tconst item = this.storage.remove_from_head();\n\t\tif (this.isEmpty() !== true) {\n\t\t\t// only do this if the item is not null\n\t\t\tthis.length--;\n\t\t}\n\n\t\treturn item;\n\t}", "dequeue() {\n this._treatNoValues();\n return this.storage.shift();\n }", "dequeue() {\n if (!this.first) throw new Error(\"Cannot dequeue! Queue is empty\");\n let removed = this.first;\n // only one item in queue: remove it and set last to be null\n if (this.first === this.last) {\n this.last = null;\n }\n // set first to be what came after first, which will be null if queue has only one item\n this.first = this.first.next;\n this.size -= 1;\n return removed.val;\n }", "dequeue(){\n //if queue is empty, nothing to remove\n if(this.first === null){\n return;\n }\n\n //set pointer to first item\n const node = this.first\n\n //move pointer to next in the queue and make it first\n this.first = this.first.next;\n\n //if this is the last item in the queue\n if(node === this.last){\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n return queue.pop()\n }", "dequeue() {\n this.size -= 1;\n return this.queue.shift();\n }", "dequeue() {\n if (this.length === 0) throw new Error(\"No more items in queue\");\n\n const oldHead = this.head;\n\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = oldHead.next;\n oldHead.next = null;\n }\n\n this.length--;\n\n return oldHead.val;\n }", "dequeue(){\n //if queue is empty there is nothing to return\n if(this.first === null){\n return;\n }\n const node = this.first;\n this.first = this.first.next;\n //if this is last item in queue\n if(node === this.last){\n this.last = null;\n }\n return node.value\n }", "dequeue() {\n if (0 != this.q.length) {\n let c = this.q[0];\n this.q.splice(0, 1);\n return c\n }\n }", "dequeue() {\n if (this.tail > this.head) {\n const value = this.storage[this.head];\n delete this.storage[this.head];\n this.head++;\n return value;\n } else {\n return null;\n }\n }", "dequeue() {\n if(! this.isEmpty()) return this.items.shift()\n else return undefined\n }", "dequeue() {\n return this._queue.shift();\n }", "dequeue() {\n //if the queue is empty, there is nothing to return\n if (this.first === null) {\n return;\n }\n const node = this.first;\n this.first = this.first.next;\n //if this is the last item in the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n const element = this.queue.binaryTree.shift();\n this.queue.binaryTree.unshift(this.queue.binaryTree.pop());\n this.queue.siftDown(0);\n return element;\n }", "dequeue() {\n return this.queue.shift()\n }", "remove() {\n if (this.isEmpty()) throw new Error('Queue is empty!');\n const value = this.first.value;\n this.first = this.first.next;\n this.size--;\n return value;\n }", "dequeue() {\n if (!this.first) return null;\n\n let current = this.first;\n if (this.first === this.last) this.last = null;\n this.first = this.first.next;\n this.size--;\n return current.val;\n }", "dequeue() {\n //if the queue is empty, there is nothing to return\n if (this.first === null) {\n return;\n }\n const node = this.first;\n this.first = node.next;\n //if this is the last item in the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n if (this.count == 0) {\n return undefined;\n }\n let deletedItem = this.items[0];\n this.items.splice(0, 1);\n this.count--;\n return deletedItem;\n }", "dequeue() {\n if (this.count === 0) {\n return 0;\n }\n var firstIdx = Object.keys(this.storage)[0];\n var itemToRemove = this.storage[firstIdx];\n delete this.storage[firstIdx];\n this.count -= 1;\n return itemToRemove;\n }", "remove(){\n /*as it's FIFO so just need to remove the first node and \n adjust the next node in the Queue to be the first node after \n the removal of the first node.*/\n\n const firstNode = this.first;\n\n //check if Queue is empty then return undefined\n\n if (firstNode === null){\n return undefined;\n }\n\n //make this.first point to next node\n this.first = firstNode.after;\n\n //check if the Queue only had one node\n if(this.first === null){\n this.last = null;\n }\n\n this.qLength--;\n\n return firstNode.value;\n }", "dequeue() {\n if (!this.first) return null;\n const temp = this.first;\n if (this.first === this.last) {\n this.first = null;\n }\n this.first = this.first.next;\n this.size -= 1;\n return temp.val;\n }", "dequeue() {\n const node = this.head;\n\n if (node === null) {\n console.log(new Error('No more items in the queue.'))\n return;\n }\n this.head = this.head.next;\n\n return node.value;\n }", "deQueue() {\n if (!this.head) {\n return \"No item\";\n } else {\n let itemToPop = this.head;\n this.head = this.head.next;\n return itemToPop;\n }\n }", "dequeue() {\n const value = _(this).collection.shift();\n return value[0];\n }", "dequeue() {\n return queue.pop();\n }", "dequeue() {\n return queue.pop();\n }", "dequeue() {\n if (this.isEmpty) { throw new Error(\"Can't remove from empty queue\") };\n return this.#queue.pop();\n }", "dequeue(){\n if(this.isEmpty()){\n throw Error ('The Queue is Empty, Unable to dequeue()');\n }else{\n const removingElement = this.queue[this.front];\n this.front +=1;\n return removingElement;\n }\n }", "dequeue() {\n if (this.size === 0) {\n return null\n }\n var temp = this.first;\n if (this.first === this.last) {\n this.last = null;\n }\n // remove from the head\n this.first = this.first.next\n this.size--\n return temp.value;\n }", "remove() {\n if (!this.isEmpty()) {\n let firstElement = this.queue[0];\n this.queue.shift();\n this.length -= 1;\n return firstElement;\n } else {\n return null;\n }\n }", "dequeue() {\n if (this.isEmpty()) {\n return null;\n }\n\n return this.list.shift().value;\n }", "dequeue() {\n\t\treturn this.items.shift();\n\t}", "dequeue(){\n let dequeue = this.linkedList.deleteHead();\n return dequeue ? dequeue.value : null;\n }", "dequeue() {\n return this.items.shift();\n }", "function dequeue() {\n return queue[index++];\n }", "dequeue() {\n // save item to return\n const item = this.first.item;\n\n // delete first node\n this.first = this.first.next;\n\n if (this.isEmpty()) {\n this.last = null;\n }\n \n // return saved item\n return item;\n }", "dequeue() {\n if (this.isEmpty()) \n throw \"Queue is Empty\"; \n return this.queue.shift(); \n }", "dequeue() {\n\t\tif (this.isEmpty()) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst node = this._dummyHead.prev;\n\t\tconst newFirst = node.prev;\n\t\tthis._dummyHead.prev = newFirst;\n\t\tnewFirst.next = this._dummyHead;\n\t\t// unlink the node to be dequeued.\n\t\tnode.prev = null;\n\t\tnode.next = null;\n\t\tthis._length--;\n\t\treturn node.value;\n\t}", "dequeue() {\n // Check if queue is empty\n if (this.first === null) {\n return null;\n }\n\n // Get the first node in the list\n let node = this.first;\n\n // Shift the next node in the queue to first\n this.first = this.first.next;\n\n // If the node is in the last position of the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n\t\treturn this.items.removeHead();\n\t}", "dequeue() {\n // If the queue is empty, there is nothing to dequeue\n if ( this.first === null ) {\n return;\n };\n\n // Declare our node to dequeue\n const node = this.first;\n // Set the 2nd item in queue to our first\n this.first = this.first.next;\n\n // If this is the last item in the queue\n if ( node === this.last ) {\n // Set our last to null\n this.last = null;\n };\n\n return node.val;\n }", "dequeue() {\n if(this.size === 0){\n throw Error('queue is empty');\n }\n\n // linkedList\n // const returnVal = this._linkedList.shift();\n // this.first = this._linkedList.head;\n // this.last = this._linkedList.tail;\n // this.size = this._linkedList.length;\n\n // array\n const returnVal = this._array.shift().val;\n this.first = this._array[0];\n this.last = this._array[this._array.length - 1];\n this.size = this._array.length;\n\n return returnVal;\n }", "dequeue() {\n if(this.items.length > 0) {\n return this.items.shift();\n }\n }", "dequeue() {\n if (this.first === null) {\n return;\n }\n // we need to save this first node before replacing it so that we can check\n // if it is the only item on the list\n const node = this.first;\n this.first = this.first.next;\n if (node === this.last) {\n this.last = null;\n }\n // need this to be returned so you can use its value later\n this.size--;\n return node.value;\n }", "dequeue()\r\n {\r\n if (this.isEmpty()){\r\n return null;\r\n }\r\n return this.items.shift();\r\n }", "dequeue() {\n if(!this.isEmpty()) {\n return this.collection.shift();\n } else {\n console.log(\"Queue is already empty\");\n }\n }", "dequeue() {\n return this.collection.shift()[0]\n }", "dequeue() {\n\t\treturn this.shift();\n\t}", "dequeue() {\n // check is size is greater than zero\n if (this.size() > 0) {\n // incrememnt depostion\n this.deposition++;\n // create temp var to hold storage at deposition\n var tempHold = this.storage[this.deposition];\n // delete storage at deposition\n delete this.storage[this.deposition];\n // return tempHold\n return tempHold;\n }\n }", "dequeue() {\n if (!this.length) return null;\n\n const removedNode = this.first;\n if (this.length === 1) {\n this.first = null;\n this.last = null;\n }\n\n this.first = removedNode.next;\n this.length -= 1;\n removedNode.next = null;\n return removedNode.value;\n }", "dequeue() {\n this._queue.shift();\n }", "dequeue() {\n this.queue.shift()\n}", "dequeue() {\n return this.collection.shift();\n }", "dequeue() { \n let removed = this.front\n this.front = this.front.next\n return removed\n }", "dequeue() {\n if (this.head !== null) {\n return 'No item !'\n } else {\n let itemToPop = this.head;\n this.head = this.head.next;\n return itemToPop;\n }\n }", "dequeue() {\n let temp = this.stack1[(this.stack1.length - 1)];\n console.log(\"Popped value is\", temp);\n return this.stack1.pop();\n }", "function dequeue(queue){\n //immediately return error if queue empty\n if(queue.length < 1){\n console.log(\"ERROR: The specified queue is empty and cannot be dequeued.\")\n return JSON.stringify({})\n }\n\n var nextMessage = queue[queue.length-1]\n\n //logic to handle case when next item is in sequence\n if(nextMessage.hasOwnProperty(\"_sequence\")){\n var partList = sequenceMap.get(nextMessage[\"_sequence\"]).partList\n //case when next item in queue is appropriate message in sequence to remove\n if(nextMessage.hasOwnProperty(\"_part\") && nextMessage[\"_part\"] == partList[0]){\n var currentVal = sequenceMap.get(nextMessage[\"_sequence\"])\n currentVal.partList.shift()\n if(currentVal.partList.length == 0){\n sequenceMap.delete(nextMessage[\"_sequence\"])\n }\n else{\n sequenceMap.set(nextMessage[\"_sequence\"],currentVal)\n }\n return JSON.stringify(queue.pop())\n }\n //case when not the appropriate sequence message to remove (lower part # exists in queue)\n else{\n for(var i=queue.length-1;i>=0;i--){\n var currentMessage = queue[i]\n if(currentMessage.hasOwnProperty(\"_part\") && currentMessage[\"_part\"] == partList[0]){\n var currentVal = sequenceMap.get(currentMessage[\"_sequence\"])\n currentVal.partList.shift()\n if(currentVal.partList.length == 0){\n sequenceMap.delete(currentMessage[\"_sequence\"])\n }\n else{\n sequenceMap.set(currentMessage[\"_sequence\"],currentVal)\n }\n var removedMessage = queue.splice(i,1)\n return JSON.stringify(removedMessage[0])\n }\n }\n }\n }\n\n return JSON.stringify(queue.pop())\n}", "dequeue() {\n return this.collection.shift();\n }", "dequeue(){\n if(this.isEmpty()){\n return \"Empty Queue\"\n }\n return this.items.shift();\n }", "dequeue() {\n // Time Complexity O(n)\n return this.list.shift();\n }", "peek(){\n return queue[queue.length -1]\n }", "dequeue() {\n // return the dequeued element \n // and remove it. \n // if the queue is empty \n // returns Underflow \n if (this.isEmpty())\n return \"Underflow\";\n return this.items.shift();\n }", "dequeue(){\n //if queue is empty return false\n if (this.size === 0) return false;\n //get dequeuednode\n const dequeuedNode = this.first;\n //get new first (could be NULL if stack is length 1)\n const newFirst = this.first.next;\n //if newFirst is null, reassign last to newFirst(null)\n if (!newFirst) {\n this.last = newFirst;\n }\n //assign new first\n this.first = newFirst;\n //remove reference to list\n dequeuedNode.next = null;\n //remove 1 from size\n this.size--;\n //return dequeuednode\n return dequeuedNode.value;\n }", "dequeue() {\n if(!this.front) return null;\n if(this.size === 1) {\n let retVal = this.front.value;\n this.front = null;\n this.back = null;\n this.size--;\n return retVal;\n } else {\n let iteratorNode = this.front;\n while(iteratorNode.next !== this.back) {\n iteratorNode = iteratorNode.next;\n }\n let retVal = this.back.value;\n iteratorNode.next = null;\n this.back = iteratorNode;\n this.size--;\n return retVal;\n }\n }", "shift() {\n if (this.length === 0) throw new Error(\"No more items in queue\");\n\n const oldHead = this.head;\n\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = oldHead.next;\n oldHead.next = null;\n }\n\n this.length--;\n\n return oldHead.val;\n }", "dequeue() {\n\t\tif ( this.size() >= 1 ) {\n\t\t\tlet nextUp = this._storage[this._start];\n\t\t\tdelete this._storage[this._start];\n\n\t\t\tif ( this._start == this._end ) {\n\t\t\t\tthis._start = this._end = -1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._start++;\n\t\t\t}\n\t\t\treturn nextUp;\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"Queue is Empty!\");\n\t\t\treturn false;\n\t\t}\n\t}", "dequeue(data) {\n if (this.size() === 0) {\n return null\n } else {\n let dequeuedData = this.get(0)\n this.remove(0)\n return dequeuedData\n }\n }", "dequeue() {\r\n return this.data.removeFromFront();\r\n }", "dequeue() {\n if (this.isEmpty()) {\n return \"Queue is empty: underflow.\";\n } else {\n return this.items.shift();\n }\n }", "dequeue(){\r\n // Dequeue is super simple. Removing from a queue is functionally the same\r\n // as removing from a stack.\r\n return this.stack1.pop();\r\n }", "dequeue() { // removes the item from the queue FIFO\n return this.processes.shift(); // use array shift\n }", "function DequeueNext() {\n\tm_refreshing = true;\n\t/*\n\tif( m_queue.length == 0 ) {\n\t\tm_refreshing = false;\n\t\treturn;\n\t}*/\n\tif( m_queued == 0 ) {\n\t\tm_refreshing = false;\n\t\treturn;\n\t}\n\tm_queued--;\n\t//m_current_serial = m_queue.shift();\n\tDoRefresh();\n}", "dequeue() {\n return _(this).collection.shift();\n }", "poll() {\n const top = this.queue.shift(); \n return top; \n }", "dequeue() {\n if (!this.first) return null;\n\n let temp = this.first;\n // 1 node left\n if (this.first === this.last) {\n this.last = null;\n }\n // so if one node left, this.first.next is also null\n // first and last pointer overlap\n this.first = this.first.next;\n this.size--;\n\n return temp.value;\n }", "dequeue() {\n\n //如果是剛建立,沒有任何node的queue,this._head的初始數值就是null\n if (!this.head) {\n return null;\n }\n\n const valueOfHeadNode = this._head;\n\n if (this.head === this.tail) {\n // 如果目前queue只有一個元素,這樣頭跟尾都的地址都是同一個node\n // 所以 this._head === this._tail 等於拿同一個node做比較\n this.head = null;\n this.tail = null; // 利用null值來清空目前的queue\n } else {\n this.head = this.head.nextNode;\n // tail 不變\n }\n\n // 無論是if或是else condition,都會減少一個元素,所以要更新nodesCounts\n this._subtractNodesCounter();\n return valueOfHeadNode;\n }", "dequeue(){\n const oldRoot = this.values[0];\n const lastNode = this.values.pop();\n \n if(this.values.length > 0){\n this.values[0] = lastNode;\n this.bubbleDown();\n }\n \n return oldRoot;\n }", "dequeue() {\n return this.processes.shift();\n // console.log('dequeu',this.processes[0]);\n }", "dequeue(){\n if(!this.eQueue.length && !this.dQueue.length) throw Error(\"Empty Stack\");\n \n if(this.dQueue.length === 0){\n for(let item of this.eQueue){\n this.dQueue.push(item);\n }\n }\n return this.dQueue.pop();\n }", "dequeue() {\n // set a variable equal to the object keys array\n var keys = Object.keys(this.storage);\n // set a variable equal to the lowest key value\n var lowest = this.storage[keys[0]];\n // delete the lowest key value\n delete this.storage[keys[0]];\n // return the lowest key value variable\n return lowest;\n }", "dequeue() {\n if (this.isEmpty()) throw new Error('Can not dequeue. The priority queue is empty');\n\n return this.items.shift();\n }", "denqueue() {\n debug(`\\nLOG: remove the queue`);\n this.queue.shift();\n }", "dequeue(){\n if (!this.first) {\n return null;\n }else if (this.size === 1) {\n this.first = null;\n this.last = null;\n }else{\n let oldStart = this.first.next;\n this.first.next = null;\n this.first = oldStart;\n }\n this.size--;\n return this;\n }", "shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }", "shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }", "function peek(){\n return queue[0];\n }", "dequeue(){\n if(this.size === 0) return undefined;\n const node = this.first;\n\n this.first = this.first.next;\n\n this.size--;\n\n if(this.size === 0) this.last = undefined;\n\n node.next = undefined;\n return node;\n }", "shift() {\n if (!this.first) return undefined; // edge case for empty queue\n if (this.first === this.last) { // edge case for size = 1\n this.last = null;\n }\n let removed = this.first; // store first node in a variable \n this.first = this.first.next; // set first to be the next node\n removed.next = null; // erase link from removed node\n this.size--; // decrement size\n return removed; // return removed node\n }", "pop() {\n if (this._array.length === 0) {\n throw new error.NotFound('Queue is empty')\n }\n return this._array.shift()\n }", "dequeue(){\n if(this.length === 0){\n return null;\n }\n if(this.length === 1){\n this.last = null;\n this.first = null;\n return this;\n }\n\n const deleteFirst = this.first.next;\n this.first = deleteFirst;\n\n this.length--;\n return this;\n }", "dequeue () {\n this.head.shift()\n }", "pop(){\n if (!this.head) {\n return null;\n }\n var removed = this.head.value;\n this.head = this.head.next;\n this.length--;\n return removed;\n }", "pop() {\n if (this.isEmpty()) {\n throw new RangeError('Ring buffer is empty.');\n }\n this.end = this.wrap(this.end - 1);\n const result = this.get(this.end);\n this.set(this.end, undefined);\n return result;\n }", "deQueue() {\n if (!this.En_stack.length) {\n throw new Error('Queue is empty')\n }\n while (this.En_stack.length != 1) {\n this.De_stack.push(this.En_stack.pop())\n }\n let x = this.En_stack.pop()\n while (this.De_stack.length != 0) {\n this.En_stack.push(this.De_stack.pop())\n }\n return x\n }", "deque() {\n if (this.front == -1) {\n console.log(\"Queue is empty\");\n return null;\n }\n var ele = this.items[this.front++];\n this.Size--;\n if (this.front > this.rear) {\n this.front = this.rear = -1;\n }\n return ele;\n }", "next () {\n const element = this.queue.shift()\n this.keys.delete(element.key)\n\n return element\n }", "dequeue () {\n\t\treturn this[DISPLAY_LIST].shift();\n\t}" ]
[ "0.8206041", "0.8094191", "0.80746645", "0.8055837", "0.80022115", "0.7993854", "0.797259", "0.79612017", "0.79229575", "0.7908534", "0.79070646", "0.7903664", "0.78886545", "0.78661275", "0.7855471", "0.7844776", "0.7840722", "0.78196096", "0.78067094", "0.77841955", "0.77729696", "0.7769138", "0.77646726", "0.77482975", "0.77419883", "0.773989", "0.7734269", "0.7724935", "0.7724935", "0.7713206", "0.77056664", "0.76995766", "0.768536", "0.7671377", "0.7662105", "0.7643511", "0.76102144", "0.7609166", "0.7608382", "0.76032704", "0.7591778", "0.7579583", "0.75632393", "0.7545823", "0.75386596", "0.75316757", "0.752604", "0.75257397", "0.7525022", "0.7522", "0.75092465", "0.75049746", "0.747079", "0.74351174", "0.7413687", "0.7372849", "0.7365685", "0.73629653", "0.7360413", "0.7335144", "0.7334966", "0.73109585", "0.7296558", "0.72927517", "0.7291516", "0.7288206", "0.72832584", "0.72614384", "0.72482795", "0.7231902", "0.7213189", "0.7188672", "0.7187899", "0.7176086", "0.7173393", "0.71706885", "0.7168084", "0.7160004", "0.7151797", "0.71324056", "0.71019614", "0.7098429", "0.7076006", "0.7073898", "0.70719045", "0.7040176", "0.7039147", "0.7039147", "0.7034757", "0.7025848", "0.702152", "0.7018599", "0.70169264", "0.700814", "0.70025116", "0.69660443", "0.696193", "0.69611055", "0.69547504", "0.694612" ]
0.792789
8
returns the value at the beginning of the queue without removing it from the queue
peek() { return this._storage[this._headIndex]; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function peek(){\n return queue[0];\n }", "function dequeue(){\n return queue.shift();\n }", "peek(){\n return queue[queue.length -1]\n }", "peek() {\n if(this.queue.length) return this.queue[0]; \n else return null; \n }", "peek() {\n return this.queue[0]\n}", "peek () {\n return this.queue[this.front]\n }", "poll() {\n const top = this.queue.shift(); \n return top; \n }", "peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }", "peek() { // must not be called on an empty queue\n const front = this._front;\n const cursor = this._cursor;\n return front._elements[cursor];\n }", "peek() {\n return queue[queue.length - 1];\n }", "peek() {\n return queue[queue.length - 1];\n }", "dequeue() {\n try {\n if(this.isEmpty) return null\n\n const firstValue = this._storage[this._head]\n delete this._storage[this._head]\n this._head++\n this._length--\n return firstValue\n } catch(err) {\n throw new Error(err)\n }\n }", "getFrontElement(){\n return this.queue[this.front];\n }", "dequeue(){\n //if queue is empty, nothing to remove\n if(this.first === null){\n return;\n }\n\n //set pointer to first item\n const node = this.first\n\n //move pointer to next in the queue and make it first\n this.first = this.first.next;\n\n //if this is the last item in the queue\n if(node === this.last){\n this.last = null;\n }\n return node.value;\n }", "function dequeue() {\n return queue[index++];\n }", "dequeue() {\n if(! this.isEmpty()) return this.items.shift()\n else return undefined\n }", "dequeue() {\n if (this.tail > this.head) {\n const value = this.storage[this.head];\n delete this.storage[this.head];\n this.head++;\n return value;\n } else {\n return null;\n }\n }", "dequeue() {\n if (!this.first) return null;\n const temp = this.first;\n if (this.first === this.last) {\n this.first = null;\n }\n this.first = this.first.next;\n this.size -= 1;\n return temp.val;\n }", "dequeue() {\n return this.queue.shift()\n }", "remove() {\n if (!this.isEmpty()) {\n let firstElement = this.queue[0];\n this.queue.shift();\n this.length -= 1;\n return firstElement;\n } else {\n return null;\n }\n }", "peek() {\n if (this.isEmpty()) \n throw \"Queue is Empty\"; \n return this.queue[0]; \n }", "function peek(queue) {\n return queue.first.data;\n}", "shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }", "shift() { // must not be called on an empty queue\n const oldFront = this._front;\n let newFront = oldFront;\n const oldCursor = this._cursor;\n let newCursor = oldCursor + 1;\n const elements = oldFront._elements;\n const element = elements[oldCursor];\n if (newCursor === QUEUE_MAX_ARRAY_SIZE) {\n newFront = oldFront._next;\n newCursor = 0;\n }\n // No mutations before this point.\n --this._size;\n this._cursor = newCursor;\n if (oldFront !== newFront) {\n this._front = newFront;\n }\n // Permit shifted element to be garbage collected.\n elements[oldCursor] = undefined;\n return element;\n }", "dequeue() {\n return this._queue.shift();\n }", "dequeue() {\n const element = this.queue.binaryTree.shift();\n this.queue.binaryTree.unshift(this.queue.binaryTree.pop());\n this.queue.siftDown(0);\n return element;\n }", "dequeue() {\n this.size -= 1;\n return this.queue.shift();\n }", "front() {\r\n if(this.isEmpty()){\r\n console.log(\"Queue is empty\");\r\n return null;\r\n }\r\n return this.head;\r\n }", "dequeue() {\n if (0 != this.q.length) {\n let c = this.q[0];\n this.q.splice(0, 1);\n return c\n }\n }", "dequeue() {\n if (this.isEmpty()) {\n return null;\n }\n\n return this.list.shift().value;\n }", "dequeue() {\n //if the queue is empty, there is nothing to return\n if (this.first === null) {\n return;\n }\n const node = this.first;\n this.first = this.first.next;\n //if this is the last item in the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n const value = _(this).collection.shift();\n return value[0];\n }", "dequeue(){\n //if queue is empty there is nothing to return\n if(this.first === null){\n return;\n }\n const node = this.first;\n this.first = this.first.next;\n //if this is last item in queue\n if(node === this.last){\n this.last = null;\n }\n return node.value\n }", "dequeue() {\n if (!this.first) throw new Error(\"Cannot dequeue! Queue is empty\");\n let removed = this.first;\n // only one item in queue: remove it and set last to be null\n if (this.first === this.last) {\n this.last = null;\n }\n // set first to be what came after first, which will be null if queue has only one item\n this.first = this.first.next;\n this.size -= 1;\n return removed.val;\n }", "dequeue() {\n\t\t// the first item in the queue\n\t\tconst item = this.storage.remove_from_head();\n\t\tif (this.isEmpty() !== true) {\n\t\t\t// only do this if the item is not null\n\t\t\tthis.length--;\n\t\t}\n\n\t\treturn item;\n\t}", "get _queueFirst() {\n return this._queue[0];\n }", "dequeue() {\n return this.collection.shift()[0]\n }", "dequeue() {\n const firstValue = this._storage[this._headIndex];\n delete this._storage[this._headIndex];\n this._length--;\n this._headIndex++;\n return firstValue;\n }", "peek() {\n return this.queue.binaryTree[0];\n }", "front() {\n if (this._array.length === 0) {\n throw new error.NotFound('Queue is empty')\n }\n return this._array[0]\n }", "dequeue() {\n // Check if queue is empty\n if (this.first === null) {\n return null;\n }\n\n // Get the first node in the list\n let node = this.first;\n\n // Shift the next node in the queue to first\n this.first = this.first.next;\n\n // If the node is in the last position of the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "next() {\n return queue.shift();\n }", "dequeue() {\n //if the queue is empty, there is nothing to return\n if (this.first === null) {\n return;\n }\n const node = this.first;\n this.first = node.next;\n //if this is the last item in the queue\n if (node === this.last) {\n this.last = null;\n }\n return node.value;\n }", "dequeue() {\n if (!this.first) return null;\n\n let current = this.first;\n if (this.first === this.last) this.last = null;\n this.first = this.first.next;\n this.size--;\n return current.val;\n }", "dequeue() {\n const node = this.head;\n\n if (node === null) {\n console.log(new Error('No more items in the queue.'))\n return;\n }\n this.head = this.head.next;\n\n return node.value;\n }", "function peek(queue) {\n if (!queue.first) {\n return 'Queue is empty.';\n }\n \n return queue.first.value;\n }", "dequeue()\r\n {\r\n if (this.isEmpty()){\r\n return null;\r\n }\r\n return this.items.shift();\r\n }", "dequeue() {\n this._treatNoValues();\n return this.storage.shift();\n }", "dequeue() {\n if (this.isEmpty()) \n throw \"Queue is Empty\"; \n return this.queue.shift(); \n }", "dequeue() {\n return queue.pop()\n }", "dequeue() {\n // If the queue is empty, there is nothing to dequeue\n if ( this.first === null ) {\n return;\n };\n\n // Declare our node to dequeue\n const node = this.first;\n // Set the 2nd item in queue to our first\n this.first = this.first.next;\n\n // If this is the last item in the queue\n if ( node === this.last ) {\n // Set our last to null\n this.last = null;\n };\n\n return node.val;\n }", "remove() {\n if (this.isEmpty()) throw new Error('Queue is empty!');\n const value = this.first.value;\n this.first = this.first.next;\n this.size--;\n return value;\n }", "dequeue() {\n // Time Complexity O(n)\n return this.list.shift();\n }", "peek() {\n const peekData = this.queue[0];\n debug(`\\nLOG: ${peekData} is on peek of the queue`);\n return peekData;\n }", "dequeue() {\n return this.items.shift();\n }", "dequeue(){\n if(this.isEmpty()){\n throw Error ('The Queue is Empty, Unable to dequeue()');\n }else{\n const removingElement = this.queue[this.front];\n this.front +=1;\n return removingElement;\n }\n }", "dequeue() {\n\t\treturn this.items.shift();\n\t}", "dequeue() {\n // set a variable equal to the object keys array\n var keys = Object.keys(this.storage);\n // set a variable equal to the lowest key value\n var lowest = this.storage[keys[0]];\n // delete the lowest key value\n delete this.storage[keys[0]];\n // return the lowest key value variable\n return lowest;\n }", "dequeue() {\n if (this.first === null) {\n return;\n }\n // we need to save this first node before replacing it so that we can check\n // if it is the only item on the list\n const node = this.first;\n this.first = this.first.next;\n if (node === this.last) {\n this.last = null;\n }\n // need this to be returned so you can use its value later\n this.size--;\n return node.value;\n }", "dequeue() {\n if(!this.isEmpty()) {\n return this.collection.shift();\n } else {\n console.log(\"Queue is already empty\");\n }\n }", "dequeue() {\n\t\tif ( this.size() >= 1 ) {\n\t\t\tlet nextUp = this._storage[this._start];\n\t\t\tdelete this._storage[this._start];\n\n\t\t\tif ( this._start == this._end ) {\n\t\t\t\tthis._start = this._end = -1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthis._start++;\n\t\t\t}\n\t\t\treturn nextUp;\n\t\t}\n\t\telse {\n\t\t\tconsole.log(\"Queue is Empty!\");\n\t\t\treturn false;\n\t\t}\n\t}", "peek() {\n if(this.size > 0){\n return this.first.val;\n }\n }", "dequeue() {\n if (this.size === 0) {\n return null\n }\n var temp = this.first;\n if (this.first === this.last) {\n this.last = null;\n }\n // remove from the head\n this.first = this.first.next\n this.size--\n return temp.value;\n }", "dequeue() {\n this.queue.shift()\n}", "front(){\n if(this.isEmpty()){\n return \"Empty Queue\" \n }\n return this.items[0];\n }", "remove(){\n /*as it's FIFO so just need to remove the first node and \n adjust the next node in the Queue to be the first node after \n the removal of the first node.*/\n\n const firstNode = this.first;\n\n //check if Queue is empty then return undefined\n\n if (firstNode === null){\n return undefined;\n }\n\n //make this.first point to next node\n this.first = firstNode.after;\n\n //check if the Queue only had one node\n if(this.first === null){\n this.last = null;\n }\n\n this.qLength--;\n\n return firstNode.value;\n }", "dequeue() {\n\t\treturn this.shift();\n\t}", "peek () {\n return this.head[0]\n }", "shift() {\n if (this.length === 0) throw new Error(\"No more items in queue\");\n\n const oldHead = this.head;\n\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = oldHead.next;\n oldHead.next = null;\n }\n\n this.length--;\n\n return oldHead.val;\n }", "front() {\n\t\tif (this.isEmpty()) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn this._dummyHead.prev.value;\n\t}", "peek() {\n return this.items.head.value;\n }", "peek() {\n if (this.isEmpty()) {\n return null;\n }\n\n return this.list.head.value;\n }", "dequeue() {\n if(this.items.length > 0) {\n return this.items.shift();\n }\n }", "peek() {\n\t\treturn this.head ? this.head.value : null;\n\t}", "peek(){\n if(this.isEmpty()){\n return undefined;\n }\n\n return this.items[this.count - 1];\n }", "dequeue() {\n return this.collection.shift();\n }", "getFirstCome() {\n var lowestTime = this.queue[0].getArrivalTime();\n var jobFinal = this.queue[0];\n for(var i=0; i<this.queue.length; i++) {\n var job = this.queue[i];\n if(lowestTime > job.getArrivalTime()) {\n lowestTime = job.getArrivalTime();\n jobFinal = job;\n }\n }\n return jobFinal;\n }", "dequeue(){\n let dequeue = this.linkedList.deleteHead();\n return dequeue ? dequeue.value : null;\n }", "dequeue() {\n if (this.length === 0) throw new Error(\"No more items in queue\");\n\n const oldHead = this.head;\n\n if (this.length === 1) {\n this.head = null;\n this.tail = null;\n } else {\n this.head = oldHead.next;\n oldHead.next = null;\n }\n\n this.length--;\n\n return oldHead.val;\n }", "pop() {\n // If head is null, there's nothing on the list\n if (this.head == null) {\n return null;\n } else {\n // Get the item that will be popped from the queue\n const extractedItem = this.head;\n\n // Set the next item in the queue as the new head\n this.head = this.head.next;\n\n // Returned the previous head\n return extractedItem;\n }\n}", "front() {\n\t\treturn this.items.head.value;\n\t}", "dequeue() {\n return this.collection.shift();\n }", "deque() {\n if (this.front == -1) {\n console.log(\"Queue is empty\");\n return null;\n }\n var ele = this.items[this.front++];\n this.Size--;\n if (this.front > this.rear) {\n this.front = this.rear = -1;\n }\n return ele;\n }", "dequeue() {\n if(this.size === 0){\n throw Error('queue is empty');\n }\n\n // linkedList\n // const returnVal = this._linkedList.shift();\n // this.first = this._linkedList.head;\n // this.last = this._linkedList.tail;\n // this.size = this._linkedList.length;\n\n // array\n const returnVal = this._array.shift().val;\n this.first = this._array[0];\n this.last = this._array[this._array.length - 1];\n this.size = this._array.length;\n\n return returnVal;\n }", "front()\r\n {\r\n if (this.isEmpty()){\r\n return null;\r\n }\r\n return this.items[0];\r\n }", "dequeue() {\n if (this.count === 0) {\n return 0;\n }\n var firstIdx = Object.keys(this.storage)[0];\n var itemToRemove = this.storage[firstIdx];\n delete this.storage[firstIdx];\n this.count -= 1;\n return itemToRemove;\n }", "front() {\n if (this.isEmpty()) {\n return \"Queue is empty of elements.\";\n } else {\n return this.items[0];\n }\n }", "peek() {\n if(! this.isEmpty()) return this.items[0]\n else return undefined\n }", "dequeue() {\n if (this.head !== null) {\n return 'No item !'\n } else {\n let itemToPop = this.head;\n this.head = this.head.next;\n return itemToPop;\n }\n }", "next () {\n const element = this.queue.shift()\n this.keys.delete(element.key)\n\n return element\n }", "peek() {\n return this.head.value;\n }", "peek() {\n\t\treturn !this.isEmpty() ? this.items[0] : undefined;\n\t}", "peek(){\n var topElement = this.start;\n return topElement;\n }", "dequeue() {\n if (!this.first) return null;\n\n let temp = this.first;\n // 1 node left\n if (this.first === this.last) {\n this.last = null;\n }\n // so if one node left, this.first.next is also null\n // first and last pointer overlap\n this.first = this.first.next;\n this.size--;\n\n return temp.value;\n }", "dequeue() {\n if (this.isEmpty) { throw new Error(\"Can't remove from empty queue\") };\n return this.#queue.pop();\n }", "dequeue() {\n if (this.count == 0) {\n return undefined;\n }\n let deletedItem = this.items[0];\n this.items.splice(0, 1);\n this.count--;\n return deletedItem;\n }", "pop() {\n if (this._array.length === 0) {\n throw new error.NotFound('Queue is empty')\n }\n return this._array.shift()\n }", "dequeue() {\n\n //如果是剛建立,沒有任何node的queue,this._head的初始數值就是null\n if (!this.head) {\n return null;\n }\n\n const valueOfHeadNode = this._head;\n\n if (this.head === this.tail) {\n // 如果目前queue只有一個元素,這樣頭跟尾都的地址都是同一個node\n // 所以 this._head === this._tail 等於拿同一個node做比較\n this.head = null;\n this.tail = null; // 利用null值來清空目前的queue\n } else {\n this.head = this.head.nextNode;\n // tail 不變\n }\n\n // 無論是if或是else condition,都會減少一個元素,所以要更新nodesCounts\n this._subtractNodesCounter();\n return valueOfHeadNode;\n }", "dequeue() {\n\t\tif (this.isEmpty()) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst node = this._dummyHead.prev;\n\t\tconst newFirst = node.prev;\n\t\tthis._dummyHead.prev = newFirst;\n\t\tnewFirst.next = this._dummyHead;\n\t\t// unlink the node to be dequeued.\n\t\tnode.prev = null;\n\t\tnode.next = null;\n\t\tthis._length--;\n\t\treturn node.value;\n\t}", "dequeue() {\n this._queue.shift();\n }" ]
[ "0.8130133", "0.7743013", "0.77359235", "0.7701163", "0.7637453", "0.7606839", "0.7557013", "0.75062275", "0.75062275", "0.74636436", "0.74636436", "0.7462822", "0.7422986", "0.74203724", "0.7416103", "0.74112743", "0.7403634", "0.73791283", "0.73768806", "0.73679686", "0.7356918", "0.73552734", "0.73461354", "0.73461354", "0.7344961", "0.7343905", "0.73428476", "0.7342779", "0.7329565", "0.73208374", "0.7308856", "0.7307093", "0.72994274", "0.7285571", "0.72847605", "0.7281953", "0.7276623", "0.7274188", "0.72656345", "0.72641236", "0.7261393", "0.724322", "0.71978235", "0.71868074", "0.7127237", "0.71117353", "0.7085478", "0.7057858", "0.7052107", "0.70392436", "0.70250607", "0.7018583", "0.7016201", "0.7011653", "0.7010575", "0.70102656", "0.699649", "0.69960475", "0.6980051", "0.697386", "0.6973193", "0.69596505", "0.69463664", "0.6946268", "0.6934811", "0.69087493", "0.6901122", "0.6877695", "0.68741304", "0.687401", "0.6861062", "0.68585384", "0.6852577", "0.68288267", "0.6820768", "0.6815425", "0.6814275", "0.68103045", "0.6806269", "0.6803776", "0.6800615", "0.67968565", "0.6794305", "0.678269", "0.6764756", "0.67518103", "0.67502034", "0.6738287", "0.6734729", "0.6731944", "0.6723032", "0.6718233", "0.6716319", "0.66907793", "0.66803145", "0.6673546", "0.66685724", "0.66551584", "0.665423", "0.66454303" ]
0.6777053
84
value:2 for default vallue:1 for waiting value:0 for printed
function getFile(file) { fakeAjax(file,function(text){ // what do we do here? if(text=="The first text"){ console.log("The first text"); status[text]=0; if(status["The middle text"]==1){ console.log("The middle text"); status["The middle text"]=0; if(status["The last text"]==1){ console.log("The last text"); status["The last text"]=0; } } } else if(text=="The middle text"){ if(status["The first text"]==2){ status["The middle text"]=1; } else{ console.log("The middle text"); status["The middle text"]=0; if(status["The last text"]==1){ console.log("The last text"); status["The last text"]==0; } } } else{ if(status["The middle text"]==0){ console.log(text); status["The last text"]=0; } else { status["The last text"]=1; } } }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function printVal(value) {\n console.log(value);\n // return 1; // error\n}", "static get PAUSE() { return 4; }", "function print(value){ // => the word value here is a parameter/placeholder/passenger\r\n console.log(value);\r\n }", "function next() {\n setValue(()=>{\n return checkValue(value+1)\n })\n }", "function printValue(value) {\n console.log(value);\n}", "doAction (value) {\n if (!this._params.simulate) {\n this._actuator.write(value.state === true ? 1 : 0, () => {\n this.addValue(value.state)\n })\n } else {\n this.addValue(value.state)\n }\n\n value.status = 'completed'\n\n console.info('Changed value of %s to %s', this._model.name, value.state)\n }", "value() {return 0}", "function first(value,callback){\n callback(value+2,false);\n}", "function showValue(val,slidernum) {\n // console.log(val);\n}", "function value(val) {\n if (typeof val === 'undefined') {\n return initVal\n } else {\n initVal = val\n value.emit('change', initVal)\n }\n }", "async function waiting() {\n const value = await num2();\n console.log('waiting', value);\n}", "function cb_set_2(num) {\n print(\"element \" + num); // B3 B6 B9 B15 B18 B21 B27 B30 B33\n return true; // B4 B7 B10 B16 B19 B22 B28 B31 B34\n} // B5 B8 B11 B17 B20 B23 B29 B32 B35", "async function print() {\n // await use to promise\n let value = await getValue();\n value = await getNewValue(value);\n return value;\n}", "function print_observe_tx(value) {\n console.log(\"OBSERVE_TX=\" + value + \": POLS_CNT=\" + (value >> consts.PLOS_CNT) & parseInt('1111', 2) + \" ARC_CNT=\" + (value >> consts.ARC_CNT) & parseInt('1111', 2));\n\n\n }", "function dosth_hoisted(value){\n var test;\n\n if(value){\n console.log(\"value\");\n }\n\n console.log(\"finished execution\");\n}", "function value() { }", "function print(value) {\n console.log(value)\n}", "function showValue(newValue) {\n\n\tif (newValue === 0) {\n\t\t$('#showRange').html(\"&nbsp;slow&nbsp;\");\n\t\twait = 250;\n\t} else if (newValue === 25) {\n\t\t$('#showRange').html(\"&nbsp;still slow&nbsp;\");\n\t\twait = 200;\n\t} else if (newValue === 50) {\n\t\t$('#showRange').html(\"&nbsp;medium&nbsp;\");\n\t\twait = 150;\n\t} else if (newValue === 75) {\n\t\t$('#showRange').html(\"&nbsp;fast&nbsp;\");\n\t\twait = 100;\n\t} else if (newValue === 100) {\n\t\t$('#showRange').html(\"&nbsp;faster&nbsp;\");\n\t\twait = 50;\n\t} else if (newValue === 125) {\n\t\t$('#showRange').html(\"&nbsp;warp 10&nbsp;\");\n\t\twait = 25;\n\t}\t\n}", "print({ value: newValue, previous: oldValue }) {\n console.log('> ', newValue, oldValue);\n }", "function activacion(valor) {\n return valor >= 0 ? 1 : 0;//Devuelvo 1 o 0 dependiendo si la condicion se cumple\n }", "SetCounterValue() {}", "function print(value){console.log(value)}", "function block(){\n flag2=0;\nv=2;\n}", "next(){\n if(max>0){\n return {value: max--, done: false}\n }else{\n return {value: undefined, done: true}\n }\n\n }", "updateValue() {\n if (this.value < 10) {\n this.spinner1.notchId = 0;\n this.spinner2.notchId = this.value;\n }\n else {\n var tmp = this.value.toString();\n var digit1 = tmp[0];\n var digit2 = tmp[1];\n this.spinner1.notchId = parseInt(digit1);\n this.spinner2.notchId = parseInt(digit2);\n }\n }", "propagateValue() {\n this.dialOutputs[this.value - 1].activate()\n }", "function waitForNewValue(){\n io.socket.on('newDeviceState', function (deviceState) {\n // if the device is the current device, push the value in the graph\n if(vm.currentDeviceType && deviceState.devicetype == vm.currentDeviceType.id){\n $scope.$apply(function(){\n vm.currentDeviceType.value = deviceState.value;\n if(vm.currentDeviceType.type == 'binary'){\n if(vm.currentDeviceType.value == 1) {\n vm.currentDeviceType.value = \"ON\"\n }else{\n vm.currentDeviceType.value = \"OFF\"\n }\n // if is binary, change icon\n getIcon() \n }\n });\n }\n });\n }", "printResult(value) {\n if (value === \"\") {\n // if value is a string print it\n document.getElementById(\"result\").innerText = value;\n return;\n } else {\n // if value in not a string, first convert in to string and then print it\n document.getElementById(\"result\").innerText = this.numToStr(value);\n }\n }", "function getVal() {\n return 5;\n}", "function announceResult(n, v) {\n\tconsole.log(`The number in position ${n} in the Fibonacci sequence is`, v);\n}", "function value(val) { return control_1.default(val); }", "function hasvalue(p){\n //console.log(v);\n if(p){\n let v=\"blue\";\n console.log(v);\n }else{\n let v=\"red\";\n console.log(v);\n }\n //console.log(v);\n}", "function valueCondition() {\n let variable = prompt(\"Введите значение переменной:\");\n variable = Number(variable);\n if (variable == 10) {\n console.log(\"1) Squaring result: Верно\"); \n } else {\n console.log(\"1) Squaring result: Неверно\");\n };\n \n }", "_seqCallback(time, value) {\n if (value !== null && !this.mute) {\n this.callback(time, value);\n }\n }", "function indicator (value)\n{\n switch (value)\n {\n case 0 :\n {\n return \"Off\";\n }\n case 1 :\n {\n return \"On\";\n }\n case 2 :\n {\n return \"Failed\";\n }\n default :\n {\n return \"Reserved\";\n }\n }\n}", "function fillWithValues(value) {\n div .transition() \n .duration(200) \n .style(\"opacity\", .9); \n div .html(function () {\n var starttxt = \"<span style=\" + \"font-size:12pt>\" + value + \"</span><br><br>Click to \";\n var endtxt = \"<br>Press b to go back a message.\";\n if (n == 0 && messages.length == 1) {\n return starttxt + \"close.\";\n } else if (n == 0) {\n return starttxt + \"continue...\"; \n } else if (messages.length > (n + 1)) {\n return starttxt + \"continue...\" + endtxt;\n } else {\n return starttxt + \"close.\" + endtxt;\n }\n });\n }", "function v(num) {\r\n\tif (output.value == '0') {\r\n\t\toutput.value = num;\r\n\t} else {\r\n\t\toutput.value = output.value + num;\r\n\t}\r\n}", "function printer(value){\r\n return value; // => example of a function that can optionally take arguments \r\n}", "function printOne(callback) {\n setTimeout(function () {\n console.log('1');\n return callback();\n }, 100 * Math.random());\n}", "function fn1(val) {\n console.log(1, val);\n}", "function valueOutput(element) {\n var value = element.value,\n output = element.parentNode.getElementsByTagName('output')[0];\n output.innerHTML = value+\" kms\";\n }", "get STATE_AWAIT() { return 5; }", "_valueChanged(v) {\n if(this._startHandle) {\n var valid = this._validateValue(v, 'value');\n if(valid) {\n this._moveHandle(this._startHandle, v);\n this.setAttribute('aria-valuenow',v);\n }\n }\n }", "writeValue() { }", "function get(value) {\n console.log('everything is ' + value);\n}", "function printing() {\n console.log(1);\n setTimeout(function() {\n console.log(2);\n }, 1000);\n setTimeout(function() {\n console.log(3);\n }, 0);\n console.log(4);\n }", "function outPutMessage(value) {\n\t if (callBackOutput) {\n\t callBackOutput(value);\n\t }\n\t }", "function printOutput(num)\n{\n\tdocument.getElementById(\"output-value\").innerText=num;\n}", "function changeGPIOValue(){\n var hl = $('#gpio_value').val();\n $('#gpio_not_value').html((hl == 0) ? \"HIGH\" : \"LOW\");\n}", "function grab(val) {\n console.log(val);\n}", "function printOutput(num){\r\n\tdocument.getElementById(\"output_value\").innerText=num;\r\n}", "function output(id, value) {\n player = !player;\n document.getElementById(id).innerHTML = value;\n }", "function lg(tema, value) {\n console.log(`-- ${tema} --`);\n console.log(value);\n}", "function log(value, desc) {\n if (value) {\n console.log(\"\\033[32m \" + desc + \"\\033[0m\");\n } else {\n console.log(\"\\033[31m \" + desc + \"\\033[0m\");\n }\n}", "function setVisualStatus(value){\n if (value == \"Pending\"){\n setServoDegrees(80); // Top\n }\n else if (value == \"Sunny\"){\n setServoDegrees(-20); // Bottom\n }\n else if (value == \"Rain\"){\n setServoDegrees(30); // Middle\n }\n //devicelog(false,value);\n}", "value(value) {\n this.performAction();\n this.activeId = value;\n this.performAction();\n }", "formatIntegerObjectiveValue ( mode = 0) {}", "function queueRenderer(value) {\n\t\treturn (value == -1) ? '' : value + 1;\n\t}", "function queueRenderer(value) {\n\t\treturn (value == -1) ? '' : value + 1;\n\t}", "function doubleValue(value) {\n value *= 2;\n console.log(\"-->\", value)\n}", "get value() {\n return this.mode === 'determinate' ? this._value : 0;\n }", "static get WAITING_INIT () { return 0; }", "function sequencia1(num) {\n return 0\n}", "function initWatchVal() {} // 16439", "enterIntegerValue(ctx) {\n }", "function setTargetValue() {\n targetValue = Math.floor(Math.random() * 100) + 20;\n console.log(\"tv \" + targetValue);\n $(\"#target\").text(targetValue);\n alphaValue = Math.floor(Math.random() * 11) + 1;\n console.log(\"a \" + alphaValue);\n betaValue = Math.floor(Math.random() * 11) + 1;\n console.log(\"b \" + betaValue);\n gammaValue = Math.floor(Math.random() * 11) + 1;\n console.log(\"g \" + gammaValue);\n zappaValue = Math.floor(Math.random() * 11) + 1;\n console.log(\"z \" + zappaValue);\n}", "function sequencia2(num) {\n return 0\n}", "enterWaitDelayValue(ctx) {\n\t}", "function display(n){\n document.write(\"<br/><font color=red> Value is \"+n+\"</font>\") \n // while display time big logic. \n}", "function countdown() {\n console.log(5)\n console.log(4)\n console.log(3)\n console.log(2)\n console.log(1)\n}", "function prev() {\n setValue(()=>{\n return checkValue(value-1)\n })\n }", "function getValue(callback) {\n let value = 0;\n setTimeout(function () {\n value = 10;\n callback(value);\n }, 2000);\n return value;\n}", "set Pause(value) {}", "function callback(err,msg){\n\tif(err){\n\t\tconsole.log('The value is False')\n\t}else{\n\t\tconsole.log(msg+' The value is True')\n\t}\n}", "function setValue(val, vertical) {\n document.getElementById(\"slider\").value = 3;\n showValue(val, vertical);\n}", "setPrecUnmuteVal(value) { // prev, new \n let precUnmuteVal = this.getSetting(\"prec-unmute-val\"); \n if (value != \"true\" && value != \"false\") {\n this.logColouredText(\"blue\", \"PUM: \" + precUnmuteVal); \n return precUnmuteVal; \n } else {\n this.setSetting(\"prec-unmute-val\", value); \n /*\n I done this so the unit test wouldn't fail [not good], but I'd like to ensure the number of read/writes are as small as possible \n */ \n precUnmuteVal = this.getSetting(\"prec-unmute-val\"); \n // console.log(precUnmuteVal)\n this.logColouredText(\"blue\", \"[changes made] PUM: \" + value); \n // console.log(precUnmuteVal); \n return precUnmuteVal; \n } \n }", "function print(value) {\n\t$('#rokResult').val($('#rokResult').val()+value);\n}", "function showValue(value, state) {\n return (state < 3) ? '' : value;\n }", "function promised(val) {\n return new Promise(resolve => setTimeout(() => resolve(val), 2000));\n}", "function nextOneMode() {\n if (b != 2) {\n b = b + 1;\n document.getElementById(\"test\").innerHTML = b;\n sendRequest(\"camera\", c, b);\n }\n}", "static get DONE() {\n return 3;\n }", "function changePlayerValue(){\n if(player.value == 0){\n player.value = 1;\n }\n else{\n player.value = 0;\n }\n}", "async function print_nlpResp(val) {\n let nlpResp = await get_nlpResp(val);\n let nlpPos = \"displayLeft\";\n\n setTimeout(() => {\n updateLog(nlpResp, nlpPos);\n }, respTime);\n}", "async function print1() {\n await sleep();\n console.log(\"1\");\n}", "function value1() {\n\tvar text = \"Same text.\";\n\tdocument.getElementById(\"value\").innerHTML = text.valueOf();\n}", "updateValue(arg1, arg2) {\n return \"une string\"\n }", "static get STOP() { return 3; }", "function println(value) {\n\t$('#rokResult').val($('#rokResult').val()+\"\\n\"+value);\n}", "function showVal(newVal, num){\n document.getElementById(\"demo\"+num).innerHTML= newVal;\n updateServings();\n}", "enterValue(ctx) {\n\t}", "slotValue() {\n\t\tlet rv = undefined\n\t\t\t, self = this;\n\n\t\twithIntegrity(null,null, function () {\n\t\t\tlet vPrior = self.pv;\n\t\t\trv = self.ensureValueIsCurrent( 'c-read', null);\n\t\t\t//clg('evic said',rv.toString());\n\t\t\tif (!self.md && self.state === kNascent\n\t\t\t\t&& gpulse() > self.pulseObserved) {\n\t\t\t\tself.state = kAwake;\n\t\t\t\tself.observe(vPrior, 'cget');\n\t\t\t\tself.ephemeralReset();\n\t\t\t}\n\t\t});\n\t\tif (depender) {\n\t\t\tdepender.recordDependency(this);\n\t\t}\n\t\treturn rv;\n\t}", "function output(value) {\n debug.innerHTML = value;\n return true;\n}", "function ensure_have_value( name, value, isExitIfEmpty, isPrintValue, fnNameColorizer, fnValueColorizer ) {\n isExitIfEmpty = isExitIfEmpty || false;\n isPrintValue = isPrintValue || false;\n fnNameColorizer = fnNameColorizer || ( (x) => { return cc.info( x ); } );\n fnValueColorizer = fnValueColorizer || ( (x) => { return cc.notice( x ); } );\n var retVal = true;\n value = value.toString();\n if( value.length == 0 ) {\n retVal = false;\n console.log( cc.fatal(\"Error:\") + cc.error(\" missing value for \") + fnNameColorizer(name) );\n if( isExitIfEmpty )\n process.exit( 666 );\n }\n var strDots = \"...\", n = 50 - name.length;\n for( ; n > 0; -- n )\n strDots += \".\";\n log.write( fnNameColorizer(name) + cc.debug(strDots) + fnValueColorizer(value) + \"\\n\" ); // just print value\n return retVal;\n}", "function z2volume()\n {\n var volValue = document.getElementById('z2vol').value;\n\n if (volValue < 10){\n connection.send('Vol z20'+volValue);\n }\n else{\n connection.send('Vol Z2'+volValue)\n }\n document.getElementById('z2sliderVal').innerHTML = volValue;\n }", "set value(value) {}", "function cinco() {\n\t\t\t\t\treturn 5;\n\t\t\t\t}", "next() {\n if (this.current == \"one\") {\n this.current = \"two\";\n return { done: false, value: \"one\" };\n } else if (this.current == \"two\") {\n this.current = \"\";\n return { done: false, value: \"two\" };\n }\n return { done: true };\n }", "write() {\n let value = constrain(this.#state.value, 0, 1);\n if (this.#state.sink) {\n value = 1 - value;\n }\n value = map(value, 0, 1, this.LOW, this.HIGH);\n this.io.write(value);\n }", "function changeValue(questo) {\n switch(questo.parentElement.textContent) {\n case \"tracer\":\n tracerVar = questo.checked;\n break;\n case \"NoRecoil\":\n recoilHack = questo.checked;\n break;\n case \"NoSpread\":\n SpreadHack = questo.checked;\n break;\n case \"instaBreak\":\n instaBreak = questo.checked;\n break;\n case \"noReload\":\n noReload = questo.checked;\n break;\n case \"noBlockUpdate\":\n noBlocksUpdate = questo.checked;\n break;\n case \"noClip\":\n noClip = questo.checked;\n break;\n case \"jumpyGlitch\":\n jumpyGlitch = questo.checked;\n break;\n case \"noChat\":\n document.getElementsByClassName(\"Chat__Wrapper-sc-16u2dec-0 cOWABl\")[0].style.display = questo.checked ? \"none\" : \"initial\";\n break;\n case \"listPlayer\":\n listPlayerValue = questo.checked;\n document.getElementById(\"players\").style.display = listPlayerValue ? \"initial\" : \"none\";\n break;\n case \"noKillFeed\":\n document.getElementsByClassName(\"KillFeed__Wrapper-sc-1xasb9r-0 byxfaz\")[0].style.display = questo.checked ? \"none\" : \"initial\";\n break;\n case \"waterSpeed\":\n waterSpeed = parseFloat(questo.value);\n break;\n case \"waterSpeedVer\":\n waterSpeedVer = parseFloat(questo.value);\n break;\n case \"ChunkSize\":\n chunkSize = parseInt(questo.value);\n break;\n case \"aimbot\":\n aimbotHack = questo.checked;\n break;\n case \"hitbox\":\n hitboxhack = questo.checked;\n break;\n }\n}", "function assert(value, desc){\r\n\tConsole.log(\"Result \" + value + desc);\r\n}", "function printValue(value) {\n\tvar log = console.log;\n\tswitch (typeof value) {\n\t\tcase 'number':\n\t\t\tlog('Number: ' + value);\n\t\t\tbreak;\n\t\tcase 'string':\n\t\t\tlog('String: ' + value);\n\t\t\tbreak;\n\t\tcase 'object':\n\t\t\tlog('Object: ' + value);\n\t\t\tbreak;\n\t\tcase 'boolean':\n\t\t\tlog('Number: ' + value);\n\t\t\tbreak;\n\t}\n}" ]
[ "0.5916579", "0.58305335", "0.58298475", "0.58161443", "0.5808925", "0.56767595", "0.56534946", "0.5634155", "0.56337607", "0.56108195", "0.55911165", "0.55774146", "0.5572823", "0.5553151", "0.5546801", "0.5533161", "0.5516638", "0.55052686", "0.54891646", "0.5472748", "0.5462152", "0.54512304", "0.5436489", "0.54304224", "0.5417869", "0.5413778", "0.54064894", "0.53928083", "0.5371833", "0.5323547", "0.53216094", "0.53196764", "0.53133655", "0.5305584", "0.5255113", "0.5248818", "0.5230494", "0.5230203", "0.52275556", "0.52111167", "0.52073264", "0.5202523", "0.5196763", "0.51909", "0.51799905", "0.5175758", "0.51678056", "0.51520187", "0.51514316", "0.51513845", "0.5149425", "0.5130901", "0.51052594", "0.5093982", "0.5086177", "0.50849336", "0.5082442", "0.50776356", "0.50776356", "0.507304", "0.5070935", "0.5069957", "0.50689775", "0.50663394", "0.5062931", "0.50575876", "0.5056495", "0.5055462", "0.5052377", "0.5047005", "0.5045374", "0.5044269", "0.50389326", "0.5027136", "0.50268817", "0.50263417", "0.50203323", "0.5008562", "0.5008409", "0.49966273", "0.4994133", "0.4990234", "0.49877876", "0.49827456", "0.49736512", "0.49732295", "0.49731848", "0.49725142", "0.49684736", "0.4967415", "0.49657795", "0.49611813", "0.49604663", "0.49546525", "0.49539465", "0.4952575", "0.49499673", "0.49495947", "0.4945873", "0.4942046", "0.4938817" ]
0.0
-1
highlight the given sequence
function hSeq(seq) { /** unhighlight all others */ for (var i=0; i<sequences.length; i++) hmatch(sequences[i], false); /** highlight selected sequence */ hmatch(sequences[seq], true); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "highlight(on) { }", "function highlight() {\n if (window.getSelection) {\n var selection = window.getSelection();\n if (selection.rangeCount) {\n var range = selection.getRangeAt(0).cloneRange();\n var highlightNode = document.createElement(\"span\");\n highlightNode.setAttribute(\"id\", \"highlighted\");\n highlightNode.setAttribute(\"style\", \"background-color:#FFFF00\");\n range.surroundContents(highlightNode);\n selection.removeAllRanges();\n }\n }\n}", "function highlight(part, i){\n document.getElementById(\"myAnimation\"+i).innerHTML = fiveWords[i-1];\n var inputText = document.getElementById(\"myAnimation\"+i);\n var innerHTML = inputText.innerHTML;\n var highlightedPart = innerHTML.substring(0, part.length);\n var restOfWord = innerHTML.substring(part.length, innerHTML.length);\n \n innerHTML = \"<span class='highlight'>\" + highlightedPart + \"</span>\" + restOfWord;\n inputText.innerHTML = innerHTML;\n \n// if(highlightedPart.localeCompare(fiveWords[i-1]) == 0){\n// document.getElementById(\"myAnimation\"+i).innerHTML = fiveWords[i-1]; \n// }\n}", "highlightLine(line_num)\n{\n this.highlightSet = line_num;\n}", "function highlightRewritten(selection, container, anchorNode, focusNode, anchorOffset, focusOffset, highlightColor, uniqueId){\n // NOTE: Look at highlightTry6 for the current highlight function\n}", "function highlight(text) {\n var src_str = $(\"#demo\").html();\n var term = text;\n term = term.replace(/(\\s+)/, \"(<[^>]+>)*$1(<[^>]+>)*\");\n var pattern = new RegExp(\"(\" + term + \")\", \"gi\");\n\n src_str = src_str.replace(pattern, \"<mark>$1</mark>\");\n src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\\/mark>)/, \"$1</mark>$2<mark>$4\");\n\n $(\"#demo\").html(src_str);\n}", "function highlight(props){\n //change stroke\n var selected = d3.selectAll(\".\" + props.adm1_code)\n .style(\"stroke\", \"#62030F\")\n .style(\"stroke-width\", \"3\");\n\n setLabel(props);\n } //last line of highlight function", "highlight() {\n if (arguments.length === 2) {\n this._highlightedPositionsToBe.push({ line: arguments[1], col: arguments[0], type: '.' });\n } else if (arguments.length === 1) {\n let { line, col } = linearPosToLineCol(this._lines.join('\\n'), arguments[0]);\n this._highlightedPositionsToBe.push({ line, col, type: '.' });\n } else throw new Error(`highlight: invalid arguments`);\n }", "function highlightAnnotation(range, role){\n var s = range.start;\n var e = range.end;\n var r = new Range(s.row, s.column, e.row, e.column);\n currentHighlight = editor.getSession().addMarker(r,\"line-style-\" + role, \"text\");\n}", "function highlight(){\r\n\tfor(var i=0; i<wordItems.length; i++)\r\n\t\twordItems[i].style.color = \"red\";\r\n}", "function highlight() {\r\n\tthis.style.backgroundColor = '#ff0';\r\n}", "highlight(index) {\r\n if (this.state.active === index) {\r\n return \"#f5f5f5\";\r\n }\r\n return \"\";\r\n }", "function highlightLine(highlight) {\n d3.selectAll('.elm')\n .transition()\n .style('opacity', 0.1)\n .style('stroke-width', 1)\n\n var n = highlight.length;\n for (var i = 0; i < n; i++) {\n d3.selectAll('.sel-'+highlight[i]).transition()\n .style('opacity', 1).style('stroke-width', 3);\n }\n }", "function highlightText(list) {\n var previouslndex = null;\n list.click(function(){\n currentIndex = list.index(this);\n if (currentIndex != previouslndex){\n list.removeClass('highlight');\n $(this).addClass('highlight');\n previouslndex = currentIndex;\n }else{\n $(this).toggleClass('highlight');\n }\n \n });\n}", "function highlight(userId ) { \n \n var result = getTextNodeFromSelection();\n var textNode = result[1];\n var error = result[0]\n error = error || checkAnnoationExisted(textNode);\n \n if (!error && textNode.toString().length > 1) \n { \n //Generate an unique ID for the annotation \n var annotationPanelID = generateId(); \n var sNode = document.createElement(\"span\");\n sNode.id = annotationPanelID;\n sNode.className = \"annotate-highlight\"; \n try\n {\n textNode.surroundContents(sNode); \n }\n catch(err)\n {\n console.log(err);\n return -1\n } \n \n var parent = getParentElem(textNode);\n var pidx = 0;\n var widx = 0;\n if (parent != null) {\n pidx = getParagraphIndex(parent);\n console.log(pidx);\n widx = getWordIndex(parent, textNode);\n sNode.setAttribute('value', pidx + ',' + widx);\n }\n \n var panel = appendPanel(annotationPanelID, textNode.toString(), userId, pidx, widx, annotationState.NEW, 0);\n \n return annotationPanelID;\n }\n else if (textNode.toString().length != 0 ) {\n //TODO: Show a proper UI such as notification for error \n return -1;\n } \n}", "function highlight(props){\r\n //change stroke\r\n var selected = d3.selectAll(\".\" + props.CODE)\r\n .style(\"stroke\", \"blue\")\r\n .style(\"stroke-width\", \"2\");\r\n setLabel(props);\r\n}", "highlight_correct() {\n\t\t\tthis.selection_board.get_shape(this.shape).set_highlight('green');\n\t\t\tthis.selection_board.draw();\n\t\t}", "function highlight(target, activate) {\n if (!activate) console.log('#######################################')\n const rings = [ringOne, ringTwo, ringThree, ringFour, ringFive]// .filter((e, idx) => !(idx + 1 === target))\n const thisRing = rings.splice(target, 1)\n\n if (activate) {\n rings.forEach((each, idx) => { each.attr('fill', colours[idx].inactive) })\n } else {\n rings.forEach((each, idx) => each.attr('fill', colours[idx].default))\n }\n thisRing.forEach(each => each.attr('fill', activate ? colours[target].hover : colours[target].default))\n}", "function highlight() {\n d3.select(this).classed('selected', true)\n }", "function highlight_words() {\n\n // YOUR CODE GOES HERE\n}", "function highlight(id) {\n\n // Find and remove all higlighted chars\n var elems = el.getElementsByTagName('span');\n removeClasses(elems, 'highlight');\n\n // Mark the matching chars as highlited\n var a = annotationById(id);\n if (a) addClasses(elements(a.pos), 'highlight');\n }", "function js_highlight() \n{\n for (var i=0; i<bold_Tags.length; i++)\n { \n bold_Tags[i].style.color = \"green\";\n }\n}", "function highlightSelected()\n\t{\n\t\t// selected pileups (mutations) on the diagram\n\t\tvar selected = getSelectedPileups();\n\n\t\t// highlight residues\n\t\thighlight3dResidues(selected);\n\t}", "function highlightAnnotate(ids) {\n var idx = 0;\n var end = ids.length;\n highlight_index++;\n var selectNow = '';\n\n //strip spaces\n if ($('#' + ids[0]).hasClass(\"space\")) {\n idx = 1;\n }\n if ($('#' + ids[end - 1]).hasClass(\"space\")) {\n end = ids.length - 1;\n }\n\n //highlight\n for (i = idx; i < end; i++) {\n $(\"#\" + ids[i]).addClass(\"highlight\");\n selectNow = selectNow + $(\"#\" + ids[i]).text() + \" \";\n }\n\n return selectNow;\n}", "function paintFirstSpanInLine(){\n var oldTop;\n // target = our text\n var $selected = $('#selectme');\n //$selectedArray = $selected.text().split(' ');\n // separate each word into its own span\n $selected.html(\"<span>\" + $selected.text().split(' ').join(\"</span> <span>\") + \"</span>\");\n oldTop = -1;\n $selected.find('span').each(function(){\n var $this = $(this),\n top = $this.position().top;\n if (top > oldTop){\n $this.css(\"color\", \"rgb(0, 255, 180)\");\n oldTop = top;\n }\n });\n}", "function highlight([first,...strings], ...values) {\n return values.reduce((acc, curr) => \n [...acc, `<span>${curr}</span>`, strings.shift()], [first]).join('');\n}", "function highlight2(code) {\n return code.replace(/(F+)/g,'<span style=\"color: pink\">$1</span>').\n replace(/(L+)/g,'<span style=\"color: red\">$1</span>').\n replace(/(R+)/g,'<span style=\"color: green\">$1</span>').\n replace(/(\\d+)/g,'<span style=\"color: orange\">$1</span>');\n}", "function highlightSpan(randomSpan) {\n randomSpan.classList.add('highlight');\n}", "function highlightCurrentCode() {\n // Change the css property by applying a highlighted background color of orange\n $(\"#code_\" + registers[\"rip\"]).css('background-color', '#df9857');\n}", "function highlight(e){\n a_FAO_i='';\n for(var i=0;i<n_FAO;i++) b_FAO[id_FAO[i]]=false;\n // document.getElementById(word).style.fontSize='10px';\n word=e.target.id;\n for(var i=0;i<n_words;i++) if(word===words[i]) i_word=i;\n data_json_w=data_json[word];\n document.getElementById('WORD').innerHTML=word;\n initializing_description();\n // e.target.style.fontSize='30px';\n list_pileups_year();\n list_pairwize_year();\n change();\n}", "function highlight(target){\n var opts = $.data(target, 'timespinner').options;\n var start = 0, end = 0;\n if (opts.highlight == 0){\n start = 0;\n end = 2;\n } else if (opts.highlight == 1){\n start = 3;\n end = 5;\n } else if (opts.highlight == 2){\n start = 6;\n end = 8;\n }\n if (target.selectionStart != null){\n target.setSelectionRange(start, end);\n } else if (target.createTextRange){\n var range = target.createTextRange();\n range.collapse();\n range.moveEnd('character', end);\n range.moveStart('character', start);\n range.select();\n }\n $(target).focus();\n }", "function readCodeHighlightIcon(routine, step){\r\n let elipseColor = \"#006060\";\r\n\r\n readCodeEllipseStack[routine][step].background = elipseColor;\r\n\r\n\r\n\r\n}", "function highlight(props){\n var selected=d3.selectAll(\".\"+props.adm0_a3)\n .style({\n \"fill-opacity\":\"1\",\n \"stroke\":\"white\",\n \"stroke-width\":\"2\"\n })\n setLabel(props);\n}", "function highlight(code) {\n return new Promise((resolve, reject) => {\n pygmentize({ lang: 'html', format: 'html' }, code, function (err, result) {\n if (err) {\n console.log(err);\n reject(err);\n } else {\n resolve(result.toString());\n }\n });\n });\n}", "function syntaxColorMouseEvent(event) {\n \n \tif (event) {//event.keyCode ==32\n \t\tvar sbwin = Chickenfoot.getSidebarWindow(chromeWindow);\n \tvar ed = sbwin.getSelectedBuffer().editor;\n \tvar doc = ed.contentDocument;\n \tvar pre = doc.getElementById(\"pre\");\n \t//var preElement=false; \n \tvar anchorNodeCaret = sbwin.getSelectedBuffer().api.selection.focusNode;\n \tvar anchorOffsetCaret = sbwin.getSelectedBuffer().api.selection.focusOffset;\n \t//debug('offset: '+anchorOffsetCaret);\n \t\n \t//pre.innerHTML=\"<span style=\\\"color: blue;\\\">/*j<br>*/</span><br>\";\n /*\n \tdebug('pre');\n \tdebug(pre.childNodes);\n \tdebug(\"anchorNodeCaret\");\n \tdebug(anchorNodeCaret);\n \t//debug(\"anchorNodeCaret.parentNode\");\n \t//debug(anchorNodeCaret.parentNode);\n \t//debug(\"anchorNodeCaret.parentNode.parentNode\");\n \t//debug(anchorNodeCaret.parentNode.parentNode);\n \tdebug(anchorNodeCaret.data+\"+end\");\n \t//debug(anchorNodeCaret.innerHTML);\n \tdebug(anchorOffsetCaret);\n \t*/\n \t\n }\n}", "highlightCorrectWord(result) {\n const highlightTint = this.getHighlightColour()\n\n // result contains the sprites of the letters, the word, etc.\n const word = this.wordList[result.word]\n\n word.text.fill = '#' + highlightTint.toString(16)\n word.text.stroke = '#000000'\n\n this.selectFeatureWord(word.text)\n\n result.letters.forEach((letter) => {\n letter.tint = highlightTint\n })\n }", "highlightCode() {\n hljs.highlightElement(this.el);\n }", "function resultHighlight(text, term) {\n var terms = term.split(\" \");\n\n $.each(terms, function (key, term) {\n if (term.length >= 3) {\n term = term.replace(/(\\s+)/, \"(<[^>]+>)*$1(<[^>]+>)*\");\n var pattern = new RegExp(\"(\" + term + \")\", \"gi\");\n\n text = text.replace(pattern, \"<mark>$1</mark>\");\n }\n });\n\n return text;\n //remove the mark tag if needed\n //srcstr = srcstr.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\\/mark>)/, \"$1</mark>$2<mark>$4\");\n }", "function highlight(text, style) {\n var page_html = document.getElementById('page').innerHTML;\n var page = document.getElementById('page');\n var draft_html = document.getElementById('draft').innerHTML;\n var draft = document.getElementById('draft');\n text = text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); //https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex\n\n var re = new RegExp(text, 'g');\n var m;\n\n if (text.length > 0) {\n page.innerHTML = page_html.replace(re, `<span style='background-color:${style};'>$&</span>`);\n draft.innerHTML = draft_html.replace(re, `<span style='background-color:${style};'>$&</span>`);\n\n } else {\n page.innerHTML = page_html;\n draft.innerHTML = draft_html;\n }\n }", "highlightRange(range) {\n let span = document.createElement('span');\n span.classList.add(SELECTED_CLS);\n let spans = [span];\n\n // If the selection starts and ends in different containers\n if (range.startContainer !== range.endContainer) {\n let startRange = new Range();\n let startSpan = span.cloneNode();\n startRange.setStart(range.startContainer, range.startOffset);\n startRange.setEnd(range.startContainer, range.startContainer.length);\n startRange.surroundContents(startSpan);\n spans.push(startSpan);\n\n let endRange = new Range();\n let endSpan = span.cloneNode();\n endRange.setStart(range.endContainer, 0);\n endRange.setEnd(range.endContainer, range.endOffset);\n endRange.surroundContents(endSpan);\n spans.push(endSpan);\n\n // Get nodes between the start and end containers\n let betweenNodes = getBetweenNodes(startSpan, endSpan, range.commonAncestorContainer);\n betweenNodes.forEach((n) => {\n let range = new Range();\n if (n instanceof Text) {\n let s = span.cloneNode();\n range.setStart(n, 0);\n range.setEnd(n, n.length);\n range.surroundContents(s);\n spans.push(s);\n } else {\n // Just re-use existing span\n n.classList.add(SELECTED_CLS);\n [...n.querySelectorAll('span')].forEach((s) => {\n s.classList.add(SELECTED_CLS);\n });\n }\n });\n } else {\n range.surroundContents(span);\n }\n return spans;\n }", "function highlight(counties, val)\n { \n // console.log(counties)\n //change stroke\n var selected = d3.selectAll('.' + counties)\n .style(\n {\n \"stroke\": \"#f40c4a\",\n \"stroke-width\": \"3\"\n });\n\n setLabel(counties, val);\n }", "function highlightTag(tag) {\n var pTag = _ById('htmlContent');\n var tokens = xmlText.split(tag);\n var node;\n var len = tokens.length - 1;\n pTag.innerHTML = '';\n\n for (var i = 0; i < len; i++) {\n node = document.createTextNode(tokens[i])\n pTag.appendChild(node);\n node = document.createElement('mark');\n node.appendChild(document.createTextNode(tag))\n pTag.appendChild(node);\n }\n node = document.createTextNode(tokens[i])\n pTag.appendChild(node);\n}", "function highlightTerm(passage, start) {\n var id = $(passage).parents('.eventextraction')[0].typeId;\n if(!$(start).parents('#selection').length && id != -1) { // if no selection is made and maximum matches is not reached\n \n $(passage).children('#selection').contents().unwrap();\n start.wrapAll(\"<span class='term event\" + id + \"term' id='selection' />\");\n\n $(passage).find('span:not(#selection)').bind('mouseover', function(e) {\n highlightMultiple(start, $(e.target), passage, id);\n });\n\n } else { // remove when click on selection\n $(passage).children('#selection').replaceWith(function() {\n return $(this).contents();\n });\n }\n }", "function highlightAya(elem, chapter, verse){\n\t//console.log('highlighting: ' + chapter + ' ' + verse);\n\n\tvar id_num = -1;\n\tfor(var i = 0; i<quran_json_string.length; i++){\n\t\tif((quran_json_string[i].chapter == chapter) && (quran_json_string[i].verse == verse)){\n\t\t\tid_num = i;\n\t\t}\n\t}\n\tif(id_num==-1){\n\t\treturn;\n\t}\n\n\tif(search_idx_list.includes(id_num)){\n\t\tbox_list[id_num].transition()\n\t\t\t\t.attr('fill', hover_color)\n\t}else{\n box_list[id_num].transition()\n\t\t\t\t.attr('fill', hover_color)\n\t}\n\n\thighlighted_list.push(id_num);\n\n\t/*\n\tdocument.getElementById('infobox').classList.remove(\"infoBoxClassInvisible\");\n\tdocument.getElementById('infobox').classList.add(\"infoBoxClassVisible\");\n\tdocument.getElementById('arabic_text_p').innerHTML= quran_json_string[id_num].arabic;\n\tdocument.getElementById('english_text_p').innerHTML = quran_json_string[id_num].english;\n\tdocument.getElementById('juz_text_p').innerHTML =\"juz: \" + quran_json_string[id_num].juz_number;\n\tdocument.getElementById('sura_text_p').innerHTML =\"surah: \" + quran_json_string[id_num].chapter;\n\tdocument.getElementById('aya_text_p').innerHTML =\"aya: \" + quran_json_string[id_num].verse;\n\n\t//put id box in right spot\n\tdocument.getElementById('infobox').style.left = box_list[id_num].node().getBoundingClientRect().left + 50;\n\tdocument.getElementById('infobox').style.top = box_list[id_num].node().getBoundingClientRect().top + 0;\t\n\t*/\n\n\t//add a leader line?\n\tfor(var i = 0; i<line_list.length; i++){\n\t\tline_list[i].remove();\n\t}\n\tline_list = [];\n\t//the original aya, hmmmm.\n\tvar myLine = new LeaderLine( elem, box_list[id_num].node(), {color: 'orange', size: 8});\n\t//var myLine = new LeaderLine( LeaderLine.pointAnchor(elem, {x: '50%', y: '100%'}), box_list[id_num].node(), {color: 'orange', size: 8});\t\t\n\t\n\t//myLine.style.zIndex = \"400\";\t\n\tline_list.push(myLine);\t\n\tif(isInViewport(myLine.start)){\n\t\tmyLine.show();\n\t}else{\n\t\tmyLine.hide();\n\t}\n\n}", "function highlight(id) {\n\tvar note = document.getElementById(id);\n\tnote.className += ' highlight';\n}", "_msgHighlightTransform(event, message, map, $msg, $effects) {\n let result = message;\n for (let pat of this._highlights) {\n let pattern = pat;\n let locations = [];\n let arr = null;\n /* Ensure pattern has \"g\" flag */\n if (pat.flags.indexOf(\"g\") === -1) {\n pattern = new RegExp(pat, pat.flags + \"g\");\n }\n while ((arr = pattern.exec(event.message)) !== null) {\n if (!$msg.hasClass(\"highlight\")) {\n $msg.addClass(\"highlight\");\n }\n let whole = arr[0];\n let part = arr.length > 1 ? arr[1] : arr[0];\n let start = arr.index + whole.indexOf(part);\n let end = start + part.length;\n locations.push({part: part, start: start, end: end});\n }\n /* Ensure the locations array is indeed sorted */\n locations.sort((a, b) => a.start - b.start);\n while (locations.length > 0) {\n let location = locations.pop();\n let node = $(`<em class=\"highlight\"></em>`).text(location.part);\n let msg_start = result.substr(0, map[location.start]);\n let msg_part = node[0].outerHTML;\n let msg_end = result.substr(map[location.end]);\n $msg.addClass(\"highlight\");\n result = msg_start + msg_part + msg_end;\n this._remap(map, location.start, location.end, msg_part.length);\n }\n }\n return result;\n }", "function highlight(beatNum) {\n let prevBeat = (beatNum - 1) < 0 ? 7 : (beatNum - 1);\n // Clear previous beat\n document.getElementById(prevBeat + \"\").style.background = \"#2c3e50\";\n // Light current beat\n document.getElementById(beatNum + \"\").style.background = \"#d15d36\";\n}", "function highlight() {\n\t\t$('pre code').each(function(i, e) {\n\t\t hljs.highlightBlock(e)\n\t\t});\n\t}", "highlightInText(term) {\n var content = $('#textviewer');\n var results;\n\n function jumpTo() {\n if (results.length) {\n var position;\n var current = results.eq(0);\n\n if (current.length) {\n content.scrollTop(0);\n content.scrollTop(current.offset().top - content.offset().top - 20);\n }\n }\n }\n\n content.unmark({\n done: function() {\n content.mark(term, {\n done: function() {\n results = content.find(\"mark\");\n jumpTo();\n }\n });\n }\n });\n }", "function highlightMultiple(start, end, passage, id) {\n // ignore margins between elements\n $(passage).find('#selection').contents().unwrap();\n if(start.is(end)) { // single element\n $(start).wrapAll(\"<span class='term event\" + id + \"term' id='selection'/>\");\n } else { // if range of elements\n if($(passage).find('span').index(start) > $(passage).find('span').index(end)) { // swap if end is before start\n var temp = end;\n end = start;\n start = temp;\n }\n \n \n if(!start.parent().not($('#selection')).is(end.parent().not($('#selection')))) {\n // common parent element\n var common = end.parents().not($('#selection')).has(start).first();\n \n if(start.parent('.term').not(common).length) { // if word has a parent term\n start = $(common).children().has(start);\n // $(start).parent('.term');\n }\n \n if(end.parent('.term').not(common).length) {\n end = $(common).children().has(end);\n //end = $(end).parent('.term');\n }\n }\n // highlight range\n $(start).nextUntil(end.next()).andSelf().wrapAll(\"<span class='term event\" + id + \"term' id='selection' />\");\n }\n }", "function highlightTranslatedCode( title, code, gray ) {\n\t\treturn \"<MM:DECORATION\"\n\t\t+ ' outline=\"' + title + '\"'\n\t\t+ ' outlineId=\"unique\"'\n\t\t+ (!gray ? ' outlineForSelection=\"outlineForSelection\"' : '')\n\t\t+ (!gray ? ' hiliteChildrenOnSelect=\"true\"' : '') + '>'\n\t\t+ code\n\t \t+ \"</MM:DECORATION>\";\n}", "_highlightCode() {\n let code = this.$('pre code');\n\n code.each((i, block) => {\n Highlight.highlightBlock(block);\n });\n }", "function highlightLetters() {\n textContentSplit = log.textContent.split('')\n for (var i = 0; i < randomWordSplit.length; i++) {\n if (randomWordSplit[i] === textContentSplit[i]) {\n document.getElementById(i).setAttribute('class', 'text-color');\n }\n if (randomWordSplit[i] !== textContentSplit[i]) \n { break;}\n }\n}", "highlight(query) {\n const tokens = this.tokenizer.tokenize(query);\n let token;\n let ret = '';\n let position = 0;\n // eslint-disable-next-line no-cond-assign\n while (token = tokens[position++]) {\n ret += this.highlightToken(token.type, token.value);\n }\n return ret;\n }", "highlightFirst_() {\n this.highlightHelper_(-1, 1);\n }", "function highlight(target, index){\n\t\tvar opts = $.data(target, 'timespinner').options;\n\t\tif (index != undefined){\n\t\t\topts.highlight = index;\n\t\t}\n\t\tvar range = opts.selections[opts.highlight];\n\t\tif (range){\n\t\t\tvar tb = $(target).timespinner('textbox');\n\t\t\t$(target).timespinner('setSelectionRange', {start:range[0],end:range[1]});\n\t\t\ttb.focus();\n\t\t}\n\t}", "function highlight(text, selection, tagType) {\n const color = tagType === 'origin' ? '#af3011' : '#37a425';\n let re = new RegExp(`<span data-id=\"${tagType}\"[^>]*>(.*?)</span>`);\n return text\n .replace(re, '$1')\n .replace(\n selection.toString(),\n x =>\n `<span data-id=\"${tagType}\" style=\"padding: 2px 5px; background-color: ${color}; border-radius: 2px; color: white;\">${x}</span>`\n );\n}", "function highlightedText() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $highlightedTextOffsetPos = ($('#nectar_fullscreen_rows').length > 0) ? '200%' : 'bottom-in-view';\r\n\t\t\t\t\tvar highlightedColorCss = '';\r\n\t\t\t\t\t\r\n\t\t\t\t\t$($fullscreenSelector + '.nectar-highlighted-text').each(function (i) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Custom color \r\n\t\t\t\t\t\tif ($(this).is('[data-using-custom-color=\"true\"]')) {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tvar $custom_highlight_color = $(this).attr('data-color');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$(this).addClass('instance-' + i);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\thighlightedColorCss += '.nectar-highlighted-text.instance-' + i + ' em:before { background-color: ' + $custom_highlight_color + '; }';\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif (nectarDOMInfo.usingMobileBrowser) {\r\n\t\t\t\t\t\t\t$(this).find('em').addClass('animated');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Waypoint\r\n\t\t\t\t\t\tvar $that = $(this);\r\n\t\t\t\t\t\tvar waypoint = new Waypoint({\r\n\t\t\t\t\t\t\telement: $that,\r\n\t\t\t\t\t\t\thandler: function () {\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tif ($that.parents('.wpb_tab').length > 0 && $that.parents('.wpb_tab').css('visibility') == 'hidden' || $that.hasClass('animated')) {\r\n\t\t\t\t\t\t\t\t\twaypoint.destroy();\r\n\t\t\t\t\t\t\t\t\treturn;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t$that.find('em').each(function (i) {\r\n\t\t\t\t\t\t\t\t\tvar $highlighted_em = $(this);\r\n\t\t\t\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\t\t\t\t$highlighted_em.addClass('animated');\r\n\t\t\t\t\t\t\t\t\t}, i * 300);\r\n\t\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\twaypoint.destroy();\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t},\r\n\t\t\t\t\t\t\toffset: $highlightedTextOffsetPos\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Style\r\n\t\t\t\t\tnectarCreateStyle(highlightedColorCss, 'highlighted-text');\r\n\t\t\t\t\t\r\n\t\t\t\t}", "highlight_move(args) {\n\n }", "function highlight(classNameBRBC){\n\t\t\t\t\t\tvar x = document.getElementsByClassName(classNameBRBC);\n\t \t\t\t\tvar i;\n\t \t\t\t\tfor (i = 0; i < x.length; i++) {\n\t \t\t\t\t//instead of changing the background add a class that changes the background\n\t \t\t\t\tx[i].className +=' highlight1';\n\t \t\t\t//x[i].style.background = \"#a67cf4\";\n\t \t\t\t}\n\t\t\t\t\t}", "highlight_space(args) {\n\n }", "function highlight(props){\n\n //Ids were stored in different forms on the map\n // and the barchart\n var selectThis;\n if(props.Id2){\n selectThis = \".id\" + props.Id2;\n }else{\n selectThis = \".\" + props[0];\n }\n //change stroke\n var selected = d3.selectAll(selectThis)\n .style({\n \"stroke\": \"black\",\n \"stroke-width\": \"2\"\n });\n\n setLabel(props);\n }", "function highlight(d) {\n let elements = getElements();\n let columns = getColumns();\n if (d === DIRECTION.none) {\n elements[selection].getElementsByTagName(\"img\")[0].style.background = HIGHLIGHT_COLOUR;\n } else if (d === DIRECTION.remove) {\n elements[selection].getElementsByTagName(\"img\")[0].style.background = \"\";\n } else if (d === DIRECTION.backwards && selection > 0 && selection % columns !== 0) {\n highlight(DIRECTION.remove);\n selection--;\n highlight(DIRECTION.none);\n } else if (d === DIRECTION.forward && selection < elements.length - 1 && selection % columns !== columns - 1) {\n highlight(DIRECTION.remove);\n selection++;\n highlight(DIRECTION.none);\n } else if (d === DIRECTION.up && selection > columns - 1) {\n highlight(DIRECTION.remove);\n selection -= columns;\n highlight(DIRECTION.none);\n } else if (d === DIRECTION.down && selection < elements.length - columns) {\n highlight(DIRECTION.remove);\n selection += columns;\n highlight(DIRECTION.none);\n }\n\n scroll();\n}", "function highlight1(classNameBRBC){\n\t\t\tvar x = document.getElementsByClassName(classNameBRBC);\n\t\t\tvar i;\n\t\t\tfor (i = 0; i < x.length; i++) {\n\t\t\t//instead of changing the background add a class that changes the background\n\t\t\tx[i].className +=' highlight';\n\t\t\t}\n\t\t}", "function highlight(tag, color, select) {\n\tt = \"#\" + tag\n\t$(t).css(\"border-color\", color).prev().css(\"color\", color);\n\tif (select) {\n\t\tselectFocus(tag);\n\t}\n}", "function highlight() {\n var code_blocks = document.body.getElementsByClassName(\"language-c\");\n var keywords = [\n \"auto\", \"break\", \"case\", \"char\", \"const\", \"continue\", \"default\",\n \"do\", \"double\", \"else\", \"enum\", \"extern\", \"float\", \"for\", \"goto\",\n \"if\", \"inline\", \"int\", \"long\", \"register\", \"restrict\", \"return\",\n \"short\", \"signed\", \"sizeof\", \"static\", \"struct\", \"switch\",\n \"typedef\", \"union\", \"unsigned\", \"void\", \"volatile\", \"while\",\n ];\n var regex_var = /\\b[A-z][A-z0-9]*/;\n var regex_number = /\\b0[xX][0-9a-fA-F]+\\b|\\b[0-9]*\\.[0-9]+\\b|\\b[0-9]*\\b/;\n var regex_string = /\"[^\"]*\"/;\n var regex_symbol = /&gt;|&lt;|\\ |\\(|\\)|;|-/;\n for (var i = 0; i < code_blocks.length; i++) {\n var element = code_blocks.item(i);\n var code_lines = element.innerHTML.split('\\n');\n var cursor = 0;\n\n var parts = [];\n var insert_index = 0;\n function insert_at(index, insertable) {\n if (index < insert_index) console.error(\"inserting before last insert!!\");\n parts.push(element.innerHTML.substr(insert_index, index - insert_index));\n parts.push(insertable);\n insert_index = index;\n }\n\n var in_block_comment = false;\n\n for (var j = 0; j < code_lines.length; j++) {\n var words = code_lines[j].split(regex_symbol);\n var in_line_comment = false;\n\n for (var k = 0; k < words.length; k++) {\n var word = words[k];\n\n // Special case for < and >, because they're escaped in\n // innerHTML.\n var to_be_processed_html = element.innerHTML.substr(cursor);\n if (to_be_processed_html.startsWith(\"lt;\") ||\n to_be_processed_html.startsWith(\"gt;\")) {\n cursor += 3;\n }\n\n if (in_block_comment) {\n if (word == \"*/\") {\n in_block_comment = false;\n insert_at(cursor + word.length, \"</span>\"); // close comment block\n }\n } else {\n if (!in_line_comment) {\n if (word == \"//\") {\n in_line_comment = true;\n insert_at(cursor, \"<span class='syntax-comment'>\"); // open comment line\n }\n if (word == \"/*\") {\n in_block_comment = true;\n insert_at(cursor, \"<span class='syntax-comment'>\"); // open comment block\n }\n }\n\n if (!in_line_comment && !in_block_comment) {\n if (keywords.indexOf(word) != -1) {\n insert_at(cursor, \"<span class='syntax-keyword'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_string.test(word)) {\n insert_at(cursor, \"<span class='syntax-string'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_var.test(word) && element.innerHTML.substr(cursor + word.length, 1) == \"(\") {\n insert_at(cursor, \"<span class='syntax-call'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_var.test(word)) {\n insert_at(cursor, \"<span class='syntax-variable'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_number.test(word)) {\n insert_at(cursor, \"<span class='syntax-number'>\");\n insert_at(cursor + word.length, \"</span>\");\n }\n }\n }\n\n cursor += word.length + 1;\n }\n\n if (in_line_comment) {\n insert_at(cursor, \"</span>\"); // close comment line\n }\n }\n\n parts.push(element.innerHTML.substr(insert_index));\n element.innerHTML = parts.join('');\n\n // When processing, using &lt; and &gt; is forced upon us. Now we\n // can fix that to allow for good copypasting.\n element.innerHTML.replace(/&lt;/g, \"<\");\n element.innerHTML.replace(/&gt;/g, \">\");\n }\n}", "function highlight(i)\r\n{\r\n document.getElementsByTagName(\"strong\")[i].setAttribute(\"class\", \"democlass\");\r\n}", "function drawSelectionRange(cm, range$$1, output) {\r\n var display = cm.display, doc = cm.doc;\r\n var fragment = document.createDocumentFragment();\r\n var padding = paddingH(cm.display), leftSide = padding.left;\r\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\r\n var docLTR = doc.direction == \"ltr\";\r\n\r\n function add(left, top, width, bottom) {\r\n if (top < 0) { top = 0; }\r\n top = Math.round(top);\r\n bottom = Math.round(bottom);\r\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\r\n }\r\n\r\n function drawForLine(line, fromArg, toArg) {\r\n var lineObj = getLine(doc, line);\r\n var lineLen = lineObj.text.length;\r\n var start, end;\r\n function coords(ch, bias) {\r\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\r\n }\r\n\r\n function wrapX(pos, dir, side) {\r\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\r\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\r\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\r\n return coords(ch, prop)[prop]\r\n }\r\n\r\n var order = getOrder(lineObj, doc.direction);\r\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\r\n var ltr = dir == \"ltr\";\r\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\r\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\r\n\r\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\r\n var first = i == 0, last = !order || i == order.length - 1;\r\n if (toPos.top - fromPos.top <= 3) { // Single line\r\n var openLeft = (docLTR ? openStart : openEnd) && first;\r\n var openRight = (docLTR ? openEnd : openStart) && last;\r\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\r\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\r\n add(left, fromPos.top, right - left, fromPos.bottom);\r\n } else { // Multiple lines\r\n var topLeft, topRight, botLeft, botRight;\r\n if (ltr) {\r\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\r\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\r\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\r\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\r\n } else {\r\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\r\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\r\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\r\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\r\n }\r\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\r\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\r\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\r\n }\r\n\r\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\r\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\r\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\r\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\r\n });\r\n return {start: start, end: end}\r\n }\r\n\r\n var sFrom = range$$1.from(), sTo = range$$1.to();\r\n if (sFrom.line == sTo.line) {\r\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\r\n } else {\r\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\r\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\r\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\r\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\r\n if (singleVLine) {\r\n if (leftEnd.top < rightStart.top - 2) {\r\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\r\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\r\n } else {\r\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\r\n }\r\n }\r\n if (leftEnd.bottom < rightStart.top)\r\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\r\n }\r\n\r\n output.appendChild(fragment);\r\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var fromPos = coords(from, dir == \"ltr\" ? \"left\" : \"right\");\n var toPos = coords(to - 1, dir == \"ltr\" ? \"right\" : \"left\");\n if (dir == \"ltr\") {\n var fromLeft = fromArg == null && from == 0 ? leftSide : fromPos.left;\n var toRight = toArg == null && to == lineLen ? rightSide : toPos.right;\n if (toPos.top - fromPos.top <= 3) { // Single line\n add(fromLeft, toPos.top, toRight - fromLeft, toPos.bottom);\n } else { // Multiple lines\n add(fromLeft, fromPos.top, null, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(leftSide, toPos.top, toPos.right, toPos.bottom);\n }\n } else if (from < to) { // RTL\n var fromRight = fromArg == null && from == 0 ? rightSide : fromPos.right;\n var toLeft = toArg == null && to == lineLen ? leftSide : toPos.left;\n if (toPos.top - fromPos.top <= 3) { // Single line\n add(toLeft, toPos.top, fromRight - toLeft, toPos.bottom);\n } else { // Multiple lines\n var topLeft = leftSide;\n if (i) {\n var topEnd = wrappedLineExtentChar(cm, lineObj, null, from).end;\n // The coordinates returned for an RTL wrapped space tend to\n // be complete bogus, so try to skip that here.\n topLeft = coords(topEnd - (/\\s/.test(lineObj.text.charAt(topEnd - 1)) ? 2 : 1), \"left\").left;\n }\n add(topLeft, fromPos.top, fromRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n var botWidth = null;\n if (i < order.length - 1 || true) {\n var botStart = wrappedLineExtentChar(cm, lineObj, null, to).begin;\n botWidth = coords(botStart, \"right\").right - toLeft;\n }\n add(toLeft, toPos.top, botWidth, toPos.bottom);\n }\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n}", "function highlight(e){\neventobj=ns6? e.target : event.srcElement\nif (previous!=''){\nif (checkel(previous))\nprevious.style.backgroundColor=''\nprevious=eventobj\nif (checkel(eventobj))\neventobj.style.backgroundColor=highlightcolor\n}\nelse{\nif (checkel(eventobj))\neventobj.style.backgroundColor=highlightcolor\nprevious=eventobj\n}\n}", "function highlight(props){\n //change stroke\n var selected = d3.selectAll(\".\" + props.NAME_1)\n .style(\"stroke\", \"#54B6E4\")\n .style(\"stroke-width\", \"2\");\n setLabel(props);\n}", "highlight(color){\r\n let x = this.col * this.size / this.cols + 1\r\n let y = this.row * this.size / this.rows + 1\r\n ctx.fillStyle = color\r\n ctx.fillRect(x,y,this.size/this.cols -5,this.size/this.rows -5)\r\n }", "function highlightUserSpecified(){\n\n\n\n var userSpecifiedArray = new Array();\n var newArray = new Array();\n\n //Quads for word \"For\" --word Quad\n //236.90859985351562,458.2436828613281,265.9341125488281,458.2436828613281,236.90859985351562,425.3403625488281,265.9341125488281,425.3403625488281\n\n //Quads for wod \"Reference\" -- annotation Quad\n //407.77801513671875,458.2439880371094,504.6159973144531,458.2439880371094,407.77801513671875,425.3399963378906,504.6159973144531,425.3399963378906\n\n //Quads for word \"Contents\" on page 3 \n //107.46000671386719,727.82373046875,187.44012451171875,727.82373046875,107.46000671386719,698.7603149414062,187.44012451171875,698.7603149414062\n\n var userSpecified = null;\n var userSpecifiedPage = null;\n\n \n userSpecified = app.response(\"What are the quad coordinates?\");\n \n userSpecifiedPage = app.response(\"What is the page number\");\n\n parsedUserPage = parseInt(userSpecifiedPage)-1;\n\n userSpecifiedSplit = userSpecified.split(\",\");\n\n for(var i = 0; i < userSpecifiedSplit.length; i++){\n var parsedFloat = parseFloat(userSpecifiedSplit[i]);\n newArray[i] = parsedFloat;\n }\n\n \n userSpecifiedArray[0] = [newArray[0],newArray[1],newArray[2],newArray[3],newArray[4],newArray[5],newArray[6],newArray[7]];\n \n console.println(userSpecifiedArray[0]);\n \n var annot = this.addAnnot({\n page: parsedUserPage, //need to specificy which page the quad coordinates apply to\n type: \"Highlight\",\n quads: userSpecifiedArray,\n author: \"User\",\n contents: \"userspecifiedArray\"\n });\n\n}", "function highlight(concept) {\n var the_map = {\n opinions:\"chartreuse\",\n life:\"yellow\",\n }\n return the_map[concept]\n}", "function highlightLabel(highlight) {\n d3.selectAll('.labels').transition().style('opacity', 0.2)\n .style('font-size', \"9.5px\").style('fill', '#B8CBED');\n\n highlight.forEach(function(d) {\n d3.selectAll('.lab-'+d).transition().style('opacity', 1)\n .style('font-size', \"13px\")\n .style('fill', '#5B6D8F')\n })\n }", "function highlight(tr) {\n while (tr && tr.length > 0) {\n tr = highlight0(tr);\n if (trjs.events.lineGetCell(tr, trjs.data.TSCOL) || trjs.events.lineGetCell(tr, trjs.data.TECOL))\n break;\n }\n }", "function insertKeyword(text, currColor, currWord){\n\n\tvar index = indexArr.length-1;\n\n\tif(index == 0){\n\t\ttextArr.push(text.substring(0 , indexArr[index]) + ' <span class = \"highlightWord\" style=\"background-color:' + currColor + '\">' + text.substring(indexArr[index] , indexArr[index]+currWord.text.length) + '</span>');\n\t}else{ \n\t\ttextArr.push(text.substring(indexArr[index-1]+currWord.text.length , indexArr[index]) + ' <span class = \"highlightWord\" style=\"background-color:' + currColor + '\">' + text.substring(indexArr[index] , indexArr[index]+currWord.text.length) + '</span>');\n\t}\n\n}", "function seqAligner(pattern_seq, subject_seq, topID, midID, botID) {\n\t\tvar patternArray = pattern_seq.split('');\n\t\tvar subjectArray = subject_seq.split('');\n\n\t\tfor (index = 0; index < patternArray.length; index++) {\n\t\t\tvar patternCode = \"<span class='styleGuide'>\" + patternArray[index] + \"</span>\";\n\t\t\tvar subjectCode = \"<span class='styleGuide'>\" + subjectArray[index] + \"</span>\";\n\n\t\t\tvar topSeqID = \"#\" + topID;\n\t\t\tvar midSeqID = \"#\" + midID;\n\t\t\tvar botSeqID = \"#\" + botID;\n\n\t\t\t$(topSeqID).append(patternCode);\n\t\t\t$(botSeqID).append(subjectCode);\n\t\t\tif (isSameBase(patternArray[index], subjectArray[index])) \n\t\t\t{\n\t\t\t\tvar midCode = \"<span class='styleGuide'>\" + \"|\" + \"</span>\";\n\t\t\t} else {\n\t\t\t\tvar midCode = \"<span class='styleGuide'>\" + \"<div class='blockYellow'>&nbsp</div>\" + \"</span>\";\n\t\t\t}\n\t\t\t$(midSeqID).append(midCode);\n\n\t\t}\n\t}", "function dehighlight(){\n for(var i = 1; i <= fiveWords.length; i++){\n //just took this substring from compare function\n var stringValue = fiveWords[i-1].substring(0, userWord.length).toUpperCase();\n //it reinserts words that are not valid, and keeps the word that is good.\n if(userWord != stringValue){\n document.getElementById(\"myAnimation\" + i).innerHTML = fiveWords[i - 1];\n }\n }\n}", "function codeMouseUp() {\n if (cr == null || !cr.is_grader) {\n // students don't need to highlight\n return\n }\n\n var s = window.getSelection()\n var filename = findSelectionFileName(s.anchorNode)\n if (filename == null) {\n return\n }\n\n var offset1 = getAbsoluteOffset(s.anchorNode, s.anchorOffset, \"lang-py\")\n var offset2 = getAbsoluteOffset(s.focusNode, s.focusOffset, \"lang-py\")\n console.log(offset1)\n console.log(offset2)\n var offset = Math.min(offset1, offset2)\n var length = Math.max(offset1, offset2) - offset + 1\n\n for(var i=0; i<cr.highlights[filename].length; i++) {\n var highlight = cr.highlights[filename][i]\n if (!(offset+length <= highlight.offset || highlight.offset+highlight.length <= offset)) {\n // too close to another highlight (or overlapping)\n console.log('overlaps')\n return\n }\n }\n\n console.log('does not overlap')\n\n cr.highlights[filename].push({offset:offset, length:length, comment:\"\"})\n cr_dirty = true\n console.log(cr.highlights)\n code_review.refreshCR()\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function drawSelectionRange(cm, range$$1, output) {\n var display = cm.display, doc = cm.doc;\n var fragment = document.createDocumentFragment();\n var padding = paddingH(cm.display), leftSide = padding.left;\n var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;\n var docLTR = doc.direction == \"ltr\";\n\n function add(left, top, width, bottom) {\n if (top < 0) { top = 0; }\n top = Math.round(top);\n bottom = Math.round(bottom);\n fragment.appendChild(elt(\"div\", null, \"CodeMirror-selected\", (\"position: absolute; left: \" + left + \"px;\\n top: \" + top + \"px; width: \" + (width == null ? rightSide - left : width) + \"px;\\n height: \" + (bottom - top) + \"px\")));\n }\n\n function drawForLine(line, fromArg, toArg) {\n var lineObj = getLine(doc, line);\n var lineLen = lineObj.text.length;\n var start, end;\n function coords(ch, bias) {\n return charCoords(cm, Pos(line, ch), \"div\", lineObj, bias)\n }\n\n function wrapX(pos, dir, side) {\n var extent = wrappedLineExtentChar(cm, lineObj, null, pos);\n var prop = (dir == \"ltr\") == (side == \"after\") ? \"left\" : \"right\";\n var ch = side == \"after\" ? extent.begin : extent.end - (/\\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);\n return coords(ch, prop)[prop]\n }\n\n var order = getOrder(lineObj, doc.direction);\n iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {\n var ltr = dir == \"ltr\";\n var fromPos = coords(from, ltr ? \"left\" : \"right\");\n var toPos = coords(to - 1, ltr ? \"right\" : \"left\");\n\n var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;\n var first = i == 0, last = !order || i == order.length - 1;\n if (toPos.top - fromPos.top <= 3) { // Single line\n var openLeft = (docLTR ? openStart : openEnd) && first;\n var openRight = (docLTR ? openEnd : openStart) && last;\n var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;\n var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;\n add(left, fromPos.top, right - left, fromPos.bottom);\n } else { // Multiple lines\n var topLeft, topRight, botLeft, botRight;\n if (ltr) {\n topLeft = docLTR && openStart && first ? leftSide : fromPos.left;\n topRight = docLTR ? rightSide : wrapX(from, dir, \"before\");\n botLeft = docLTR ? leftSide : wrapX(to, dir, \"after\");\n botRight = docLTR && openEnd && last ? rightSide : toPos.right;\n } else {\n topLeft = !docLTR ? leftSide : wrapX(from, dir, \"before\");\n topRight = !docLTR && openStart && first ? rightSide : fromPos.right;\n botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;\n botRight = !docLTR ? rightSide : wrapX(to, dir, \"after\");\n }\n add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);\n if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }\n add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);\n }\n\n if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }\n if (cmpCoords(toPos, start) < 0) { start = toPos; }\n if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }\n if (cmpCoords(toPos, end) < 0) { end = toPos; }\n });\n return {start: start, end: end}\n }\n\n var sFrom = range$$1.from(), sTo = range$$1.to();\n if (sFrom.line == sTo.line) {\n drawForLine(sFrom.line, sFrom.ch, sTo.ch);\n } else {\n var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line);\n var singleVLine = visualLine(fromLine) == visualLine(toLine);\n var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end;\n var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start;\n if (singleVLine) {\n if (leftEnd.top < rightStart.top - 2) {\n add(leftEnd.right, leftEnd.top, null, leftEnd.bottom);\n add(leftSide, rightStart.top, rightStart.left, rightStart.bottom);\n } else {\n add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom);\n }\n }\n if (leftEnd.bottom < rightStart.top)\n { add(leftSide, leftEnd.bottom, null, rightStart.top); }\n }\n\n output.appendChild(fragment);\n }", "function highlight(props){\n //change stroke\n var selected = d3.selectAll(\".\" + props.iso_a3) //or iso_a3?\n .style(\"stroke\", \"blue\")\n .style(\"stroke-width\", \"2\");\n //console.log(\"hello\", \".\" + props.iso_a3);\n // add dynamic label on mouseover\n setLabel(props);\n}" ]
[ "0.70990103", "0.66774166", "0.66539", "0.657652", "0.6483792", "0.64282423", "0.64135957", "0.63620836", "0.635916", "0.63515896", "0.6324142", "0.63159174", "0.63112307", "0.6219677", "0.61696327", "0.61276925", "0.61201197", "0.6114018", "0.6084117", "0.6083986", "0.608185", "0.60745215", "0.6069155", "0.6060381", "0.6024895", "0.6020606", "0.6008471", "0.6003167", "0.6000474", "0.59966654", "0.5995553", "0.5978735", "0.59722155", "0.59552", "0.59469694", "0.5944843", "0.5944823", "0.59084773", "0.5891087", "0.5887657", "0.58811426", "0.58784336", "0.58756155", "0.5865061", "0.5862926", "0.58620393", "0.5861759", "0.5858934", "0.58567667", "0.5852371", "0.5834345", "0.58336645", "0.58205533", "0.5801621", "0.5798725", "0.5764206", "0.5751329", "0.57217354", "0.5710876", "0.570695", "0.56872433", "0.5685147", "0.56841606", "0.56760085", "0.56734926", "0.5670042", "0.5668759", "0.56451464", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.5640284", "0.56349593", "0.56328404", "0.56254894", "0.5617741", "0.5616335", "0.5613475", "0.561225", "0.5599922", "0.5593054", "0.5589783", "0.55820894", "0.55811054", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5577763", "0.5564902" ]
0.74495226
1
highlight all occurrences of the given cipher letters
function highlightLetters(letters) { unhighlightAll(); for (var row=0; row<cipher[which].length; row++) { for (var col=0; col<cipher[which][row].length; col++) { id = row + "_" + col; letter = cipher[which][row].substring(col,col+1); for (var i=0; i<letters.length; i++) { if (letter == letters.substring(i,i+1)) { h(id); break; } } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function highlightLetters() {\n textContentSplit = log.textContent.split('')\n for (var i = 0; i < randomWordSplit.length; i++) {\n if (randomWordSplit[i] === textContentSplit[i]) {\n document.getElementById(i).setAttribute('class', 'text-color');\n }\n if (randomWordSplit[i] !== textContentSplit[i]) \n { break;}\n }\n}", "showMatchedLetter(char) {\r\n const letters = document.getElementsByClassName('letter');\r\n for (let i = 0; i < letters.length; i++) {\r\n if (char === letters[i].textContent) {\r\n letters[i].classList.add(\"show\");\r\n }\r\n }\r\n }", "highlightCorrectWord(result) {\n const highlightTint = this.getHighlightColour()\n\n // result contains the sprites of the letters, the word, etc.\n const word = this.wordList[result.word]\n\n word.text.fill = '#' + highlightTint.toString(16)\n word.text.stroke = '#000000'\n\n this.selectFeatureWord(word.text)\n\n result.letters.forEach((letter) => {\n letter.tint = highlightTint\n })\n }", "showMatchedLetter(letter) {\n const letterCollection = document.getElementById('phrase').firstElementChild.children;\n for (let i = 0; i < letterCollection.length; i++) {\n if (letterCollection[i].textContent.toLowerCase() === letter) {\n letterCollection[i].className = 'show letter ' + letter;\n }\n }\n }", "showMatchedLetter(letter) {\r\n const phraseDivUl = document.getElementById('phrase').firstElementChild.children;\r\n for (let i = 0; i < phraseDivUl.length; i++) {\r\n if (letter === phraseDivUl[i].textContent) {\r\n phraseDivUl[i].className = `show letter ${phraseDivUl[i].textContent}`;\r\n }\r\n }\r\n }", "showMatchedLetter(){\n $('.correct').css('color', 'black');\n $('.correct').css('background-color', 'green');\n $('.correct').css('text-shadow', '4px black');\n }", "showMatchedLetter(l) {\r\n\r\n let letterToBeShown = game.activePhrase.toLowerCase().split(\"\").find(i => i === l);\r\n let listOfDOMElementLetters = document.getElementsByClassName(letterToBeShown);\r\n for (let i = 0; i < listOfDOMElementLetters.length; i++) {\r\n listOfDOMElementLetters[i].className = \"show letter \" + letterToBeShown;\r\n }\r\n }", "showMatchedLetter(letter) {\n const phraseLis = document.getElementById('phrase').children[0].children;\n\n for(let i = 0; i < phraseLis.length; i++) {\n if(phraseLis[i].textContent.includes(letter)) {\n phraseLis[i].className = 'show';\n }\n }\n }", "showMatchedLetter(keyPressed){\n let letters = document.getElementsByClassName('js-letter');\n for (let j = 0; j < letters.length; j++){\n if(letters[j].textContent === keyPressed){\n letters[j].classList.remove('hide');\n letters[j].classList.add('show');\n }\n }\n }", "showMatchedLetter(letter) {\r\n const phrase = document.querySelectorAll(\".letter\");\r\n phrase.forEach((char) => {\r\n if (char.textContent === letter) {\r\n char.classList.add(\"show\");\r\n char.classList.remove(\"hide\");\r\n }\r\n });\r\n }", "function highlight(){\r\n\tfor(var i=0; i<wordItems.length; i++)\r\n\t\twordItems[i].style.color = \"red\";\r\n}", "showMatchedLetter(letter){\r\n $(letter).addClass('show');\r\n // display the char of the corresponding letters check if game is won\r\n }", "function atbashCipher(text) {\n let output = \"\";\n let alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n for (let i = 0; i < text.length; i++) {\n output += alphabet[26 - alphabet.indexOf(text[i]) - 1];\n }\n return output;\n}", "showMatchedLetter(letter) {\n const letterElements = document.getElementsByClassName(letter);\n for (let i = 0; i < letterElements.length; i ++) {\n letterElements[i].classList.add('show');\n }\n }", "showMatchedLetter(e) {\n let lettersToCheck = document.getElementsByClassName(e.target.innerText)\n for (i = 0; i < lettersToCheck.length; i++) {\n\n lettersToCheck[i].classList.remove(\"hide\")\n lettersToCheck[i].classList.add(\"show\")\n };\n }", "function highlight_words() {\n\n // YOUR CODE GOES HERE\n}", "function processWord(word) {\n var optimalRecognitionposition = Math.floor(word.length / 3),\n letters = word.split('')\n return letters.map(function(letter, idx) {\n if (idx === optimalRecognitionposition)\n return '<span class=\"highlight\">' + letter + '</span>'\n return letter;\n }).join('')\n }", "showMatchedLetter(letter) {\n \n const letterLiCollection = document.getElementById('phrase').firstElementChild;\n \n for ( let i = 0; i < letterLiCollection.childElementCount; i++) {\n \n const currentLi = letterLiCollection.children[i];\n\n if (currentLi.innerHTML === letter ) {\n currentLi.className = `show letter ${letter}`;\n }\n }\n }", "showMatchedLetter(guess){\n //phrase colors \n let phraseLetter = document.querySelectorAll('li.hide.letter');\n phraseLetter.forEach(letter =>{\n if(guess == letter.textContent.toLowerCase()){\n letter.classList.add('show');\n letter.classList.remove('hide');\n }\n })\n }", "showMatchedLetter(letter){\n const correctPhrase = document.querySelectorAll('#phrase ul li ');\n for(let i = 0; i<correctPhrase.length;i++){\n if(correctPhrase[i].innerHTML === letter) {\n correctPhrase[i].className = 'show'; \n }\n }\n }", "showMatchedLetter(letter) {\n const listOfLetters = document.getElementsByClassName(`hide letter ${letter}`);\n this.listOfLettersLenght = listOfLetters.length;\n \n while (listOfLetters.length) {\n listOfLetters[0].className = \"show\";\n }\n }", "wordColorAttribution() {\r\n for (let i=0; i<25; i++) {\r\n if (i===0) {\r\n this.words[i].color = 'black';// ' \\u{2B1B} '; // black\r\n } else if (i<9) {\r\n this.words[i].color = 'red';// ' \\u{1F7E5} '; // red\r\n } else if (i<18) {\r\n this.words[i].color = 'blue';// ' \\u{1F7E6} '; // blue\r\n } else {\r\n this.words[i].color = 'white';// ' \\u{2B1C} '; // white\r\n }\r\n };\r\n }", "showMatchedLetter(letter) {\r\n const letters = document.querySelectorAll(`.hide.${letter}`);\r\n for (let i=0; i<letters.length; i+=1) {\r\n if (letter === letters[i].textContent.toLowerCase()) {\r\n letters[i].className = `show letter ${letter}`;\r\n }\r\n }\r\n }", "function caesarCipher() {\n let originalString = getText();\n let cipherAmt = getCipherAmount();\n let encryptedString = \"\";\n for (let char of originalString) {\n char = char.toUpperCase();\n // Check if this char is a letter.\n if (char.toUpperCase() !== char.toLowerCase()) {\n // Char is a letter. Encrypt it.\n let charCode = ((char.charCodeAt(0) + cipherAmt) - 65) % 26 + 65;\n encryptedString += String.fromCharCode(charCode);\n } else {\n // Otherwise, add it to encrypted string unchanged.\n encryptedString += char;\n }\n }\n // Display the encrypted text in the top portion of the page\n let outputSection = document.getElementById(\"caesarCipherSection\");\n outputSection.innerText = encryptedString;\n}", "function checkLetter(event) {\n let char = document.querySelectorAll('.letter');\n let result = null;\n\n for (let i = 0; i < char.length; i++) {\n if (char[i].textContent == event.textContent) {\n\n char[i].classList.add(\"show\");\n \tchar[i].style.boxShadow = '5px 4px 10px 0px #9e9e9e';\n \tchar[i].style.transition = 'ease 0.5s';\n\n result = event;\n }\n }\n return result;\n}", "showMatchedLetter(letter) {\n\n const lis = document.getElementById('phrase').firstElementChild.children;\n for (let i = 0; i < lis.length; i++) {\n if (lis[i].textContent.toLowerCase() === letter) {\n lis[i].classList.add('show');\n lis[i].classList.remove('hide');\n }\n }\n }", "function cipher() {\n // variable acía, para recibir los índices cifrados\n var cipherPhrase = '';\n // recorro la frase obtenida\n for (var i = 0; i < obtainedPhrase.length; i++) {\n // si la frase tiene espacio, devuelve espacio\n if (obtainedPhrase[i] === ' ') {\n cipherPhrase = cipherPhrase + ' ';\n } else {\n // codifica a ASCII las letras de la frase\n var letters = obtainedPhrase.charCodeAt(i);\n // fórmula para cifrar\n letters = (((letters - 65) + 7) % 26) + 65;\n // devuelve las letras de lo cifrado\n letters = String.fromCharCode(letters);\n cipherPhrase = cipherPhrase + letters;\n }\n }\n return alert('Tu frase cifrada se ve así: \\n' + cipherPhrase);\n}", "function highlight2(code) {\n return code.replace(/(F+)/g,'<span style=\"color: pink\">$1</span>').\n replace(/(L+)/g,'<span style=\"color: red\">$1</span>').\n replace(/(R+)/g,'<span style=\"color: green\">$1</span>').\n replace(/(\\d+)/g,'<span style=\"color: orange\">$1</span>');\n}", "checkChar(inputChars) {\n let len = inputChars.length;\n if(this.chars.slice(0, len).join('') === inputChars.join('')) {\n for(let i = 0; i < len; i++) {\n this.children[i].classList.add('highlight');\n }\n this.isUpdated = true;\n } else if (this.isUpdated) {\n for(let i = 0; i < this.chars.length; i++) {\n this.children[i].classList.remove('highlight')\n }\n }\n }", "showMatchedLetter(letter) {\n const selectedLetter = document.querySelectorAll(\".letter\");\n selectedLetter.forEach(element => {\n if (element.innerHTML === letter) {\n element.className = \"show\";\n }\n });\n }", "function unhighlightAll() {\n\t\tfor (var row=0; row<cipher[which].length; row++) {\n\t\t\tfor (var col=0; col<cipher[which][row].length; col++) {\n\t\t\t\tu(row+\"_\"+col);\n\t\t\t}\n\t\t}\n\t}", "function unhighlightAll() {\n\t\tfor (var row=0; row<cipher[which].length; row++) {\n\t\t\tfor (var col=0; col<cipher[which][row].length; col++) {\n\t\t\t\tu(row+\"_\"+col);\n\t\t\t}\n\t\t}\n\t}", "function letterMatched() {\n for (var i = 0; i < randomWords.length; i++) {\n if (letterClicked === randomWords[i]) {\n emptySpacesForDashes[i] = letterClicked;\n }\n $('#underscore').text(emptySpacesForDashes.join(' '));\n } \n}", "showMatchedLetter(letter) {\n const displayedLetters = document.querySelectorAll('.letter')\n\n displayedLetters.forEach(item => {\n if (item.classList.contains('letter') && item.innerHTML === letter) {\n item.classList.add('show');\n item.classList.remove('hide');\n item.innerHTML = `${letter}`;\n }\n })\n }", "showMatchedLetter(letter) {\r\n const reference = `.hide.letter.${letter}`;\r\n const correctLetters = document.querySelectorAll(reference);\r\n for (let each of correctLetters) {\r\n each.classList.remove('hide');\r\n each.classList.add('show');\r\n }\r\n}", "showMatchedLetter(letter) {\n\t\tlet liMatches = document.querySelectorAll('LI.letter');\n\t\tfor (let i = 0; i < liMatches.length; i += 1) {\n\t\t\tif (liMatches[i].className[12] === letter) {\n\t\t\t\tliMatches[i].className = 'show';\n\t\t\t}\n\t\t}\n\n\t}", "showMatchedLetter(letter){\n\n const phrases = document.querySelector('#phrase ul').children;\n\n\n\n for (let i = 0; i < phrases.length; i++) {\n if (phrases[i].textContent === letter) {\n phrases[i].setAttribute('class', `show letter ${letter}`);\n\n }\n }\n }", "function checkLetter() {\n const sContainer = selectElement(\".secret-word\");\n let word = secretWord.toUpperCase();\n\n //Check if word includes this letter\n if (word.includes(this.textContent)) {\n this.classList.add(\"true\");\n let indexArr = [];\n //Get all indexs where we must replace symbol\n for (let i = 0; i < secretWord.length; i++) {\n let symbol = word.indexOf(this.textContent, i);\n if (symbol != -1) {\n indexArr.push({ index: symbol });\n }\n }\n //Replace symbols\n for (let i = 0; i < indexArr.length; i++) {\n let wordSize = (+indexArr[i].index) ?\n this.textContent.toLowerCase() : this.textContent;\n sContainer.textContent = sContainer.textContent\n .replaceAt(indexArr[i].index, wordSize);\n }\n\n if (sContainer.textContent == secretWord) {\n wictoryFun();\n }\n }\n else {\n selectElement(\".hangman img\").classList.add(\"hide\");\n selectElement(\".hangman img\").src = `image/${count}.png`;\n setTimeout(() => selectElement(\".hangman img\").classList.remove(\"hide\"), 400);\n this.classList.add(\"false\");\n count++;\n if (count == 13) {\n setTimeout(overFun, 1500);\n };\n }\n this.removeEventListener('click', checkLetter);\n}", "showMatchedLetter(letter) {\n $(\".letter\").each(function(index) {\n if (this.innerText === letter) {\n $(this).removeClass('hide');\n $(this).addClass('show');\n }\n });\n }", "showMatchedLetter(letter) {\r\n const letters = Array.from(document.getElementsByClassName(letter));\r\n letters.forEach(match => {\r\n match.classList.remove('hide');\r\n match.classList.add('show');\r\n });\r\n }", "function Hilitor2(id, tag)\n{\n\n var targetNode = document.getElementById(id) || document.body;\n var hiliteTag = tag || \"EM\";\n var skipTags = new RegExp(\"^(?:\" + hiliteTag + \"|SCRIPT|FORM)$\");\n var colors = [\"#0e7582\", \"#0e7582\", \"#0e7582\", \"#0e7582\", \"#0e7582\"];\n var wordColor = [];\n var colorIdx = 0;\n var matchRegex = \"\";\n var openLeft = false;\n var openRight = false;\n\n this.setMatchType = function(type)\n {\n switch(type)\n {\n case \"left\":\n this.openLeft = false;\n this.openRight = true;\n break;\n case \"right\":\n this.openLeft = true;\n this.openRight = false;\n break;\n case \"open\":\n this.openLeft = this.openRight = true;\n break;\n default:\n this.openLeft = this.openRight = false;\n }\n };\n\n function addAccents(input)\n {\n retval = input;\n retval = retval.replace(/([ao])e/ig, \"$1\");\n retval = retval.replace(/\\\\u00E[024]/ig, \"a\");\n retval = retval.replace(/\\\\u00E[89AB]/ig, \"e\");\n retval = retval.replace(/\\\\u00E[EF]/ig, \"i\");\n retval = retval.replace(/\\\\u00F[46]/ig, \"o\");\n retval = retval.replace(/\\\\u00F[9BC]/ig, \"u\");\n retval = retval.replace(/\\\\u00FF/ig, \"y\");\n retval = retval.replace(/\\\\u00DF/ig, \"s\");\n retval = retval.replace(/a/ig, \"([aàâä]|ae)\");\n retval = retval.replace(/e/ig, \"[eèéêë]\");\n retval = retval.replace(/i/ig, \"[iîï]\");\n retval = retval.replace(/o/ig, \"([oôö]|oe)\");\n retval = retval.replace(/u/ig, \"[uùûü]\");\n retval = retval.replace(/y/ig, \"[yÿ]\");\n retval = retval.replace(/s/ig, \"(ss|[sß])\");\n return retval;\n }\n\n this.setRegex = function(input)\n {\n input = input.replace(/\\\\([^u]|$)/g, \"$1\");\n input = input.replace(/[^\\w\\\\\\s']+/g, \"\").replace(/\\s+/g, \"|\");\n input = addAccents(input);\n var re = \"(\" + input + \")\";\n if(!this.openLeft) re = \"(?:^|[\\\\b\\\\s])\" + re;\n if(!this.openRight) re = re + \"(?:[\\\\b\\\\s]|$)\";\n matchRegex = new RegExp(re, \"i\");\n };\n\n this.getRegex = function()\n {\n var retval = matchRegex.toString();\n retval = retval.replace(/(^\\/|\\(\\?:[^\\)]+\\)|\\/i$)/g, \"\");\n return retval;\n };\n\n // recursively apply word highlighting\n this.hiliteWords = function(node)\n {\n if(node === undefined || !node) return;\n if(!matchRegex) return;\n if(skipTags.test(node.nodeName)) return;\n\n if(node.hasChildNodes()) {\n for(var i=0; i < node.childNodes.length; i++)\n this.hiliteWords(node.childNodes[i]);\n }\n if(node.nodeType == 3) { // NODE_TEXT\n if((nv = node.nodeValue) && (regs = matchRegex.exec(nv))) {\n if(!wordColor[regs[1].toLowerCase()]) {\n wordColor[regs[1].toLowerCase()] = colors[colorIdx++ % colors.length];\n }\n\n var match = document.createElement(hiliteTag);\n match.appendChild(document.createTextNode(regs[1]));\n match.style.backgroundColor = wordColor[regs[1].toLowerCase()];\n match.style.fontStyle = \"inherit\";\n match.style.color = \"#000\";\n\n var after;\n if(regs[0].match(/^\\s/)) { // in case of leading whitespace\n after = node.splitText(regs.index + 1);\n } else {\n after = node.splitText(regs.index);\n }\n after.nodeValue = after.nodeValue.substring(regs[1].length);\n node.parentNode.insertBefore(match, after);\n }\n };\n };\n\n // remove highlighting\n this.remove = function()\n {\n var arr = document.getElementsByTagName(hiliteTag);\n while(arr.length && (el = arr[0])) {\n var parent = el.parentNode;\n parent.replaceChild(el.firstChild, el);\n parent.normalize();\n }\n };\n\n // start highlighting at target node\n this.apply = function(input)\n {\n this.remove();\n if(input === undefined || !(input = input.replace(/(^\\s+|\\s+$)/g, \"\"))) return;\n input = convertCharStr2jEsc(input);\n this.setRegex(input);\n this.hiliteWords(targetNode);\n };\n\n // added by Yanosh Kunsh to include utf-8 string comparison\n function dec2hex4(textString)\n {\n var hexequiv = new Array(\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\");\n return hexequiv[(textString >> 12) & 0xF] + hexequiv[(textString >> 8) & 0xF] + hexequiv[(textString >> 4) & 0xF] + hexequiv[textString & 0xF];\n }\n\n function convertCharStr2jEsc(str, cstyle)\n {\n // Converts a string of characters to JavaScript escapes\n // str: sequence of Unicode characters\n var highsurrogate = 0;\n var suppCP;\n var pad;\n var n = 0;\n var outputString = '';\n for(var i=0; i < str.length; i++) {\n var cc = str.charCodeAt(i);\n if(cc < 0 || cc > 0xFFFF) {\n outputString += '!Error in convertCharStr2UTF16: unexpected charCodeAt result, cc=' + cc + '!';\n }\n if(highsurrogate != 0) { // this is a supp char, and cc contains the low surrogate\n if(0xDC00 <= cc && cc <= 0xDFFF) {\n suppCP = 0x10000 + ((highsurrogate - 0xD800) << 10) + (cc - 0xDC00);\n if(cstyle) {\n pad = suppCP.toString(16);\n while(pad.length < 8) {\n pad = '0' + pad;\n }\n outputString += '\\\\U' + pad;\n } else {\n suppCP -= 0x10000;\n outputString += '\\\\u' + dec2hex4(0xD800 | (suppCP >> 10)) + '\\\\u' + dec2hex4(0xDC00 | (suppCP & 0x3FF));\n }\n highsurrogate = 0;\n continue;\n } else {\n outputString += 'Error in convertCharStr2UTF16: low surrogate expected, cc=' + cc + '!';\n highsurrogate = 0;\n }\n }\n if(0xD800 <= cc && cc <= 0xDBFF) { // start of supplementary character\n highsurrogate = cc;\n } else { // this is a BMP character\n switch(cc)\n {\n case 0:\n outputString += '\\\\0';\n break;\n case 8:\n outputString += '\\\\b';\n break;\n case 9:\n outputString += '\\\\t';\n break;\n case 10:\n outputString += '\\\\n';\n break;\n case 13:\n outputString += '\\\\r';\n break;\n case 11:\n outputString += '\\\\v';\n break;\n case 12:\n outputString += '\\\\f';\n break;\n case 34:\n outputString += '\\\\\\\"';\n break;\n case 39:\n outputString += '\\\\\\'';\n break;\n case 92:\n outputString += '\\\\\\\\';\n break;\n default:\n if(cc > 0x1f && cc < 0x7F) {\n outputString += String.fromCharCode(cc);\n } else {\n pad = cc.toString(16).toUpperCase();\n while(pad.length < 4) {\n pad = '0' + pad;\n }\n outputString += '\\\\u' + pad;\n }\n }\n }\n }\n return outputString;\n }\n\n}", "checkLetter(){\n /** will correctly match if letter is on the current phrase**/\n let matched = this;\n let phraseLi = document.getElementById(\"phrase\").getElementsByTagName(\"li\");\n $('.keyrow button').bind('click', function(){\n for (var i = 0; i < phraseLi.length; i++) {\n if ($(this).text() === phraseLi[i].innerHTML) {\n $(this).addClass(\"phraseLetters\");\n phraseLi[i].classList.add(\"correct\");\n matched.showMatchedLetter();\n }\n }\n })\n }", "showMatchedLetter(letter) {\r\n const listItem = document.querySelectorAll('.letter');\r\n // Add 'show' class if passed letter mathces\r\n for (let li of listItem) {\r\n if (li.innerText === letter) {\r\n li.classList.remove('hide');\r\n li.classList.add('show');\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\n const liElement = document.getElementsByClassName('letter');\n for (let i = 0; i < liElement.length; i++) {\n if (liElement[i].innerHTML === letter) {\n liElement[i].className = 'letter show';\n console.log('Success'); //track if letter is matched in the console\n\n } else {\n console.log('Fail'); //track if letter is not matched in the console\n }\n }\n }", "showMatchedLetter(correctLetter){\n correctLetter.classList.remove('hide');\n correctLetter.classList.add('show');\n }", "function WR_Highlight_key() {\n\t \t$( '.search-results .search-item .entry-content p, .search-results .search-item .entry-title a' ).each( function( i, el ) {\n\t \t\tvar keyword = $( '.search-results .result-list' ).attr( 'data-key' );\n\t \t\tvar text = $( el ).text();\n\t \t\tvar keywords = keyword.split( ' ' );\n\n\t \t\t$.each( keywords, function( i, key ) {\n\t \t\t\tvar regex = new RegExp( '(' + key + ')', 'gi' );\n\t \t\t\ttext = text.replace( regex, '<span class=\"highlight\">$1</span>' );\n\t \t\t\t$( el ).html( text )\n\t \t\t} )\n\t \t} )\n\t }", "function reveal(guess) {\n for (var z = 0; z < word.length; z++) {\n if (word[z] == guess) {\n context.fillText(word[z], (100 + (z * 20)), 490);\n lettersRemaining--;\n console.log(\"reveal: \" + lettersRemaining);\n }\n }\n }", "function letterChanges(str) {}", "function letterChanges(str) {}", "function letterChanges(str) {}", "function cipher(phrase){ // Con esta funcion cifraremos la frase ingresada por el usuario\n var str= \"\";// Aqui se guardara la frase cifrada\n for (var i = 0; i < phrase.length; i++) { //Iterar el string para poder obtener el numero de la letra dentro del codigo ascii para posteriormente poder recorrernos 33 espacios.\n var codeNumber = phrase.charCodeAt(i); // charCodeAt nos devuelve un número indicando el valor Unicode del carácter en el índice proporcionado el cual estaremos iterando (i).\n var letterMay = (codeNumber - 65 + 33) % 26 + 65;\n var letterMin = (codeNumber - 97 + 33) % 26 + 97;\n\n if (codeNumber >= 65 && codeNumber <= 90) { //Condicionamos y seccionamos, si codeNumber es mayor o igual a la posicion 65 o menor o igual que 90 en el codigo ASCII seran letras Mayusculas.\n str += String.fromCharCode(letterMay);\n\n } else {\n (codeNumber >= 97 && codeNumber <= 122) //Condicionamos y seccionamos, si codeNumber es mayor o igual a la posicion 97 o menor o igual que 122 en el codigo ASCII seran letras Minisculas.\n str += String.fromCharCode(letterMin);\n }\n }\n\n console.log(str); // str Nos muestra la frase cifrada\n document.write(\"Tu frase cifrada es \" + str); //Imprimimos en la pantalla la frase cifrada para el usuario que guardamos en la variable str.\n}", "function findLetterIndexes(letter) {\n var letterIndexes = [];\n for (var i = 0; i < randomWordArray.length; i++) {\n if (randomWordArray[i] === letter) {\n letterIndexes.push(i);\n }\n }\n replaceDashes(letterIndexes); // returns an array of number indexes like [1, 2, 3]\n }", "showMatchedLetter(inputLetter) {\r\n const gameLetterElements = document.querySelectorAll('#phrase li');\r\n console.log(gameLetterElements)\r\n gameLetterElements.forEach(current => {\r\n console.log(`Current phrase letter: ${current.innerText}`);\r\n console.log(`keyed letter: ${inputLetter}`);\r\n if (current.innerText.toLowerCase() == inputLetter) {\r\n current.classList.remove(\"hide\");\r\n current.classList.add(\"show\");\r\n }\r\n })\r\n }", "function ceasarCipher3(alphabet) {\n for (var i = 0; i < alphabet.length; i++){\n console.log(alphabet[i].charCodeAt());\n }\n}", "function correctLetter(letter) {\n for (let key of keyboard) {\n if (key.textContent == letter) {\n key.classList.add(\"chosen\");\n key.disabled = true;\n }\n }\n}", "function HighlightString(StringToHighlight){\n\t// const BackgroundColour = '#fff' // white\n\t// const LetterColourLowerCase = '#008080' // teal\n\t// const LetterColourUpperCase = red\n\t// const NumberColour = '#800080' // purple\n\t// const OtherColour = '#9a6510' // Golden-brown\n\n\t// Colour scheme:\n\tvar BackgroundColour = '#2e2e2e'\n\tvar LetterColourLowerCase = '#b4d273' // Green\n\tvar LetterColourUpperCase = '#9e86c8' // Purple\n\tvar NumberColour = '#6c99bb' // Blue\n\tvar OtherColour = '#e87d3e' // Orange\n\n\t// Output size\n\tvar PrintSize = '2em';\n\n\tfunction IsCharacterDigit(character){\n\t\tif(0 <= character && character <= 9){\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tfunction IsCharacterLetter(character){\n\t\t// If the character has a different upper and lower case representation it is reasonable for my use to assume that it is a letter.\n\t\t// It might even be a bit too inclusive, I guess if it annoys me over time I'll go for something more limmited like \"return (/[a-zA-Z]/).test(char)\"\n\t\treturn character.toLowerCase() != character.toUpperCase();\n\t}\n\n\tfunction IsLetterUppercase(letter){\n\t\treturn letter == letter.toUpperCase();\n\t}\n\n\n\t/* Note that ListOfCharactersWithProperties is not used, because I decided\n\t it would be simpler and faster to iterate over the string only once, with\n\t the tradeof for more memor needed to store the precomputed list of css\n\t string and the premade string for the output. Still keeping it around,\n\t because it's neat for debugging without having to step through everything\n\t for each character.\n\t*/\n\tvar ListOfCharactersWithProperties = [];\n\tvar ListOfCssStrings = [];\n\tvar ReassembledStringForPrinting = \"\";\n\n\tfor(const character of StringToHighlight){\n\t\tvar colour = OtherColour;\n\t\tif(IsCharacterLetter(character)){\n\t\t\tif(IsLetterUppercase(character)){\n\t\t\t\tcolour = LetterColourUpperCase;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tcolour = LetterColourLowerCase;\n\t\t\t}\n\t\t}\n\t\telse if(IsCharacterDigit(character)){\n\t\t\tcolour = NumberColour;\n\t\t}\n\n\t\tvar CssString = `background: ${BackgroundColour}; color: ${colour}; font-size: ${PrintSize};`;\n\t\tvar PrintString = `%c${character}`;\n\n\t\tvar characterWithMetadata = {\n\t\t\tCharacter: character,\n\t\t\tStringRepresentationForPrinting: PrintString,\n\t\t\tCssForPrinting: CssString\n\t\t};\n\n\t\tListOfCharactersWithProperties.push(characterWithMetadata);\n\t\tListOfCssStrings.push(CssString);\n\t\tReassembledStringForPrinting += PrintString;\n\n\t\t// console.debug(character);\n\t}\n\n\t// console.debug(ListOfCharactersWithProperties);\n\n\t// Print legend so that it's easier to remember what is what if you only have a lot of lookalike characters:\n\tconsole.log(\"Legend: %cABCD%cefgh%c1234%c!@#$\",\n\t\t`background: ${BackgroundColour}; color: ${LetterColourUpperCase}; font-size: ${PrintSize};`,\n\t\t`background: ${BackgroundColour}; color: ${LetterColourLowerCase}; font-size: ${PrintSize};`,\n\t\t`background: ${BackgroundColour}; color: ${NumberColour}; font-size: ${PrintSize};`,\n\t\t`background: ${BackgroundColour}; color: ${OtherColour}; font-size: ${PrintSize};`);\n\n\t// Print the highlighted string:\n\tconsole.log(ReassembledStringForPrinting, ...ListOfCssStrings);\n}", "showMatchedLetter(letter) {\r\n\r\n // Get the matchedLetters that have a class name letter\r\n const matchedLetters = document.getElementsByClassName(letter);\r\n\r\n // Loop through the matchedLetters and replace the hide class with show\r\n for (let k = 0; k < matchedLetters.length; k++) {\r\n matchedLetters[k].className = matchedLetters[k].className.replace(/\\bhide\\b/g, \"show\");\r\n } \r\n }", "function highlight(id) {\n\n // Find and remove all higlighted chars\n var elems = el.getElementsByTagName('span');\n removeClasses(elems, 'highlight');\n\n // Mark the matching chars as highlited\n var a = annotationById(id);\n if (a) addClasses(elements(a.pos), 'highlight');\n }", "showMatchedLetter(letter) {\n for (let i = 0; i < ul.children.length; i++) {\n let letterVisible = document.querySelector(`#phrase > ul > li.hide.letter.${letter}`);\n // if letter matches set class to show letter\n if (letterVisible !== null) {\n letterVisible.className = `show letter ${letter}`;\n }\n }\n }", "showMatchedLetter(letter) {\n const appendedLI = document.querySelectorAll('#phrase ul li');\n\n appendedLI.forEach((element) => {\n if (element.textContent === letter) {\n element.className = 'letter show';\n }\n });\n }", "function MyApp_HighlightAllOccurencesOfString(keyword) {\n// alert(keyword);\n\nMyApp_RemoveAllHighlights();\nMyApp_HighlightAllOccurencesOfStringForElement(document.body,\n\t\tkeyword.toLowerCase());\n}", "showMatchedLetter(letter) {\n const list = document.getElementsByClassName('hide letter');\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n // called twice to fix bug: the same consecutive letter was not being revealed, i.e., in the word `call` guessing l would only display the first l.\n for (const li of list) {\n if (li.textContent === letter.textContent) {\n li.className = 'show';\n letter.classList.add(\"chosen\");\n letter.disabled = true;\n }\n }\n }", "function incorrectLetter(letter) {\n for (let key of keyboard) {\n if (key.textContent == letter) {\n key.classList.add(\"wrong\");\n key.disabled = \"true\";\n }\n }\n}", "displayLettersToGuess() {\r\n let lettersNotGuessed = \"\\n\";\r\n for (let letter of Utilities.alphabet) {\r\n if (!this.guessedLetters.includes(letter.toLowerCase())) {\r\n lettersNotGuessed += letter.toUpperCase() + \" \";\r\n }\r\n else {\r\n lettersNotGuessed += \" \";\r\n }\r\n }\r\n lettersNotGuessed += \"\\n\";\r\n console.log(Utilities.strReplaceByIndex(lettersNotGuessed, \"\\n\", 39));\r\n }", "function kb_highlightAllKeys() {\n\n for(var keyId in kb_keys) {\n\n kb_highlightKey(keyId);\n }\n}", "showMatchedLetter(letter) {\n let letters = document.getElementsByClassName(letter);\n for (let i = 0; i < letters.length; i++) {\n if (letters[i].innerHTML === letter) {\n letters[i].classList.remove('hide');\n letters[i].classList.add('show');\n }\n }\n }", "showMatchedLetter(letter){\r\n const phraseLi = document.querySelectorAll('#phrase > ul > li');\r\n \r\n if(this.checkLetter(letter) === true){\r\n for(let i =0; i < phraseLi.length; i++){\r\n if(phraseLi[i].textContent === letter ){\r\n phraseLi[i].classList.remove('hide');\r\n phraseLi[i].classList.add('show');\r\n \r\n }\r\n }\r\n \r\n\r\n }\r\n \r\n \r\n }", "showMatchedLetter(letter) {\n const letterSpace = document.getElementsByClassName(`hide letter ${letter}`);\n\n // keeps the length of letterSpace array value constant\n const letterLength = letterSpace.length;\n \n /* loops through all classes with the 'hide letter (letter parameter)' \n and changes the class name to 'show letter (letter parameter)'*/\n for (let i = 0; i < letterLength; i++) {\n letterSpace[0].className = `show letter ${letter}`;\n }\n }", "function vigenereCipher(plaintext, keyword) {\n var CONVERT = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', \n 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',] \n\n var converValue = keyword.toLowerCase().split('').map(char => CONVERT.indexOf(char));\n var length = keyword.length;\n var result;\n var convertedCount = -1;\n\n result = plaintext.split('').map(function(char) {\n if (char.match(/[^a-z]/i)) return char;\n if (convertedCount === length - 1) convertedCount = -1;\n convertedCount++;\n \n return caesarEncrypt(char, converValue[convertedCount]);\n }).join('');\n\n return result\n}", "function ccipher(d) {\n var encMsg = '';\n var shift = 3; //shift alpha 3 letters over\n for (var i = 0; i < d.length; i++) {\n var code = d.charCodeAt(i);\n if ((code >= 65) && (code <= 90)) {\n //uppercase\n encMsg += String.fromCharCode((mod((code - 65 + shift), 26) + 65));\n } else if ((code >= 97) && (code <= 122)) {\n encMsg += String.fromCharCode((mod((code - 97 + shift), 26) + 97));\n } else {\n encMsg += String.fromCharCode(code);\n }\n }\n return encMsg;\n}", "function encryptorMin(word) {\n word = word.replace(/a/gi, '4');\n word = word.replace(/e/gi, '3');\n word = word.replace(/i/gi, '1');\n word = word.replace(/s/gi, '5');\n word = word.replace(/o/gi, '0');\n console.log(word);\n}", "function changeTextMainColor() {\n allWords.forEach(word => {\n if (!word.hasAttribute(\"data-highlight\")) {\n word.style.color = `rgba(${CP.HEX2RGB(clock.userTextMainColor.color).join()}, ${clock.userTextMainColor.alpha})`;\n\n }\n });\n}", "showMatchedLetter(letter) {\n document.querySelectorAll(`.${letter}`).forEach((element) => {\n element.classList.remove('hide');\n element.classList.add('show', 'animated', 'flipInY');\n });\n }", "function checkLetter(button) {\r\n const fontClicked = button.innerHTML;\r\n var letterFound = null;\r\n\r\n for (let i = 0; i < letter.length; i++){\r\n if (fontClicked === letter[i].innerHTML.toLowerCase()) {\r\n letter[i].classList.add('show');\r\n letterFound = true;\r\n letterFound = fontClicked;\r\n }\r\n }\r\n return letterFound;\r\n}", "showMatchedLetter(letter) {\n let matchedLetters = document.getElementsByClassName(letter); \n let i;\n for (i = 0; i < matchedLetters.length;i++) {\n matchedLetters[i].classList.remove(\"hide\");\n matchedLetters[i].classList.add(\"show\");\n }\n\n }", "showMatchedLetter(letter) {\n let matches = document\n .getElementById(\"phrase\")\n .getElementsByClassName(letter);\n //must make collection into an array to use array methods\n //learned from https://stackoverflow.com/questions/3871547/js-iterating-over-result-of-getelementsbyclassname-using-array-foreach\n Array.from(matches).forEach((match) => {\n match.classList.replace(\"hide\", \"show\");\n });\n }", "showMatchedLetter(letter) {\r\n const list = document.querySelectorAll('li');\r\n for (let i = 0; i < list.length; i+=1) {\r\n if (letter === list[i].textContent){\r\n list[i].classList.add('show');\r\n }\r\n }\r\n }", "showMatchedLetter(letter) {\r\n const matchingLetterNodes = document.querySelectorAll(`li.hide.letter.${letter}`)\r\n for (let node of matchingLetterNodes) {\r\n node.className = node.className.replace(\"hide\", \"show\");\r\n }\r\n }", "function tongues(code) {\n var alpha = 'aiyeoubkxznhdcwgpvjqtsrlmf';\n var repl = 'eouaiypvjqtsrlmfbkxznhdcwg';\n \n return code.replace(/[a-z]/gi, function(m) {\n var lower = m.toLowerCase();\n return lower === m ? repl[alpha.indexOf(m)] : repl[alpha.indexOf(lower)].toUpperCase();\n });\n}", "function highlight() {\n var code_blocks = document.body.getElementsByClassName(\"language-c\");\n var keywords = [\n \"auto\", \"break\", \"case\", \"char\", \"const\", \"continue\", \"default\",\n \"do\", \"double\", \"else\", \"enum\", \"extern\", \"float\", \"for\", \"goto\",\n \"if\", \"inline\", \"int\", \"long\", \"register\", \"restrict\", \"return\",\n \"short\", \"signed\", \"sizeof\", \"static\", \"struct\", \"switch\",\n \"typedef\", \"union\", \"unsigned\", \"void\", \"volatile\", \"while\",\n ];\n var regex_var = /\\b[A-z][A-z0-9]*/;\n var regex_number = /\\b0[xX][0-9a-fA-F]+\\b|\\b[0-9]*\\.[0-9]+\\b|\\b[0-9]*\\b/;\n var regex_string = /\"[^\"]*\"/;\n var regex_symbol = /&gt;|&lt;|\\ |\\(|\\)|;|-/;\n for (var i = 0; i < code_blocks.length; i++) {\n var element = code_blocks.item(i);\n var code_lines = element.innerHTML.split('\\n');\n var cursor = 0;\n\n var parts = [];\n var insert_index = 0;\n function insert_at(index, insertable) {\n if (index < insert_index) console.error(\"inserting before last insert!!\");\n parts.push(element.innerHTML.substr(insert_index, index - insert_index));\n parts.push(insertable);\n insert_index = index;\n }\n\n var in_block_comment = false;\n\n for (var j = 0; j < code_lines.length; j++) {\n var words = code_lines[j].split(regex_symbol);\n var in_line_comment = false;\n\n for (var k = 0; k < words.length; k++) {\n var word = words[k];\n\n // Special case for < and >, because they're escaped in\n // innerHTML.\n var to_be_processed_html = element.innerHTML.substr(cursor);\n if (to_be_processed_html.startsWith(\"lt;\") ||\n to_be_processed_html.startsWith(\"gt;\")) {\n cursor += 3;\n }\n\n if (in_block_comment) {\n if (word == \"*/\") {\n in_block_comment = false;\n insert_at(cursor + word.length, \"</span>\"); // close comment block\n }\n } else {\n if (!in_line_comment) {\n if (word == \"//\") {\n in_line_comment = true;\n insert_at(cursor, \"<span class='syntax-comment'>\"); // open comment line\n }\n if (word == \"/*\") {\n in_block_comment = true;\n insert_at(cursor, \"<span class='syntax-comment'>\"); // open comment block\n }\n }\n\n if (!in_line_comment && !in_block_comment) {\n if (keywords.indexOf(word) != -1) {\n insert_at(cursor, \"<span class='syntax-keyword'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_string.test(word)) {\n insert_at(cursor, \"<span class='syntax-string'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_var.test(word) && element.innerHTML.substr(cursor + word.length, 1) == \"(\") {\n insert_at(cursor, \"<span class='syntax-call'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_var.test(word)) {\n insert_at(cursor, \"<span class='syntax-variable'>\");\n insert_at(cursor + word.length, \"</span>\");\n } else if (regex_number.test(word)) {\n insert_at(cursor, \"<span class='syntax-number'>\");\n insert_at(cursor + word.length, \"</span>\");\n }\n }\n }\n\n cursor += word.length + 1;\n }\n\n if (in_line_comment) {\n insert_at(cursor, \"</span>\"); // close comment line\n }\n }\n\n parts.push(element.innerHTML.substr(insert_index));\n element.innerHTML = parts.join('');\n\n // When processing, using &lt; and &gt; is forced upon us. Now we\n // can fix that to allow for good copypasting.\n element.innerHTML.replace(/&lt;/g, \"<\");\n element.innerHTML.replace(/&gt;/g, \">\");\n }\n}", "HighlightCandidates (nn, ccs)\r\n { if (nn<0) { this.ExecCommands('',1); return; }\r\n let ii0=nn%8;\r\n let jj0=7-(nn-ii0)/8;\r\n let pp=this.Board[ii0][jj0];\r\n let cc=Math.sign(pp);\r\n let tt=(1-cc)/2;\r\n let dd, ddi, ddj, bb, jj, aa=new Array();\r\n let nna=0, ddA=0;\r\n if (ccs.charAt(0)==\"A\") ddA=1;\r\n\r\n if (Math.abs(pp)==6)\r\n { this.Board[ii0][jj0]=0;\r\n if (this.IsOnBoard(ii0, jj0+cc))\r\n { bb=this.Board[ii0][jj0+cc];\r\n if (bb==0)\r\n { this.Board[ii0][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+97)+(jj0+cc+1);\r\n this.Board[ii0][jj0+cc]=bb;\r\n if (2*jj0+5*cc==7)\r\n { bb=this.Board[ii0][jj0+2*cc];\r\n if (bb==0)\r\n { this.Board[ii0][jj0+2*cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { nna-=ddA;\r\n aa[nna++]=String.fromCharCode(ii0+97)+(jj0+2*cc+1);\r\n }\r\n this.Board[ii0][jj0+2*cc]=bb;\r\n }\r\n }\r\n }\r\n }\r\n for (ddi=-1; ddi<=1; ddi+=2)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+cc))\r\n { bb=this.Board[ii0+ddi][jj0+cc];\r\n if (bb*cc<0)\r\n { this.Board[ii0+ddi][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+cc+1);\r\n this.Board[ii0+ddi][jj0+cc]=bb;\r\n }\r\n }\r\n if (2*jj0-cc==7)\r\n { if (this.IsOnBoard(ii0+ddi, jj0))\r\n { if (this.Board[ii0+ddi][jj0]==-cc*6)\r\n { bb=this.Board[ii0+ddi][jj0+cc];\r\n if (bb==0)\r\n { if (this.MoveCount>this.StartMove)\r\n { this.CanPass=-1;\r\n dd=this.HistPiece[0][this.MoveCount-this.StartMove-1];\r\n if ((this.HistType[0][this.MoveCount-this.StartMove-1]==5)&&(Math.abs(this.HistPosY[0][this.MoveCount-this.StartMove-1]-this.Piece[1-this.MoveType][dd].Pos.Y)==2))\r\n this.CanPass=this.Piece[1-this.MoveType][dd].Pos.X;\r\n }\r\n else\r\n this.CanPass=this.EnPass;\r\n if (this.CanPass==ii0+ddi)\r\n { this.Board[ii0+ddi][jj0+cc]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+cc+1);\r\n this.Board[ii0+ddi][jj0+cc]=bb;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if (Math.abs(pp)==5)\r\n { this.Board[ii0][jj0]=0;\r\n for (ddi=-2; ddi<=2; ddi+=4)\r\n { for (ddj=-1; ddj<=1; ddj+=2)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+ddj))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n for (ddi=-1; ddi<=1; ddi+=2)\r\n { for (ddj=-2; ddj<=2; ddj+=4)\r\n { if (this.IsOnBoard(ii0+ddi, jj0+ddj))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if ((Math.abs(pp)==2)||(Math.abs(pp)==4))\r\n { this.Board[ii0][jj0]=0;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0+dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0+dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0-dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0-dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0-dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0-dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0-dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0-dd))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0-dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0-dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0-dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0-dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n\r\n if ((Math.abs(pp)==2)||(Math.abs(pp)==3))\r\n { this.Board[ii0][jj0]=0;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0+dd,jj0))&&(bb==0))\r\n { bb=this.Board[ii0+dd][jj0];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+dd][jj0]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+dd+97)+(jj0+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0+dd][jj0]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n dd=1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0][jj0+dd]=bb;\r\n }\r\n dd++;\r\n }\r\n if (dd>1) nna+=ddA;\r\n dd=-1;\r\n bb=0;\r\n while ((this.IsOnBoard(ii0,jj0+dd))&&(bb==0))\r\n { bb=this.Board[ii0][jj0+dd];\r\n if (bb*cc<=0)\r\n { this.Board[ii0][jj0+dd]=pp;\r\n if (!this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, tt))\r\n { aa[nna++]=String.fromCharCode(ii0+97)+(jj0+dd+1);\r\n nna-=ddA;\r\n }\r\n this.Board[ii0][jj0+dd]=bb;\r\n }\r\n dd--;\r\n }\r\n if (dd<-1) nna+=ddA;\r\n this.Board[ii0][jj0]=pp;\r\n }\r\n\r\n if (Math.abs(pp)==1)\r\n { this.Board[ii0][jj0]=0;\r\n for (ddi=-1; ddi<=1; ddi++)\r\n { for (ddj=-1; ddj<=1; ddj++)\r\n { if (((ddi!=0)||(ddj!=0))&&(this.IsOnBoard(ii0+ddi, jj0+ddj)))\r\n { bb=this.Board[ii0+ddi][jj0+ddj];\r\n if (bb*cc<=0)\r\n { this.Board[ii0+ddi][jj0+ddj]=pp;\r\n if (!this.IsCheck(ii0+ddi, jj0+ddj, tt))\r\n aa[nna++]=String.fromCharCode(ii0+ddi+97)+(jj0+ddj+1);\r\n this.Board[ii0+ddi][jj0+ddj]=bb;\r\n }\r\n }\r\n }\r\n }\r\n this.Board[ii0][jj0]=pp;\r\n jj=this.CanCastleLong();//O-O-O with Chess960 rules\r\n if (jj>=0)\r\n { this.Board[ii0][jj0]=0;\r\n this.Board[this.Piece[this.MoveType][jj].Pos.X][this.Piece[this.MoveType][jj].Pos.Y]=0;\r\n this.Board[2][tt*7]=1-2*tt;\r\n this.Board[3][tt*7]=3*(1-2*tt);\r\n ddi=ii0;\r\n bb=0;\r\n { while (ddi>2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi--;\r\n }\r\n while (ddi<2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi++;\r\n }\r\n }\r\n bb+=this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, this.MoveType);\r\n if (bb==0) aa[nna++]=String.fromCharCode(2+97)+(tt*7+1);\r\n this.Board[2][tt*7]=0;\r\n this.Board[3][tt*7]=0;\r\n this.Board[ii0][jj0]=pp;\r\n this.Board[this.Piece[tt][jj].Pos.X][this.Piece[tt][jj].Pos.Y]=cc*3;\r\n }\r\n jj=this.CanCastleShort();//O-O with Chess960 rules\r\n if (jj>=0)\r\n { this.Board[ii0][jj0]=0;\r\n this.Board[this.Piece[this.MoveType][jj].Pos.X][this.Piece[this.MoveType][jj].Pos.Y]=0;\r\n this.Board[6][tt*7]=1-2*tt;\r\n this.Board[5][tt*7]=3*(1-2*tt);\r\n ddi=ii0;\r\n bb=0;\r\n { while (ddi>2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi--;\r\n }\r\n while (ddi<2)\r\n { bb+=this.IsCheck(ddi, tt*7, tt);\r\n ddi++;\r\n }\r\n }\r\n bb+=this.IsCheck(this.Piece[tt][0].Pos.X, this.Piece[tt][0].Pos.Y, this.MoveType);\r\n if (bb==0) aa[nna++]=String.fromCharCode(6+97)+(tt*7+1);\r\n this.Board[6][tt*7]=0;\r\n this.Board[5][tt*7]=0;\r\n this.Board[ii0][jj0]=pp;\r\n this.Board[this.Piece[tt][jj].Pos.X][this.Piece[tt][jj].Pos.Y]=cc*3;\r\n }\r\n }\r\n\r\n if ((nna>0)&&(ccs!=\" \"))\r\n { tt=ccs.charAt(0);\r\n cc=ccs.substr(1,6);\r\n if (tt==\"A\")\r\n { bb=tt+String.fromCharCode(ii0+97)+(jj0+1)+aa[0]+cc;\r\n for (jj=1; jj<nna; jj++) bb+=\",\"+tt+String.fromCharCode(ii0+97)+(jj0+1)+aa[jj]+cc;\r\n }\r\n else\r\n { bb=tt+aa[0]+cc;\r\n for (jj=1; jj<nna; jj++) bb+=\",\"+tt+aa[jj]+cc;\r\n }\r\n this.ExecCommands(bb,1);\r\n }\r\n else return(aa);\r\n }", "function insertKeyword(text, currColor, currWord){\n\n\tvar index = indexArr.length-1;\n\n\tif(index == 0){\n\t\ttextArr.push(text.substring(0 , indexArr[index]) + ' <span class = \"highlightWord\" style=\"background-color:' + currColor + '\">' + text.substring(indexArr[index] , indexArr[index]+currWord.text.length) + '</span>');\n\t}else{ \n\t\ttextArr.push(text.substring(indexArr[index-1]+currWord.text.length , indexArr[index]) + ' <span class = \"highlightWord\" style=\"background-color:' + currColor + '\">' + text.substring(indexArr[index] , indexArr[index]+currWord.text.length) + '</span>');\n\t}\n\n}", "drawSecretWord() {\n ctx.clearRect(0,canvas.height-40,canvas.width,40)\n GAME.secretWord.includes(PLAYER.guess) ? PLAYER.guessStatus = true : PLAYER.guessStatus = false\n for (let i = 0; i < GAME.secretWord.length; i++) {\n const element = GAME.secretWord[i];\n if(str_replace(from,to,element) === PLAYER.guess) {\n PLAYER.guessStatus = true\n GAME.answerArray[i] = element\n }\n let x = (canvas.width - ((GAME.secretWord.length * 24) + ((GAME.secretWord.length - 1) * 4))) + (i * (24 + 4))\n ctx.beginPath()\n ctx.font = \"32px calibri\"\n ctx.fillText(GAME.answerArray[i], x, canvas.height - 6)\n ctx.closePath()\n }\n }", "function encrypt(){\n var str = \"AEGIOSZHOLAMUNDOaegiosz\";\nconsole.log(str);\nvar encrypted = {\n A:\"4\",\n E:\"3\",\n G:\"6\",\n I:\"1\",\n O:\"0\",\n S:\"5\",\n Z:\"2\",\n a:\"4\",\n e:\"3\",\n g:\"6\",\n i:\"1\",\n o:\"0\",\n s:\"5\",\n z:\"2\"\n \n};\nstr = str.replace(/A|4|E|3|G|6|I|1|O|0|S|5|Z|2|a|4|e|3|g|6|i|1|o|0|s|5|z|2/gi, function(matched){\n return encrypted[matched];\n});\nconsole.log(str);\n}", "function fillInTheBlank(c) {\n\t// has the user completed the word\n\tvar done = true;\n\t// are there any errors\n\tvar hasErrors = false;\n\t\n\tif (c === null) {\n\t\t// remove the last character\n\t\tskipIdx--;\n\t\tfillIndices[skipIdx] = -1;\n\t} else {\n\t\t// fill in the current character\n\t\tfillIndices[skipIdx] = c;\n\t\tskipIdx++;\n\t}\n\t\n\tvar html = \"\";\n\tvar j = 0;\n\tfor (var i = 0; i < english[idx].length; i++) {\n\t\tvar char = english[idx].charAt(i);\n\t\t// is this an index that was skipped\n\t\tif (i === skipIndices[j]) {\n\t\t\tif (fillIndices[j] === char) {\n\t\t\t\t// the character matches, make it green\n\t\t\t\thtml = html + \"<font color=\\\"#00dd00\\\">\" + fillIndices[j] + \"</font>\";\n\t\t\t} else if (fillIndices[j] === -1) {\n\t\t\t\t// this character hasn't been entered in yet, put in an underscore\n\t\t\t\thtml = html + \"_\";\n\t\t\t\tdone = false;\n\t\t\t} else {\n\t\t\t\t// the character is wrong, make it red\n\t\t\t\thtml = html + \"<font color=\\\"#ff0000\\\">\" + fillIndices[j] + \"</font>\";\n\t\t\t\tdone = false;\n\t\t\t\thasErrors = true;\n\t\t\t}\n\t\t\tj++;\n\t\t} else {\n\t\t\thtml = html + char;\n\t\t}\n\t}\n\t\n\tif (done) {\n\t\t// we're done, reset and move on\n\t\tskipIdx = 0;\n\t\tnext(english[idx]);\n\t} else {\n\t\t// update the input\n\t\tdocument.getElementById(\"alphabetsInput\").innerHTML = html;\n\t\tif (hasErrors) {\n\t\t\t// show errors if there are any\n\t\t\tshowError();\n\t\t} else {\n\t\t\t// clear the error message otherwise\n\t\t\thideError();\n\t\t}\n\t}\n}", "function caeserCipher(str, shift) {\n const alphabetArr = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n let res = \"\";\n for(let i =0; i < str.length; i++){\n const char = str[i];\n const idx = alphabetArr.indexOf(char);\n //console.log(idx)\n if(idx === -1 ){\n res += char;\n continue;\n }\n const encodedIdx = (idx + shift) %26;\n console.log(encodedIdx)\n res += alphabetArr[encodedIdx]\n }\n return res;\n}", "function processSearchQuery(query){\n var transcript = document.getElementById(\"text\");\n for(var i=0; i<transcript.childNodes.length; i++){\n var strings = transcript.childNodes[i].innerHTML.split(\" \");\n transcript.childNodes[i].style.backgroundColor=\"#d1d1d1\";\n for(var j=0; j<strings.length; j++){\n if(strings[j] == query){\n transcript.childNodes[i].style.backgroundColor=\"#ffffff\";\n }\n }\n }\n }", "function AtbashCipher(txt){\n \n inputText = document.getElementById(\"input1\").value;\n outputText = \"\";\n \n //Checking if inputText is empty\n if(inputText.length==0)\n document.getElementById(\"input2\").value = \"\";\n \n for( i=0;i<inputText.length;i++)\n {\n // Checking if the character is in [a-z] or [A-Z] \n if( AtbashWheel[inputText[i]] !== undefined ) {\n res += AtbashWheel[inputText[i]]; \n }\n //Checking if character non alphabetic\n else {\n //No change, use the same character\n res += inputText[i];\n }\n document.getElementById(\"input2\").value = res;\n }\n}", "function enterLetters(){\n while (pos !== -1) { \n var selector = '#x' + pos;\n document.querySelector(selector).innerHTML = ('<h4 id=\"' + pos +'\">'+guess+'</h4>'); \n wordCheck [pos] = \"1\";\n //checks for the next instance\n pos = word.indexOf(guess, pos + 1);\n };\n writeLetterboxCorrect(); \n}", "checkLetter(letter){\r\n if( this.phrase.indexOf(letter) > -1 ){\r\n this.showMatchedLetter(letter);\r\n return true; \r\n }\r\n }", "function AniLetters(_lwidth, _lheight){\n var that = this;\n that.textTyped = [];\n that.textTyped = [];\n that.paths = [];\n that.letterWidth = _lwidth;\n that.letterHeight = _lheight;\n that.lineCount = 0;\n that.aniSteps = 20;\n that.drawMode = 3;\n that.cursorLocation = {x: 50, y: 50};\n that.letterPadding = 60;\n that.style = 1;\n\n /*\n Data Handling\n */\n\n // set the lineCount to the number of \"lines\" or text object in the textTyped Array\n this.getLineCount = function(){\n if (that.textTyped.length > 0){\n that.lineCount = that.textTyped.length - 1;\n } else {\n that.lineCount = 0;\n }\n };\n\n // get each data path of the letters\n this.getPaths = function(){\n that.paths = [];\n\n that.textTyped.forEach(function(txt, idx){\n txt.text.split('').forEach(function(d, i){\n\n var pathData = {\n letter: d.toUpperCase(),\n x: that.cursorLocation.x + (that.letterWidth + that.letterPadding * i),\n y: that.cursorLocation.y + (that.letterHeight * idx)\n };\n\n that.paths.push(pathData);\n\n });\n });\n };\n\n // add a text object for each line\n this.addText = function(_text){\n var textObject = {counter: 0, text: _text};\n return textObject;\n };\n\n /*\n Keyboard interactions\n */\n\n // remove letters\n this.removeLetters = function(){\n var textTypedCounter = that.lineCount;\n // remove letters from each object\n if (textTypedCounter >= 0 && that.textTyped[0].text.length > 0){\n that.textTyped[textTypedCounter].text = that.textTyped[textTypedCounter].text.substring(0,max(0,that.textTyped[textTypedCounter].text.length - 1));\n }\n // remove objects if there's no characters\n if (that.textTyped[textTypedCounter].text.length == 0){\n textTypedCounter--;\n if (textTypedCounter < 0){\n console.log('nothing left');\n textTypedCounter = 0;\n } else {\n that.textTyped.pop();\n }\n }\n };\n\n // add lines\n this.addLines = function(){\n that.textTyped.push(that.addText(''));\n that.lineCount++;\n };\n\n // add characters\n this.addCharacters = function(_key){\n if (that[_key.toUpperCase()]){\n that.textTyped[that.lineCount].text += _key;\n } else {\n console.log('not a letter');\n }\n };\n\n /*\n Call functions in render\n */\n\n this.render = function(){\n if (that.paths.length > 0){\n that.paths.forEach(function(d){\n that[d.letter](d.x, d.y);\n });\n }\n };\n\n /*\n Letter Definitions\n */\n\n // space\n this[' '] = function(){\n // nothing\n };\n\n this.A = function(x, y){\n push();\n translate(x, y);\n this.diagonalToMiddle(that.letterWidth / 2,0, 1);\n this.diagonalToMiddle(-that.letterWidth / 2,0, -1);\n this.halfCrossBar(that.letterWidth / 4, that.letterHeight / 2);\n pop();\n };\n\n this.B = function(x, y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.halfBowl(0,0, -1);\n this.halfBowl(0,that.letterHeight / 2, -1);\n pop();\n };\n this.C = function(x, y){\n push();\n translate(x, y);\n this.fullBowl(0, 0, 1);\n pop();\n };\n\n this.D = function(x, y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.fullBowl(0, 0, -1);\n pop();\n };\n\n this.E = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.crossBar(0,0);\n this.crossBar(0,that.letterHeight / 2);\n this.crossBar(0,that.letterHeight);\n pop();\n };\n\n this.F = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.crossBar(0,0);\n this.crossBar(0,that.letterHeight / 2);\n pop();\n };\n\n this.G = function(x,y){\n push();\n translate(x, y);\n this.fullBowl(0, 0, 1);\n this.halfStem(that.letterWidth,that.letterHeight / 2);\n this.halfCrossBar(that.letterWidth / 2, that.letterHeight / 2);\n pop();\n };\n\n this.H = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.crossBar(0, that.letterHeight / 2);\n this.fullStem(that.letterWidth,0);\n pop();\n };\n\n this.I = function(x,y){\n push();\n translate(x, y);\n this.fullStem(that.letterWidth / 2,0);\n pop();\n };\n\n this.J = function(x,y){\n push();\n translate(x, y);\n this.jCurve(0, 0);\n pop();\n };\n\n this.K = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.halfDiagonalLeg(0, that.letterHeight / 2, 1);\n this.halfDiagonalLeg(0, that.letterHeight / 2, -1);\n pop();\n };\n\n this.L = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.crossBar(0, that.letterHeight);\n pop();\n };\n\n this.M = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.fullStem(that.letterWidth,0);\n this.diagonalToMiddle(0, 0, 1);\n this.diagonalToMiddle(0, 0, -1);\n pop();\n };\n\n this.N = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.fullStem(that.letterWidth,0);\n this.diagonalToEnd(0, 0, -1);\n pop();\n };\n\n this.O = function(x,y){\n push();\n translate(x, y);\n this.letterO(0, 0);\n pop();\n };\n\n this.P = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.halfBowl(0,0, -1);\n pop();\n };\n\n this.Q = function(x,y){\n push();\n translate(x, y);\n this.letterO(0,0);\n this.halfDiagonalArm(that.letterWidth / 2,that.letterHeight / 2, -1);\n pop();\n };\n\n this.R = function(x,y){\n push();\n translate(x, y);\n this.fullStem(0,0);\n this.halfBowl(0,0, -1);\n this.halfDiagonalLeg(0, that.letterHeight / 2, -1);\n pop();\n };\n\n this.S = function(x,y){\n push();\n translate(x, y);\n // noFill();\n this.sCurve(0,0);\n pop();\n };\n\n this.T = function(x,y){\n push();\n translate(x, y);\n this.fullStem(that.letterWidth / 2,0);\n this.crossBar(0,0);\n pop();\n };\n\n this.U = function(x,y){\n push();\n translate(x, y);\n this.uCurve(0,0);\n pop();\n };\n\n this.V = function(x,y){\n push();\n translate(x, y);\n this.diagonalToMiddle(0, 0, 1);\n this.diagonalToMiddle(0, 0, -1);\n pop();\n };\n\n this.W = function(x,y){\n push();\n translate(x, y);\n this.diagonalToQuarter(0, 0, 1);\n this.diagonalToQuarter(0, 0, -1);\n\n this.diagonalToQuarter(that.letterWidth / 2, 0, 1);\n this.diagonalToQuarter(that.letterWidth / 2, 0, -1);\n pop();\n };\n\n this.X = function(x, y){\n push();\n translate(x ,y);\n this.diagonalToEnd(0, 0, -1);\n this.diagonalToEnd(0, 0, 1);\n pop();\n };\n\n this.Y = function(x,y){\n push();\n translate(x, y);\n this.halfStem(that.letterWidth / 2, that.letterHeight / 2);\n this.halfDiagonalArm(0,0, 1);\n this.halfDiagonalArm(0,0, -1);\n pop();\n };\n\n this.Z = function(x,y){\n push();\n translate(x, y);\n this.diagonalToEnd(0,0,1);\n this.crossBar(0,0);\n this.crossBar(0,that.letterHeight);\n pop();\n };\n\n /*\n Component Definitions\n */\n this.sCurve = function(x1,y1){\n push();\n translate(x1, y1);\n\n this.static = function(){\n noFill();\n curve(that.letterWidth, -that.letterHeight * 1.5, 0, that.letterHeight * 0.25, that.letterWidth, that.letterHeight * 0.75, that.letterWidth - that.letterWidth, that.letterHeight * 0.75 + that.letterHeight * 1.5);\n arc(that.letterWidth / 2, that.letterHeight * 0.25, that.letterWidth, that.letterHeight / 2, PI, 0);\n arc(that.letterWidth / 2, that.letterHeight * 0.75, that.letterWidth, that.letterHeight / 2, 0, PI);\n };\n\n this.dynamic = function(){\n this.arcFromToInSteps(that.letterWidth / 2, that.letterHeight * 0.25, that.letterWidth / 2,that.letterWidth / 2, -PI, 0, that.aniSteps);\n this.arcFromToInSteps(that.letterWidth / 2, that.letterHeight * 0.75, that.letterWidth / 2,that.letterWidth / 2, PI, 0, that.aniSteps);\n this.curveFromToInSteps(that.letterWidth, -that.letterHeight * 1.5, 0, that.letterHeight * 0.25, that.letterWidth, that.letterHeight * 0.75, that.letterWidth - that.letterWidth, that.letterHeight * 0.75 + that.letterHeight * 1.5,that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.uCurve = function(x1, y1){\n push();\n translate(x1, y1);\n\n this.static = function(){\n noFill();\n arc(that.letterWidth / 2, 0, that.letterWidth, that.letterHeight * 2, 0, PI);\n };\n this.dynamic = function(){\n this.arcFromToInSteps(that.letterWidth / 2, 0, that.letterWidth / 2, that.letterHeight, 0, PI, that.aniSteps + 10);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.jCurve = function(x1, y1){\n push();\n translate(x1, y1);\n this.static = function(){\n noFill();\n bezier(that.letterWidth, 0, that.letterWidth + 10, that.letterHeight * 1.5, 0, that.letterHeight, 0, that.letterHeight * 0.75);\n };\n this.dynamic = function(){\n this.bezierFromToInSteps(that.letterWidth, 0, that.letterWidth + 10, that.letterHeight * 1.5, 0, that.letterHeight, 0, that.letterHeight * 0.75, that.aniSteps + 10);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.letterO = function(x1, y1){\n push();\n translate(x1, y1);\n\n this.static = function(){\n noFill();\n ellipse(that.letterWidth / 2, that.letterHeight / 2, that.letterWidth, that.letterHeight);\n };\n this.dynamic = function(){\n this.arcFromToInSteps(that.letterWidth / 2, that.letterHeight / 2, that.letterWidth / 2, that.letterHeight / 2, PI, -PI, that.aniSteps + 10);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.halfDiagonalArm = function(x1, y1, direction){\n push();\n translate(x1, y1);\n\n this.static = function(){\n noFill();\n if (direction == 1){\n line(that.letterWidth / 2, that.letterHeight / 2, that.letterWidth, 0);\n }\n if (direction == -1){\n line(0, 0, that.letterWidth / 2, that.letterHeight / 2);\n }\n };\n this.dynamic = function(){\n if (direction == 1){\n this.lineFromToInSteps(that.letterWidth / 2, that.letterHeight / 2, that.letterWidth, 0, that.aniSteps);\n }\n if (direction == -1){\n this.lineFromToInSteps(0, 0, that.letterWidth / 2, that.letterHeight / 2, that.aniSteps);\n }\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.diagonalToEnd = function(x1, y1, direction){\n push();\n translate(x1, y1);\n\n this.static = function(){\n noFill();\n if (direction == 1){\n line(that.letterWidth, 0, 0, that.letterHeight);\n }\n if (direction == -1){\n line(0, 0, that.letterWidth, that.letterHeight);\n }\n };\n this.dynamic = function(){\n if (direction == 1){\n this.lineFromToInSteps(that.letterWidth, 0, 0, that.letterHeight, that.aniSteps);\n }\n if (direction == -1){\n this.lineFromToInSteps(0, 0, that.letterWidth, that.letterHeight, that.aniSteps);\n }\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.diagonalToQuarter = function(x1, y1, direction){\n push();\n translate(x1, y1);\n this.static = function(){\n noFill();\n if (direction == 1){\n line(0, 0, that.letterWidth / 4 , that.letterHeight);\n }\n if (direction == -1){\n line(that.letterWidth / 4, that.letterHeight, that.letterWidth / 2, 0);\n }\n };\n this.dynamic = function(){\n if (direction == 1){\n this.lineFromToInSteps(0, 0, that.letterWidth / 4 , that.letterHeight, that.aniSteps);\n }\n if (direction == -1){\n this.lineFromToInSteps(that.letterWidth / 4, that.letterHeight, that.letterWidth / 2, 0, that.aniSteps);\n }\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.diagonalToMiddle = function(x1, y1, direction){\n push();\n translate(x1, y1);\n this.static = function(){\n noFill();\n if (direction == 1){\n line(0, 0, that.letterWidth / 2 , that.letterHeight);\n }\n if (direction == -1){\n line(that.letterWidth / 2, that.letterHeight, that.letterWidth, 0);\n }\n };\n this.dynamic = function(){\n if (direction == 1){\n this.lineFromToInSteps(0, 0, that.letterWidth / 2 , that.letterHeight, that.aniSteps);\n }\n if (direction == -1){\n this.lineFromToInSteps(that.letterWidth / 2, that.letterHeight, that.letterWidth, 0, that.aniSteps);\n }\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.halfDiagonalLeg = function(x1, y1, direction){\n push();\n translate(x1, y1);\n var endpoint;\n if (direction == 1){\n endpoint = -that.letterHeight / 2;\n }\n if (direction == -1){\n endpoint = that.letterHeight / 2;\n }\n\n this.static = function(){\n noFill();\n line(0, 0, that.letterHeight / 2, endpoint);\n };\n this.dynamic = function(){\n this.lineFromToInSteps(0, 0, that.letterHeight / 2, endpoint, that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.fullStem = function(x1, y1){\n push();\n translate(x1,y1);\n this.static = function(){\n noFill();\n line(0, 0, 0, that.letterHeight);\n };\n this.dynamic = function(){\n this.lineFromToInSteps(0, 0, 0, that.letterHeight, that.aniSteps);\n };\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.halfStem = function(x1, y1){\n push();\n translate(x1,y1);\n this.static = function(){\n noFill();\n line(0, 0, 0, that.letterHeight / 2);\n };\n this.dynamic = function(){\n this.lineFromToInSteps(0, 0, 0, that.letterHeight / 2, that.aniSteps);\n };\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.halfCrossBar = function(x1, y1){\n push();\n translate(x1,y1);\n this.static = function(){\n noFill();\n line(0, 0, that.letterWidth / 2, 0);\n };\n this.dynamic = function(){\n this.lineFromToInSteps(0, 0, that.letterWidth / 2, 0, that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.halfBowl = function(x1, y1, direction){\n var cPoint = that.letterWidth * 8;\n noFill();\n push();\n if (direction === 1){\n translate(x1 + that.letterWidth,y1);\n }\n if (direction === -1){\n translate(x1,y1);\n }\n this.static = function(){\n noFill();\n curve(cPoint * direction, 0, 0,0,0,that.letterHeight / 2,cPoint * direction,that.letterHeight / 2);\n };\n this.dynamic = function(){\n this.curveFromToInSteps(cPoint * direction, 0, 0,0,0,that.letterHeight / 2,cPoint * direction,that.letterHeight / 2,that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.fullBowl = function(x1, y1, direction){\n var cPoint = that.letterWidth * 8;\n noFill();\n push();\n if (direction === 1){\n translate(x1 + that.letterWidth,y1);\n }\n if (direction === -1){\n translate(x1,y1);\n }\n this.static = function(){\n noFill();\n curve(cPoint * direction, 0, 0,0,0,that.letterHeight, cPoint * direction,that.letterHeight);\n };\n this.dynamic = function(){\n this.curveFromToInSteps(cPoint * direction, 0, 0,0,0,that.letterHeight, cPoint * direction,that.letterHeight, that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n this.crossBar = function(x1, y1){\n push();\n translate(x1, y1);\n this.static = function(){\n noFill();\n line(0, 0, that.letterWidth, 0);\n };\n this.dynamic = function(){\n this.lineFromToInSteps(0, 0, that.letterWidth, 0, that.aniSteps);\n };\n\n if (that.drawMode === 1){\n this.static();\n }\n if (that.drawMode === 2){\n this.dynamic();\n }\n if (that.drawMode === 3){\n this.static();\n this.dynamic();\n }\n pop();\n };\n\n /*\n Animation functions\n */\n\n this.lineFromToInSteps = function(x1, y1, x2, y2, stepCount) {\n var aniIndex = frameCount % (stepCount + 1);\n var ratio = aniIndex / stepCount;\n var posX = lerp(x1, x2, ratio);\n var posY = lerp(y1, y2, ratio);\n fill(65, 105, 185);\n rectMode(CENTER);\n if (that.style == 1){\n rect(posX, posY, 10, 10);\n } else if (that.style == 2){\n ellipse(posX, posY, 10, 10);\n } else {\n ellipse(posX, posY, 10, 10);\n }\n\n };\n\n this.curveFromToInSteps = function(a1, a2, b1, b2, c1, c2, d1, d2, stepCount){\n var points = [];\n for (var i = 0; i <= stepCount; i++) {\n var t = i / stepCount;\n var cx = curvePoint(a1, b1, c1, d1, t);\n var cy = curvePoint(a2, b2, c2, d2, t);\n points.push({x: cx, y: cy});\n }\n var aniIndex = frameCount % (stepCount);\n var ratio = aniIndex / stepCount;\n var posX = lerp(points[aniIndex].x, points[aniIndex + 1].x, ratio);\n var posY = lerp(points[aniIndex].y, points[aniIndex + 1].y, ratio);\n fill(65, 105, 185);\n rectMode(CENTER);\n if (that.style == 1){\n rect(posX, posY, 10, 10);\n } else if (that.style == 2){\n ellipse(posX, posY, 10, 10);\n } else {\n ellipse(posX, posY, 10, 10);\n }\n\n };\n\n this.bezierFromToInSteps = function(a1, a2, b1, b2, c1, c2, d1, d2, stepCount){\n var points = [];\n for (var i = 0; i <= stepCount; i++) {\n var t = i / stepCount;\n var cx = bezierPoint(a1, b1, c1, d1, t);\n var cy = bezierPoint(a2, b2, c2, d2, t);\n points.push({x: cx, y: cy});\n }\n var aniIndex = frameCount % (stepCount);\n var ratio = aniIndex / stepCount;\n var posX = lerp(points[aniIndex].x, points[aniIndex + 1].x, ratio);\n var posY = lerp(points[aniIndex].y, points[aniIndex + 1].y, ratio);\n fill(65, 105, 185);\n rectMode(CENTER);\n if (that.style == 1){\n rect(posX, posY, 10, 10);\n } else if (that.style == 2){\n ellipse(posX, posY, 10, 10);\n } else {\n ellipse(posX, posY, 10, 10);\n }\n\n };\n\n this.arcFromToInSteps = function(x, y, radiusWidth, radiusHeight, a1, a2, stepCount) {\n var aniIndex = frameCount % (stepCount + 1);\n var ratio = aniIndex / stepCount;\n var angle = lerp(a1, a2, ratio);\n var posX = x + cos(angle) * radiusWidth;\n var posY = y + sin(angle) * radiusHeight;\n fill(65, 105, 185);\n rectMode(CENTER);\n if (that.style == 1){\n rect(posX, posY, 10, 10);\n } else if (that.style == 2){\n ellipse(posX, posY, 10, 10);\n } else {\n ellipse(posX, posY, 10, 10);\n }\n\n };\n\n} // end AniType() object", "function MyApp_HighlightAllOccurencesOfStringForElement(element, keyword) {\n\tif (element) {\n\t\tif (element.nodeType == 3) { // Text node\n\t\t\twhile (true) {\n\n\t\t\t\tvar value = element.nodeValue; // Search for keyword in text node\n\t\t\t\t//\n\n\t\t\t\tvar idx = value.toLowerCase().indexOf(keyword);\n\n\t\t\t\t////////////////////////////////////////////////////////////////////////////////////////////////////////////////\n\t\t\t\tif (idx < 0) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tvar symbols = \"!$%^&*()_+|~-=`{}[]:\\\";'<>?,./،:»«،؛\";\n\n\t\t\t\t//////////////////////////////////////////////////\n\n\t\t\t\tvar nextChar = value.substr(idx + keyword.length, 1);\n\t\t\t\tvar prevChar = value.substring(idx - 1, idx);\n\n\t\t\t\tif((nextChar == \" \" || nextChar == \"\\n\" || nextChar == \"\\t\" || symbols.indexOf(nextChar) != -1)\n\t\t\t\t\t\t&& (prevChar == \" \" || prevChar == \"\\n\" || prevChar == \"\\t\" || symbols.indexOf(prevChar) != -1))\n\t\t\t\t\t{\n\n\t\t\t\t\tvar span = document.createElement(\"span\");\n\t\t\t\t\tspan.className = \"highlight\";\n\t\t\t\t\tspan.style.backgroundColor = \"yellow\";\n\t\t\t\t\tspan.style.color = \"black\";\n\n\t\t\t\t\tvar text = document.createTextNode(\n\t\t\t\t\t\t\tvalue.substr(idx, keyword.length));\n\n\t\t\t\t\tspan.appendChild(text);\n\n\t\t\t\t\tvar rightText = document.createTextNode(\n\t\t\t\t\t\t\tvalue.substr(idx + keyword.length));\n\t\t\t\t\telement.deleteData(idx, value.length - idx);\n\n\t\t\t\t\tvar next = element.nextSibling;\n\n\t\t\t\t\telement.parentNode.insertBefore(rightText, next);\n\t\t\t\t\telement.parentNode.insertBefore(span, rightText);\n\n\t\t\t\t\tvar leftNeighText = element.nodeValue.substr(\n\t\t\t\t\t\t\telement.length - neighSize, neighSize);\n\t\t\t\t\tvar rightNeighText = rightText.nodeValue.substr(0,\n\t\t\t\t\t\t\tneighSize);\n\n\t\t\t\t\telement = rightText;\n\n\t\t\t\t\tleftNeighText = leftNeighText.replace(\"\\n\", \" \");\n\t\t\t\t\tif (leftNeighText.charAt(leftNeighText.length) == \" \") {\n\t\t\t\t\t\tleftNeighText = leftNeighText.trim();\n\t\t\t\t\t\tleftNeighText = leftNeighText + \" \";\n\t\t\t\t\t}\n\n\t\t\t\t\trightNeighText = rightNeighText.replace(\"\\n\", \" \");\n\t\t\t\t\tif (rightNeighText.charAt(0) == \" \") {\n\t\t\t\t\t\trightNeighText = rightNeighText.trim();\n\t\t\t\t\t\trightNeighText = \" \" + rightNeighText;\n\t\t\t\t\t}\n\t\t\t\t\tleftNeighText = leftNeighText.substring(\n\t\t\t\t\t\t\tleftNeighText.indexOf(\" \"), leftNeighText.length);\n\t\t\t\t\trightNeighText = rightNeighText.substring(0,\n\t\t\t\t\t\t\trightNeighText.lastIndexOf(\" \"));\n\n\n\t\t\t\t\tvar elementPos = getPos(span);\n\n\n\t\t\t\t\tresults += getPos(span).y+ \"|\"\n\t\t\t\t\t\t\t+ (leftNeighText + text.nodeValue + rightNeighText)\n\t\t\t\t\t\t\t+ \";\";\n\n\t\t\t\t\tidx++;\n\n\t\t\t\t\tresults;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else if (element.nodeType == 1) { // Element node\n\t\t\tif (element.style.display != \"none\"\n\t\t\t\t\t&& element.nodeName.toLowerCase() != 'select') {\n\t\t\t\tfor (var i = element.childNodes.length - 1; i >= 0; i--) {\n\t\t\t\t\tMyApp_HighlightAllOccurencesOfStringForElement(\n\t\t\t\t\t\t\telement.childNodes[i], keyword);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "showMatchedLetter(letter) {\r\n const matchLetterElement = document.querySelectorAll('.letter');\r\n matchLetterElement.forEach(letterElement =>{\r\n // console.log(letterElement);\r\n // console.log(letterElement.textContent);\r\n if(letterElement.innerHTML === letter.textContent){\r\n letterElement.classList.remove('hide');\r\n console.log(letterElement);\r\n letterElement.classList.add('show');\r\n }\r\n });\r\n }", "function js_highlight() \n{\n for (var i=0; i<bold_Tags.length; i++)\n { \n bold_Tags[i].style.color = \"green\";\n }\n}", "function checkLetter(arr) { \n let buttonClicked = arr;\n let phraseLetters = document.getElementsByClassName('letter');\n let letterMatched = null;\n\n for (let i = 0; i < phraseLetters.length; i += 1) {\n if (buttonClicked.toUpperCase() === phraseLetters[i].textContent.toUpperCase()) { \n phraseLetters[i].className += ' show';\n letterMatched = buttonClicked;\n }\n }\n\n return letterMatched;\n}", "showMatchedLetter(e) {\n \t\t$('li').parent().children(`.${this.letterGuess}`).removeClass('hide').addClass('show');\n\n\t}", "function createSpan() {\n for (var i = 0; i < chosenWord.length; i++) {\n if (!/[a-zA-Z0-9]/.test(chosenWord[i])) {\n var whiteSpace = $(\"<span>\").addClass(\"letter\").html(chosenWord[i]);\n if (/\\s+/.test(chosenWord[i])) {\n $(\"#hang-word\").append(whiteSpace);\n $(\"#hang-word\").append($(\"<br>\"));\n } else {\n $(\"#hang-word\").append(whiteSpace);\n }\n } else {\n var letter = document.createElement(\"span\");\n letter.innerHTML = `_`;\n letter.className = \"letter\";\n letter.id = `letter${i}`;\n \n $(\"#hang-word\").append(letter);\n }\n }\n $(\"#hint-img\").attr(\"src\", chosenImg).show();\n}", "function highlight_search(name) {\n var new_search = indexMap[\"search\"];\n var new_split = name.split(new_search);\n var new_name = \"\";\n var html_name = \"\";\n\n for (var l = 0; l < new_split.length; l++) {\n new_name += new_split[l];\n html_name += new_split[l];\n if (name.indexOf(new_name + new_search) != -1) {\n new_name += new_search;\n html_name += \"<font class='bg-success'>\"+new_search+\"</font>\";\n }\n }\n\n return html_name;\n}", "function addChar(char) {\n for (var index = 0; index < chosenWord.length; index++) {\n if (chosenWord[index] === char) {\n blankWord = (blankWord.replaceAt(index, char));\n SpaceInWord();\n console.log(spacedWord);\n countUp++;\n $(\"#theWord\").text(spacedWord);\n //document.getElementById(\"animeImage\").src = \"\";\n }\n }\n }" ]
[ "0.69809395", "0.65275204", "0.6464697", "0.64588654", "0.6416339", "0.6395215", "0.63820565", "0.63819623", "0.6255993", "0.620108", "0.6179255", "0.6098701", "0.60863984", "0.6066258", "0.5990375", "0.59819627", "0.5973279", "0.59144324", "0.58898747", "0.58893126", "0.5886177", "0.58598125", "0.5857394", "0.5844338", "0.58377135", "0.58345747", "0.58253175", "0.581541", "0.58095294", "0.58090943", "0.5778725", "0.5778725", "0.5773695", "0.57643765", "0.57509255", "0.57325405", "0.57299316", "0.57246745", "0.5723058", "0.57202584", "0.5715259", "0.5701761", "0.569707", "0.56954074", "0.5693151", "0.5692171", "0.56857634", "0.56852645", "0.56852645", "0.56852645", "0.5669395", "0.56611425", "0.5654134", "0.5652592", "0.5649048", "0.5646701", "0.5644915", "0.56340444", "0.56310105", "0.5617707", "0.5615877", "0.56144345", "0.5613515", "0.5601185", "0.55946076", "0.55925876", "0.55917877", "0.55868787", "0.5584246", "0.55768365", "0.5565095", "0.556358", "0.55572844", "0.55550593", "0.5550546", "0.55461216", "0.55446416", "0.5537556", "0.55312824", "0.55213183", "0.5518529", "0.5518441", "0.5512444", "0.5506541", "0.55060256", "0.55058646", "0.5501912", "0.5497391", "0.5487294", "0.5473893", "0.5470685", "0.546488", "0.54582626", "0.544494", "0.54375154", "0.543573", "0.5435229", "0.54333353", "0.5428792" ]
0.8016309
1
clear all letter highlighting
function unhighlightAll() { for (var row=0; row<cipher[which].length; row++) { for (var col=0; col<cipher[which][row].length; col++) { u(row+"_"+col); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function clearAll() {\n if (activeHighlight && activeHighlight.applied) {\n activeHighlight.cleanup();\n }\n activeHighlight = null;\n }", "clearHighlight() {\n\n //TODO - your code goes here -\n }", "function clearAllHighlighted() {\n var canvas = document.getElementById('highlight');\n var context = canvas.getContext('2d');\n \n context.clearRect(0, 0, canvas.width, canvas.height);\n // Move the highlight canvas its original z-position (0)\n document.getElementById('highlight').style.zIndex = \"0\";\n}", "unhighlightAll() {\n if (!this.tf.highlightKeywords) {\n return;\n }\n\n this.unhighlight(null, this.highlightCssClass);\n }", "clearHighlights() {\n\t\tvar t = this;\n\t\tvar len = t.getLength();\n\t\tfor (var x = 0; x < len; x++) {\n\t\t\tt.getRow(x).classList.remove(\"highlight\");\n\t\t}\n\t}", "resetHighlighted() {\n this.highlights.forEach((h) => h.remove());\n this.highlights.length = 0; // Clear\n }", "function resetHighlight(e) {\n\tciycle.resetStyle(e.target);\n}", "function clearHighlightsOnPage()\n{\n unhighlight(document.getElementsByTagName('body')[0], \"ffff00\");\n highlightedPage = false;\n lastText = \"\";\n}", "function clearHighlights() {\n $(getContainer()).find('.' + className).each(function() {\n var $wrapped = $(this);\n $wrapped.replaceWith($wrapped.text());\n });\n }", "function ResetHighlightedKws() {\n for (var i = 0; i < HighlightedKws.length; i++) {\n var highlightedkw = HighlightedKws[i];\n highlightedkw.setTextFill(highlightedkw.origColor);\n var layer = highlightedkw.parent;\n layer.draw();\n }\n HighlightedKws = [];\n }", "function clear(){\r\n\tmessages.push({command:\"clearHighlights\"});\r\n\tgetCurrentTabAndSendMessages();\r\n}", "function clearSelection()\n{\n if (window.getSelection) {window.getSelection().removeAllRanges();}\n else if (document.selection) {document.selection.empty();}\n}", "clearSelection() {\n this.selectionStart = undefined;\n this.selectionEnd = undefined;\n this.isSelectAllActive = false;\n this.selectionStartLength = 0;\n }", "ClearGraphicHighlight() {\n this.highlight.remove();\n this.highlight = null;\n }", "function unhighlight(){\n insertWords();\n //added to reset value variable -- alec;\n //value=\"\";\n //userWord=\"\";\n}", "function ClearTextSelection() {\n\t//console.log('Clear text selection.');\n\tif ( document.selection ) {\n //console.log('document.selection'); \n\t\tdocument.selection.empty();\n\t} else if ( window.getSelection ) {\n\t\t//console.log('window.getSelection');\n\t\twindow.getSelection().removeAllRanges();\n\t}\n} // END ClearTextSelection.", "function unHighlight() {\r\n var sel = window.getSelection && window.getSelection();\r\n if (sel && sel.rangeCount == 0 && savedRange != null) {\r\n sel.addRange(savedRange);\r\n }\r\n if (sel && sel.rangeCount > 0) {\r\n // Get location and text info\r\n let range = sel.getRangeAt(0);\r\n console.log(range)\r\n let node = document.createElement('p')\r\n node.setAttribute('class', 'unhighlight')\r\n let selText = range.cloneContents();\r\n node.appendChild(selText);\r\n let markedList = node.getElementsByTagName('mark');\r\n for (let i = 0; i < markedList.length; i++) {\r\n markedList[i].outerHTML = markedList[i].innerHTML;\r\n }\r\n\r\n range.deleteContents();\r\n range.insertNode(node);\r\n // Remove the tags from inserted node\r\n var unHiteLiteList = document.getElementsByClassName('unhighlight');\r\n\r\n for (let i = 0 ; i < unHiteLiteList.length; i ++) {\r\n var parent = unHiteLiteList[i].parentNode;\r\n while (unHiteLiteList[i].firstChild) {\r\n parent.insertBefore(unHiteLiteList[i].firstChild, unHiteLiteList[i]);\r\n }\r\n parent.removeChild(unHiteLiteList[i]);\r\n }\r\n // range.selectNodeContents(selText); \r\n saveCurrentState();\r\n }\r\n }", "deselectAll() {\n if (document.selection) {\n document.selection.empty();\n } else if (window.getSelection) {\n window.getSelection().removeAllRanges();\n }\n }", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n }", "function clearHighlighting()\n{\n for(var i = 0; i < 3; i++)\n {\n for(var j = 0; j < 3; j++)\n {\n document.getElementById(\"cell\" + i + \"x\" + j).setAttributeNS(null, \"fill-opacity\", 0);\n }\n }\n}", "function resetHighlight_GCQ(e) {\nAreas_ECQ_GCQ.resetStyle(e.target);\ninfo.update();\n}", "function resetSelection(){\n\t$(\".document-list, #scrapPaperDiv, .scrap-keyword\").find(\"span\").each(function( index ){\n\t\tif($(this).hasClass('ent_highlighted')){\n\t\t\t$(this).removeClass('ent_highlighted');\n\t\t}\n\t\t\n\t\tif($(this).hasClass('highlighted')){\n\t\t\t$(this).parent().unhighlight({className:$(this).text().split(\" \")[0]});\t\t\n\t\t}\n\t});\n\tqueue = [];\n}", "function resetHighlight(e) {\n\tgeojson.resetStyle(e.target);\n}", "function resetHighlight(e) {\n\t\t\tgeojson.resetStyle(e.target);\n\t\t}", "clearSelection() {\n this._clearSelection();\n }", "function resetHighlight_eecq(e) {\neecq.resetStyle(e.target);\ninfo.update();\n}", "function clearSelection () {\n if (document.selection) {\n document.selection.empty();\n } else if (window.getSelection) {\n window.getSelection().removeAllRanges();\n }\n}", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n info.update();\n }", "function js_unHighlight()\n{\n for (var i=0; i<bold_Tags.length; i++) \n {\n bold_Tags[i].style.color = \"black\";\n }\n}", "function clearHighlight() {\n document.getElementById(\"flyLynchburg\").style.border = unhighlight;\n document.getElementById(\"flyAlexandria\").style.border = unhighlight;\n document.getElementById(\"flyHenrico\").style.border = unhighlight;\n \n }", "function resetHighlight(e) {\n\tcountyLayer.resetStyle(e.target)\n}", "clearHighlight() {\n\n //TODO - Your code goes here - \n let icon = d3.select('.icon-holder').selectAll('text');\n icon.remove();\n let values = d3.select('.value-holder').selectAll('text');\n values.remove();\n let name = d3.select('.name-holder').selectAll('text');\n name.remove();\n\n }", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n info.update();\n }", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n info.update();\n}", "function SearchDoc_RemoveAllHighlights() {\n SearchDoc_SearchResultCount = 0;\n SearchDoc_RemoveAllHighlightsForElement(document.body);\n}", "function clearAllHighlightedAceLines (aceEditor) {\n var session = aceEditor.getSession();\n for (var hlClass in lastHighlightMarkerIds) {\n session.removeMarker(lastHighlightMarkerIds[hlClass]);\n }\n lastHighlightMarkerIds = {};\n}", "function resetHighlight(e) {\n // console.log(\"resetHighlight\");\n CapaAsentamientos.resetStyle(e.target);\n var layer = e.target;\n //layer.closePopup();\n // info.update(); //controla la info de la caja\n}", "function reset() {\n initializeCharacters();\n }", "function clearSelection() {\n if (window.getSelection) {\n if (window.getSelection().empty) { // Chrome\n window.getSelection().empty();\n } else if (window.getSelection().removeAllRanges) { // Firefox\n window.getSelection().removeAllRanges();\n }\n } else if (document.selection) { // IE?\n document.selection.empty();\n }\n }", "function _removeHighlights() {\n\t\t$(\".find-highlight\").contents().unwrap();\n\t}", "function removeTextSelections() {\n if (document.selection) document.selection.empty();\n else if (window.getSelection) window.getSelection().removeAllRanges();\n}", "function resetMouseHighlighter() {\n const prevTarget = document.querySelector(\".c8a11y-mouse-target\");\n\n if (prevTarget) {\n bodyEl.removeChild(prevTarget);\n }\n }", "function highlight_clear(locations) {\n \"use strict\";\n var i, selector;\n for (i = 0; i < locations.length; i += 1) {\n selector = $('div[class=\"' + locations[i].line + '\"]', window.parent.frames[0].document);\n selector.css('background-color', 'inherit');\n selector.removeAttr('title');\n }\n}", "function clearHighlights() {\n $('li.regionLink').removeClass('selected');\n }", "function clearhighlight() {\r\n var layers = webMap._layers;\r\n for (var i = 0; i < layers.length; i++) {\r\n if (layers[i].active) {\r\n layers[i].unHighlightAllObjects();\r\n }\r\n }\r\n cesiumViewer.selectedEntity = undefined;\r\n}", "function resetHighlight(e) {\n\te.target.setStyle({\n\t\tweight: 1.5,\n\t\tcolor: '#fff'\n\t});\n\tinfo.update();\n}", "clearHighlight() {\n // ++++++++ BEGIN CUT +++++++++++\n d3.select('#country-detail').style('opacity', 0);\n // ++++++++ END CUT +++++++++++\n }", "function clearPreviousSelection()\n {\n if ($.browser.msie) \n {\n document.selection.empty();\n }\n else\n {\n window.getSelection().removeAllRanges();\n }\n }", "function unHighlight() {\n if (window.getSelection) {\n var selection = window.getSelection();\n if (selection.rangeCount) {\n\n var highlightNode = document.createElement(\"span\");\n highlightNode.setAttribute(\"id\", \"highlighted\");\n highlightNode.setAttribute(\"style\", \"background-color:#FFFF00\");\n\n var range = selection.getRangeAt(0).cloneRange();\n var node = $(range.commonAncestorContainer);\n\n var previousRange = document.createRange();\n previousRange.setStart(range.startContainer, 0);\n previousRange.setEnd(range.startContainer, range.startOffset);\n\n var nextRange = document.createRange();\n nextRange.setStart(range.endContainer, range.endOffset);\n nextRange.setEnd(range.endContainer, 0);\n\n node.unwrap();\n previousRange.surroundContents(highlightNode);\n nextRange.surroundContents(highlightNode);\n\n selection.removeAllRanges();\n selection.addRange(previousRange);\n selection.addRange(nextRange);\n }\n }\n}", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n //FIXME: Info hasn't been defined\n \t//info.update();\n }", "function MyApp_RemoveAllHighlights() {\nMyApp_RemoveAllHighlightsForElement(document.body);\n}", "function resetHighlight(e){\n\tBuildings.resetStyle(e.target); // Resets the building styles when the user's mouse is not on it to its original style (buildingStyle)\n}", "function rem(){\n $(\"#b1\").removeClass(\"Highlight\") ;\n $(\"#b2\").removeClass(\"Highlight\") ;\n $(\"#b3\").removeClass(\"Highlight\") ;\n $(\"#b4\").removeClass(\"Highlight\") ;\n }", "function DevFeed_RemoveAllHighlights() {\n DevFeed_SearchResultCount = 0;\n DevFeed_RemoveAllHighlightsForElement(document.body);\n}", "function unselectAll() {\n resetAllStrokes();\n resetAllBackgrounds();\n selected_robots = [];\n}", "reset() {\n let i;\n let target;\n for (i = 0; i < this.targetStartIndex; i++) {\n target = this.targets[i];\n target.textNode.textContent = target.textContent;\n target.isRemoved = false;\n }\n for (i = this.targetStartIndex; i < this.targets.length; i++) {\n target = this.targets[i];\n target.textNode.textContent = \"\";\n target.isRemoved = false;\n }\n this.cursor.target = this.targets[this.targetStartIndex];\n }", "function clearSelections() {\r\n var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\r\n if (isFirefox) {\r\n document.selection.empty();\r\n } else {\r\n window.getSelection().removeAllRanges();\r\n }\r\n }", "function unrender(){\n var textmap = textMap,\n i = textmap.length - 1,\n entry, Node, Parent;\n // 1st pass, remove highlights\n while (i-- > 0) {\n entry = textmap[i];\n Node = entry.n.parentNode;\n if (Node && Node.className && Node.className === 'hi') {\n Node.parentNode.replaceChild(entry.n, Node);\n }\n }\n // 2nd pass, remove highlight parents\n i = textmap.length - 1;\n while (i-- > 0) {\n entry = textmap[i];\n Parent = entry.n.parentNode;\n if (Node && Node.className && Parent.className === '-parent') {\n while (Parent.hasChildNodes()) {\n Parent.parentNode.insertBefore(Parent.firstChild, Parent);\n }\n Parent.parentNode.removeChild(Parent);\n }\n }\n}", "function clearGlyphs() {\n var curGlyphs = [null, null, null, null, null, null];\n changeUrlGlyphs(curGlyphs);\n\n return curGlyphs;\n }", "function resetHighlightUNEMP(e) {\n geojson_unempl.resetStyle(e.target);\n info.update();\n}", "unhighlightWord(word, ayah) {\n if (word.char_type === \"word\") {\n let highlightedWords = this.state.highlightedWords;\n delete highlightedWords[word.id];\n this.setState({ highlightedWords });\n } else if (word.char_type === \"end\") {\n //if user presses on an end of ayah, we highlight that entire ayah\n let highlightedAyahs = this.state.highlightedAyahs;\n let ayahKey = toNumberString(ayah);\n delete highlightedAyahs[ayahKey];\n this.setState({ highlightedAyahs });\n }\n }", "function removeTextSelection() {\n\n if (window.getSelection) {\n\n window.getSelection().removeAllRanges();\n\n } else if (document.selection) {\n\n document.selection.empty();\n\n }\n\n}", "function clearHighlights () {\n a4.classList.remove('box-highlight');\n b4.classList.remove('box-highlight');\n c4.classList.remove('box-highlight');\n d4.classList.remove('box-highlight');\n a3.classList.remove('box-highlight');\n b3.classList.remove('box-highlight');\n c3.classList.remove('box-highlight');\n d3.classList.remove('box-highlight');\n a2.classList.remove('box-highlight');\n b2.classList.remove('box-highlight');\n c2.classList.remove('box-highlight');\n d2.classList.remove('box-highlight');\n a1.classList.remove('box-highlight');\n b1.classList.remove('box-highlight');\n c1.classList.remove('box-highlight');\n d1.classList.remove('box-highlight');\n}", "function resetHighlight(e) {\n style_override = {};\n var layer = e.target;\n geojson.resetStyle(layer);\n}", "function clearCharRadius(scene) {\n for (let i = 0; i < 17; i++) {\n for (let j = 0; j < 17; j++) {\n var temp = \"highlightB - \" + i + \" - \" + j;\n var highlight = scene.getObjectByName(temp);\n\n if (highlight == undefined)\n continue;\n\n highlight.visible = false;\n\n }\n }\n}", "function clearSelection() {\r\n map.deselectCountry();\r\n pc1.deselectLine();\r\n donut.deselectPie();\r\n sp1.deselectDot();\r\n }", "function dehighlight() {\n\n\t// Get tweet text div\n\tvar tweetTextDiv = d3.select(\"#tweetTextDiv\");\n\n\t// Get tweet text\n\tvar tweetText = tweetTextDiv.text();\n\n\t// Remove highlighted text (the old tweet text with 3 <span>s)\n\ttweetTextDiv.selectAll(\"span\").remove();\n\n\t// Add non highlighted text\n\ttweetTextDiv.append(\"span\").text(tweetText);\n\n\t// Add actual tweet\n\n}", "function cleanupHighlights() {\n\t\t// Remember range details to restore it later.\n\t\tvar startContainer = rangeObject.startContainer;\n\t\tvar startOffset = rangeObject.startOffset;\n\t\tvar endContainer = rangeObject.endContainer;\n\t\tvar endOffset = rangeObject.endOffset;\n\n\t\t// Remove each of the created highlights.\n\t\tfor (var highlightIdx in highlights) {\n\t\t\tremoveHighlight(highlights[highlightIdx]);\n\t\t}\n\n\t\t// Be kind and restore the rangeObject again.\n\t\trangeObject.setStart(startContainer, startOffset);\n\t\trangeObject.setEnd(endContainer, endOffset);\n\t}", "function clearCodeSelection() {\n\n}", "function removeAllSelections() {\r\n\tvar pos = getCaretPosition();\r\n\twindow.getSelection().removeAllRanges();\r\n\tsetCaretPosition(pos);\r\n}", "function removeUnderlineSelection() {\n\n var sel = window.getSelection();\n var range = sel.getRangeAt(0);\n\n var nodes = getRangeTextNodes(range);\n\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i];\n// unhighlight(node);\n var parent = node.parentNode;\n// window.TextSelection.jsLog(\"====\\n!@@@@@@@@@@! span= \" + parent.getElementsByTagName(\"span\").length);\n if (parent.nodeName != \"SPAN\") {\n unhighlight(node);\n// window.TextSelection.jsLog(\"1111\");\n } else {\n// window.TextSelection.jsLog(\"2222\");\n unhighlight(parent);\n }\n\n// window.TextSelection.jsError(\"!@@@@@@@@@@! = \" + parent.nodeType);\n// window.TextSelection.jsError(\"!@@@@@@@@@@! = \" + parent.textContent);\n// window.TextSelection.jsError(\"!@@@@@@@@@@! = \" + parent.nodeName);\n// continue;\n//\n// var r = document.createRange();\n// r.setStart(node, 0);\n// r.setEnd(node, node.textContent.length);\n// setRangeTextDecoration(r, \"none\");\n//\n//\n//// r.setStart(node, )\n// if (node.style) {\n// node.style.textDecoration = \"none\";\n// }\n }\n}", "function unselectText() {\n window.getSelection().empty();\n}", "function undoHighlightContext() {\n highlightDOM.style.display = \"none\";\n document.body.removeChild(highlightDOM);\n}", "function resetHighlight(e) {\n geojson.resetStyle(e.target);\n //Custom info:\n info.update();\n}", "function cleanHighlights() {\n\t\t\t// document.querySelectorAll returns a NodeList, it looks like an array, almost behaves like an array\n\t\t\t// but is not an array and therefore doesn't have the .forEach method available.\n\t\t\t// That's why I make an Array.from this list to have an array instead.\n\t\t\tArray.from(document.querySelectorAll('.playing')).forEach(function (element) {\n\t\t\t\telement.classList.remove('playing');\n\t\t\t})\n\t\t}", "clearHighlight() {\n return this.overlayAgent.invoke_hideHighlight();\n }", "clearHighlight() {\n this.clearCharts();\n\n let infoSVG = d3.select('#info-svg');\n infoSVG.selectAll(\"text\").remove();\n\n this.updateTable(this.stateDataArray);\n\n }", "function allClear() {\n previousText.innerHTML = '';\n currentText.innerHTML = '';\n}", "function clearSelectedText() {\n selectedText = \"\";\n}", "function resetHighlight() {\n\tfor (i in fgTileLayer.children) {\n\t\tfgTileLayer.children[i].setFill('rgba(0,0,0,0)');\n\t\tfgTileLayer.children[i].highlighted = false;\n\t}\n\tfgTileLayer.draw();\n}", "function cancelHighlight(){\n\t\tfor(var l = 0; l < highlightTiles.length; l++){\n\t\t\thighlightTiles[l].classList.remove(\"highlight\");\n\t\t}\n\n\t\thighlightTiles = [];\n\t}", "reset() {\n this._selection = -1;\n }", "function unhighlightEasyFeature(e) {\n info.update();\n if (e.target.feature.properties.Difficulty === selectedText || selectedText === \"All\") {\n easyLayer.resetStyle(e.target);\n }\n }", "function clearHighlight() {\n $('.opBtn').removeClass('selectedOperator');\n}", "function resetButtons() {\n $(\".letter\").css({\"pointer-events\": \"auto\", \"background-color\": \"#666600\"});\n /*\n $(\".letter\").removeClass(\"used\");\n $(\".letter\").removeClass(\"success fail\", 500);\n */\n $(\"#btn1\").removeClass(\"highlight\", 500);\n }", "function removeSelectionHighlight() {\r\n hideSelectionRect();\r\n hideRotIndicator();\r\n }", "function reset() {\r\n usedLetters = [];\r\n}", "_resetSelection() {\n this.__selectedRangeArr = [];\n this.__anchorSelectionIndex = -1;\n this.__leadSelectionIndex = -1;\n }", "function clearMarkers() {\n for(var x = 0; x < Model.markers().length; x++){\n Model.markers()[x].highlight(false);\n }\n Model.currentMarker(null);\n }", "resetHighlight(event) {\n this.layer.resetStyle(event.target);\n }", "function clearFont() {\n fontArea.innerHTML = \"\";\n}", "function clearSelectedCells() {\n var startStop = getStartStop(charaster.selectBegin, charaster.selectClose);\n for (var y = startStop[0].y; y < startStop[1].y; y++) {\n for (var x = startStop[0].x; x < startStop[1].x; x++) {\n charaster.clearCell(new Point(x, y));\n }\n }\n}", "function clearText()\n{\n codeProcessor.clear();\n}", "function unhighlight(p){\n\t$(p).css('background', '#fff');\n}", "function removeContextHighlights () {\n $('.moderation-note-contextual-highlight').each(function () {\n if ($(this).data('moderation-note-highlight-id')) {\n $(this).removeClass('moderation-note-contextual-highlight existing');\n }\n else {\n $(this).contents().unwrap();\n }\n });\n }", "function cursorClear() {\n document.body.style.cursor = 'default';\n }", "function cleanSelection() {\n for (let i = 0; i < colorOptCount; i++) {\n colorOpt.remove(colorOpt[i]);\n }\n}", "function clearHighlights() {\n // select element to unwrap\n var el = document.querySelector('#highlighted');\n\n // get the element's parent node\n if (el !== null) {\n var parent = el.parentNode;\n\n // move all children out of the element\n while (el.firstChild)\n parent.insertBefore(el.firstChild, el);\n\n // remove the empty element\n parent.removeChild(el);\n }\n}", "_reset() {\n this._buffer = [];\n this._codepage = 'ascii';\n\n this._state = {\n 'bold': false,\n 'underline': false,\n };\n }" ]
[ "0.74931645", "0.73942155", "0.7329344", "0.7296067", "0.7280655", "0.7263434", "0.71119285", "0.71032435", "0.7080586", "0.69316155", "0.69220114", "0.69005716", "0.68827707", "0.68760043", "0.68590003", "0.6858664", "0.68261915", "0.68254304", "0.6809151", "0.6797355", "0.6795632", "0.67940104", "0.679061", "0.6772212", "0.67642117", "0.67516184", "0.67403", "0.6727877", "0.672655", "0.67248696", "0.6714052", "0.6704436", "0.66943747", "0.6684205", "0.66721076", "0.6671977", "0.66552156", "0.66184103", "0.6614678", "0.66101134", "0.6588369", "0.65705377", "0.65655965", "0.6555805", "0.65542936", "0.65448856", "0.654483", "0.65293866", "0.65206164", "0.65058774", "0.6501429", "0.6496028", "0.6490926", "0.6488927", "0.64672214", "0.64570355", "0.64413244", "0.64390177", "0.6433408", "0.6429015", "0.6428499", "0.64226115", "0.6410698", "0.64069796", "0.6402659", "0.6401418", "0.6394708", "0.6375643", "0.63733643", "0.63698363", "0.63556755", "0.6354962", "0.6351617", "0.63488466", "0.6339656", "0.6338163", "0.63309085", "0.63188726", "0.63122034", "0.6306235", "0.62966293", "0.62895405", "0.62732923", "0.62674916", "0.62626773", "0.62437654", "0.6219158", "0.62066656", "0.61968493", "0.61949277", "0.61802226", "0.6169381", "0.61647266", "0.6157819", "0.614152", "0.6138553", "0.61382425", "0.6133061", "0.6118608" ]
0.766301
1
for each letter, map it to list of positions of all its appearances in the cipher.
function makeIndex() { // var s = ""; var index = {}; for (var row=0; row<cipher[which].length; row++) { for (var col=0; col<cipher[which][row].length; col++) { var key = cipher[which][row].charAt(col); // s += "("+row+","+col+","+key+") "; if (index[key]) { index[key][index[key].length] = [row, col]; } else { index[key] = [[row, col]]; } } } // alert(s); return index; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function letterInWord(letter) {\n // the array that will contain the char positions in the currentWord that has the\n var positions = new Array();\n for (i = 0 ; i < currentWord.length; i++) {\n if (currentWord[i] === letter)\n positions.push(i);\n }\n return positions;\n }", "function alphabetPosition(text) {\n const letters = \"abcdefghijklmnopqrstuvwxyz\".split('')\n \n return text.toLowerCase().split('').filter(el => el >= 'a' & el <= 'z').map(el => letters.indexOf(el) + 1 ).join(' ')\n}", "function findLetterIndexes(letter) {\n var letterIndexes = [];\n for (var i = 0; i < randomWordArray.length; i++) {\n if (randomWordArray[i] === letter) {\n letterIndexes.push(i);\n }\n }\n replaceDashes(letterIndexes); // returns an array of number indexes like [1, 2, 3]\n }", "function letterInWord(letter) {\n var positions = new Array();\n for (i = 0; i < currentWord.length; i++) {\n if (currentWord[i] === letter)\n positions.push(i);\n }\n return positions;\n }", "function alphabetPosition(text) {\n let stringOfNumbers = []\n for (let i=0; i<text.length; i++) {\n const ascii = text[i].toLowerCase().charCodeAt()\n //console.log(ascii)\n //this is too specify the alphabet range \n if (ascii >=97 && ascii <=122 && ascii) stringOfNumbers.push(ascii-96)\n }\n return stringOfNumbers.join(' ')\n }", "function alphabetPosition(text) {\n\tlet alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n\tlet textArray = [];\n\tlet position = [];\n\n\tfor (i = 0; i < text.length; i++) {\n\t\ttextArray.push(text[i].toLowerCase());\n\t}\n\n\ttextArray.forEach((letter) => {\n\t\tfor (i = 0; i < alphabet.length; i++) {\n\t\t\tif (alphabet[i] == letter) {\n\t\t\t\tposition.push(alphabet.indexOf(alphabet[i]) + 1);\n\t\t\t}\n\t\t}\n\t});\n\n\tlet numbers = position.join(\" \");\n\tconsole.log(textArray);\n\tconsole.log(position);\n\tconsole.log(numbers);\n}", "function letterInWord(letter) {\n // letter position in the currentWord\n var positions = new Array();\n for (i = 0 ; i < currentWord.length; i++) {\n if (currentWord[i] === letter)\n positions.push(i);\n }\n return positions;\n}", "function letterInWord(letter) {\n var positions = new Array();\n for (i = 0; i < word.length; i++) {\n if (word[i] === letter)\n positions.push(i);\n }\n return positions;\n}", "function alphabetPosition(text){\n let result = '';\n for(let i = 0; i < text.length; i++){\n let current = text[i].toUpperCase().charCodeAt(0);\n if( (current> 65) && ( current< 91) ){\n result += current -64 + ' ';\n }\n }\n return result;\n}", "function alphabetPosition(text) {\n let final = [];\n let lowerCased = text.toLowerCase();\n for (let i=0; i<lowerCased.length; i++) {\n if (lowerCased.charCodeAt(i) >= 97 && lowerCased.charCodeAt(i) <=122) {\n final.push(lowerCased.charCodeAt(i) - 96);\n }\n }\n return final.join(\" \");\n}", "function alphabetPosition(text) {\n const splitString = text.split('')\n const numText = splitString.reduce((numText, letter, index) => {\n if (!alphaData[letter.toLowerCase()]) {\n return numText\n }\n if (!numText.length) {\n return numText + alphaData[letter.toLowerCase()]\n }\n return numText + \" \" + alphaData[letter.toLowerCase()]\n }, \"\")\n return numText;\n}", "function alphabetPosition2(text) {\n return text.match(/[a-zA-Z]/g).map( (el) => el.toUpperCase().charCodeAt(0) - 64 ).join(' ');\n}", "function alphabetPosition(text) {\n const alphabet = 'abcdefghijklmnopqrstuvwxyz '\n\n if (text != undefined && !text.match(/[^A-Za-z ]/g, \"\")) {\n const string = text.toString().toLowerCase()\n const stringArray = Array.from(string)\n\n let output = stringArray.map(e => {\n let letter = ''\n alphabet.indexOf(e) != 26\n ? letter = `[${alphabet.indexOf(e) + 1}]`\n : letter = `[Espaço]`\n return letter\n })\n\n return output.join(\"-\")\n\n } else {\n return 'Somente letras são permitidas.'\n }\n}", "function alphabetPosition(text) {\n\n var newText = \"\";\n var dict1 = {\n \"a\": \"1\", \"b\": \"2\", \"c\": \"3\", \"d\": \"4\", \"e\": \"5\",\n \"f\": \"6\", \"g\": \"7\", \"h\": \"8\", \"i\": \"9\", \"j\": \"10\",\n \"k\": \"11\", \"l\": \"12\", \"m\": \"13\", \"n\": \"14\", \"o\": \"15\",\n \"p\": \"16\", \"q\": \"17\", \"r\": \"18\", \"s\": \"19\", \"t\": \"20\",\n \"u\": \"21\", \"v\": \"22\", \"w\": \"23\", \"x\": \"24\", \"y\": \"25\",\n \"z\": \"26\"\n };\n\n // replace text code to newText variable\n for (var i = 0; i < text.length; i++) {\n let char1 = text[i].toLowerCase();\n if (char1 in dict1) {\n newText += dict1[char1] + \" \";\n }\n }\n\n // remove last character which is empty space\n newText = newText.substring(0, newText.length-1);\n return newText;\n}", "function characterMapping(str) {\n let repeat = [];\n let map = [];\n for (let i = 0; i < str.length; i++) {\n if (repeat.indexOf(str[i]) === -1) {\n repeat.push(str[i]);\n map.length === 0 ? map.push(0) : map.push(Math.max(...map) + 1)\n } else {\n map.push(repeat.indexOf(str[i]))\n }\n }\n return map \n}", "function position(letter){\n return \"Position of alphabet: \" + ((letter.charCodeAt(0)-97) + 1);\n }", "function solution(S) {\n let lowerS = S.toLowerCase();\n var occurrences = new Array(26);\n //set every letter as array index, and occurrences as 0 to initialize\n for (var i = 0; i < occurrences.length; i++) {\n occurrences[i] = 0;\n }\n // for ( <var> in <string> ) {\n // returns index of each element of string;\n // for ( <var> of <string> ) {\n // returns each character of string\n \n //for (var id in lowerS) {\n for (let id = 0; id < lowerS.length; id++) {\n //id yields the index of the characters in lowerS\n //lowerS.charCodeAt(id) yields the character code at position id of lower\n // Code: 104 id: 0 lowerS[id]: h\n // code - 'a'.charCodeAt(0) = 104 - 97 = 7\n // Code: 101 id: 1 lowerS[id]: e\n // code - 'a'.charCodeAt(0) = 101 - 97 = 4\n // Code: 108 id: 2 lowerS[id]: l\n // code - 'a'.charCodeAt(0) = 108 - 97 = 11\n // Code: 108 id: 3 lowerS[id]: l\n // code - 'a'.charCodeAt(0) = 108 - 97 = 11\n // Code: 111 id: 4 lowerS[id]: o\n // code - 'a'.charCodeAt(0) = 111 - 97 = 14\n let code = lowerS.charCodeAt(id);\n console.log(\"Code: \", code, \" id: \", id, \" lowerS[id]: \", lowerS[id]);\n //Subtracting the character code of 'a' from code yields the character # of a-z (0-25)\n let index = code - 'a'.charCodeAt(0);\n console.log(`code - 'a'.charCodeAt(0) = ${code} - ${'a'.charCodeAt(0)} = ${index}`);\n occurrences[index]++;\n }\n console.log(\"New occurrences: \", occurrences);\n\n var best_char = 'a';\n var best_res = occurrences[0]; //replace 0 with the actual value of occurrences of 'a'\n\n //starting i at 1, because we've already set best_char = 'a' and 'a's occurrences.\n for (var i = 1; i < 26; i++) {\n if (occurrences[i] >= best_res) {\n //Now reverse this from an index (i) to a character code (fromCharCode) to a character (best_char)\n best_char = String.fromCharCode('a'.charCodeAt(0) + i);\n best_res = occurrences[i];\n }\n }\n\n return best_char;\n}", "function characPosit(character){\n\t\t//your code is here\n\t\tvar code = character.toLowerCase().charCodeAt(0)\n\t\treturn \"Position of alphabet: \" + (code - 96);\n\t}", "function convert(letter){\n var letters=['A','B','C', 'D','E','F','G','H'];\n return letters.indexOf(letter) + 1;\n }", "function position(letter){\n let alphabet ='abcdefghijklmnopqrstuvwxyz';\nreturn `Position of alphabet: ${alphabet.indexOf(letter)+1}`;\n}", "function alphabetPosition(text) {\n var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];\n var position = '';\n for(var i=0; i< text.length; i++) {\n if(alphabet.includes(text[i].toLowerCase())) {\n replace(alphabet.indexOf(text[i].toLowerCase()) +1) + \"\";\n } else {\n continue;\n }\n return position.trim()\n }\n alphabetPosition(\"The sunset sets at twelve o'clock.\")\n}", "function charactersOccurencesCount(word) \n{\n var letterAndNumber = [];\n \n for(let i = 0; i < word.length; i++)\n {\n for (let j = 0; j < letterAndNumber.length; j++)\n {\n if (word[i] === letterAndNumber[j][0])\n {\n letterAndNumber[j][1]++;\n break;\n }\n else if (word[i] !== letterAndNumber[j][0] && j === letterAndNumber.length - 1)\n {\n letterAndNumber[letterAndNumber.length][0] = word[i];\n letterAndNumber[letterAndNumber.length][1] = 1;\n }\n }\n }\n\n return letterAndNumber;\n}", "function alphabetPosition(text) {\n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n var word = \"\"\n var lowercase = text.toLowerCase()\n for (var i = 0 ; i < lowercase.length ; i ++ ) {\n for (var j = 0 ; j < alphabet.length ; j++) {\n if ( lowercase[i] === alphabet[j]) {\n word += `${j+1} `;\n }\n }\n }\n return word.trim();\n }", "function getCharPosition(c) {\n var index = cipher.key.indexOf(c);\n var row = Math.floor(index / 5);\n var col = index % 5;\n return {\n row: row,\n col: col,\n };\n}", "function letterToNumber(letter) {\n let alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',\n 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];\n let position = alphabet.indexOf(letter) + 1;\n let uni = letter.charCodeAt(0);\n console.log(uni);\n\n\n return 'Alphabet position: ' + position + ' Unicode value: ' + uni;\n}", "function lowerLetters(){\n // start at the position of the first lowercase letter\n for (var i = 97; i <= 122; i++) {\n // push every lowercase letter from positions 97 to 122 into storedCharacters key\n answer.storedCharacters.push(String.fromCharCode(i));\n }\n}", "function alphabetPosition(text) {\n \n let letter = \"\"\n let stringWithNumber = \"\"\n for (let i=0; i<text.length; i++) {\n letter = text.charCodeAt(i) - 64\n if (letter !== ''){\n stringWithNumber+=letter + \" \"\n }\n letter=\"\"\n }\n\n return stringWithNumber;\n}", "function alphabetPosition(text) {\n let result = \"\";\n\n text = text.toLowerCase();\n console.log(text);\n \n for (let i = 0; i < text.length; i++) {\n code = text.charCodeAt(i) - 96;\n console.log(code); \n if (26 >= code && code >= 1) {\n result += code.toString() + ' ';\n } how would you clean it up? im sure you can do chains of like .toString.trimRight. etc?\n } // so at this point i was figuring out how to add a space between each number.\n // i also need to remember to subtract 97 from each number. \n return result.trimRight() // <-- i am proud i knew to put it here \n}", "function characPosit(character){\n\t\tvar alphabet=\"abcdefghijklmnopqrstuvwxyz\"\n\t\tvar position =eval(alphabet.indexOf(character))+1;\n\t\treturn \"Position of alphabet: \" + position;\n\t}", "function answerMap() {\n let alpha = numbers.map(numbers => {\n document.getElementById('map').innerHTML += ' ' + String.fromCharCode(numbers)\n })\n}", "function characPosit(character){\n\t\tvar letters=\"abcdefghijklmnopqrstuvwxyz\"\n\t\treturn letters.indexOf(character.toLowerCase())+1\n\t}", "function caeserCipher(str, shift) {\n const alphabetArr = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n let res = \"\";\n for(let i =0; i < str.length; i++){\n const char = str[i];\n const idx = alphabetArr.indexOf(char);\n //console.log(idx)\n if(idx === -1 ){\n res += char;\n continue;\n }\n const encodedIdx = (idx + shift) %26;\n console.log(encodedIdx)\n res += alphabetArr[encodedIdx]\n }\n return res;\n}", "function react(letters) {\n const stack = [];\n for (let char of letters.split(\"\")) {\n const top = stack[stack.length - 1];\n if (top && top.toLowerCase() === char.toLowerCase() && top !== char) {\n stack.pop();\n } else {\n stack.push(char);\n }\n }\n return stack.length;\n}", "function letterTallyHelper(str) {\n let map = {}\n function helper(word) {\n if(word.length === 0) return map \n if(map.hasOwnProperty(word[0])) map[word[0]]++\n if(!map.hasOwnProperty(word[0])) map[word[0]] = 1\n helper(word.slice(1))\n }\n helper(str)\n return map \n}", "function commonLetter(word,guess){\n\tlet count = 0;\n\tlet map = [];\n\tfor (let letter of word) {\n\t\tif (!map[letter]){\n\t\t\tmap[letter] = 0;\n\t\t}\n\t\tmap[letter]++;\t\n\t}\n\t//console.log(map);\n\tfor (let i = 0; i < guess.length; i++) {\n\t\tif ( map[guess[i]] && map[guess[i]] != 0) {\n\t\t\tmap[guess[i]]--;\n\t\t\tcount++;\n\t\t}else{\n\t\t\tcontinue;\n\t\t}\n\t}\n\t//console.log(map);\n\treturn count;\n}", "function positionInAlphabet(myChar) {\n const DIFFERENCE_CHARCODE_AND_LETTERS = 96;\n // Convert the character into lowercase\n const myCharLowercase = myChar.toLowerCase();\n // Find the position of the char in the alphabet\n const position = myCharLowercase.charCodeAt() - DIFFERENCE_CHARCODE_AND_LETTERS;\n // Return the desired message with the position\n return `Position in Alphabet: ${position}`\n}", "function collectAndSetChars() {\n var charsS = new Set();\n var charsA;\n var cc;\n dictionary.reset();\n println(\"collecting chars…\");\n while (!dictionary.eof()) {\n cc = dictionary.data[1].charCodeAt(dictionary.data[0]);\n if (cc === 45 || cc >= 65) {\n charsS.add(cc);\n }\n dictionary.data[0] += 1;\n }\n charsA = Array.from(charsS);\n charsA.sort((a, b) => a - b);\n charsA.forEach(function setChar(cc) {\n var c = String.fromCharCode(cc);\n var i = xint[cc];\n if (i === undefined) {\n if (c === c.toUpperCase()) {\n //c is upperCase -> try lowerCase\n i = xint[c.toLowerCase().charCodeAt(0)];\n } else if (c.toUpperCase().length === 1) { //test for length is necessary because \"ß\".toUpperCase() -> \"SS\"\n //c ist lowerCase -> try upperCase\n i = xint[c.toUpperCase().charCodeAt(0)];\n }\n if (i === undefined) {\n i = xext.push(c.toLowerCase()) - 1;\n xint[cc] = i;\n xclass[cc] = letter_class;\n } else {\n //other case already exists:\n xint[cc] = i;\n xclass[cc] = letter_class;\n }\n }\n });\n xdig = xext.slice(0, 10);\n cmax = xext.length - 1;\n cnum = xext.length;\n}", "function replaceLetter(letter){\n var str = currentWordChosen;\n var indices = [];\n for(var i=0; i<str.length;i++) {\n if (str[i] === letter) indices.push(i);\n }\n //console.log(indices);\n if(indices.length == 0){\n return -1;\n }\n for(var key in indices){\n var index = indices[key];\n guessedWordSoFar[index] = letter;\n }\n\n //console.log(guessedWordSoFar);\n }", "convertForwards(letter) {\n const inIndex = this._inputIndex(letter)\n letter = this._rotor.alphabet.charAt(inIndex)\n const outIndex = this._outputIndex(letter, plainAlphabet)\n return plainAlphabet.charAt(outIndex)\n }", "function findLetter (arrFind, letter, arrIndexOfGuessedLetters) {\n \n for (i=0; i <arrFind.length; i++) {\n if (letter.toLowerCase()===arrFind[i]) {\n countLetters+=1;\n arrIndexOfGuessedLetters [i]= i;\n var isLetter =1;\n }\n else {\n var isLetter=0;\n \n }\n \n }\n console.log (countLetters);\n return arrIndexOfGuessedLetters;\n }", "function countABC(sentence) {\n sentence = sentence.replace(/\\s/g, \"\");\n let letterCounter = {};\n for (letter of sentence) {\n if (!letterCounter[letter]) {\n letterCounter[letter] = 1;\n }\n else letterCounter[letter] += 1;\n }\n return letterCounter;\n}", "function evaluateGuess(letter) {\n var positions = [];\n for (var i = 0; i < wordList[currentWordIndex].length; i++) {\n if(wordList[currentWordIndex][i] === letter) {\n positions.push(i);\n }\n }\n if (positions.length <= 0) {\n guessesRemaining--;\n } \n else {\n for(var i = 0; i < positions.length; i++) {\n currentWord[positions[i]] = letter;\n }\n }\n}", "function countLetters(){\n for (let i = 0; i < textInput.length; i++){\n if (checkLetter(textInput.charAt(i)) === false){\n letters[textInput.charAt(i)] = 1;\n }else{\n current = letters[textInput.charAt(i)];\n letters[textInput.charAt(i)] = current + 1;\n }\n }\n}", "function samePosLetter(word, guess){\n\tlet count = 0;\n\tfor (let i = 0; i < word.length; i++) {\n\t\tif (word[i] === guess[i]) {\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn count;\n}", "function characPosit(character)\n{\n\tvar alphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tfor(var i = 0; i<alphabet.length; i++)\n\t{\n\t\tif(alphabet[i] === character)\n\t\t{\n\t\t\treturn i+1;\n\t\t}\n\t}\n\treturn -1; //if not found in alphabet\n}", "function convertToAlpha(num) {\n\n let perm = [];\n num = num.toString().split('');\n let temp = num.slice();\n\n perm.push(mapper(num));\n\n for (var i = 0; i < num.length; i++) {\n for (var j = i; j < num.length; j++) {\n let sum = num[j] + num[j+1]\n if (sum <= 26) {\n num[j] = sum;\n num.splice(j+1, 1);\n console.log(num);\n perm.push(mapper(num));\n }\n }\n num = temp.slice();\n }\n return perm;\n}", "function PositionForOurPhrase(a) {\n console.log(OurPhraseArray[a] + \" is the \" + (OurPhraseArray[a].charCodeAt(a) - 64) + \" letter in the alphabet and the \" + OurPhraseArray[a].charCodeAt(a) + \" letter in the ASCII table.\");\n }", "function evaluateGuess(letter) {\n // Array to store positions of letters in string\n var positions = [];\n for (var i = 0; i < wordList[currentWordIndex].length; i++) {\n if(wordList[currentWordIndex][i] === letter) {\n positions.push(i);\n }\n }\n if (positions.length <= 0) {\n remainingGuesses--;\n } else {\n for(var i = 0; i < positions.length; i++) {\n guessingWord[positions[i]] = letter;\n }\n }\n}", "function evaluateGuess(letter) {\n // Array to store positions of letters in string\n var positions = [];\n\n // Loop through word finding all instances of guessed letter, store the indicies in an array.\n for (var i = 0; i < words[guessWordIndex].length; i++) {\n if(words[guessWordIndex][i] === letter) {\n positions.push(i);\n console.log(letter);\n }\n }\n\n // if there are no indicies, remove a guess\n if (positions.length <= 0) {\n lifePoints--;\n\n } else {\n // Loop through all the indicies and replace the '_' with a letter.\n for(var i = 0; i < positions.length; i++) {\n guessWord[positions[i]] = letter;\n\n }\n }\n}", "function alphabetPosition(text) {\n\n\n const alphabetString = \"abcdefghijklmnopqrstuvwxyz\"\n\n return text;\n}", "function matchingLetters(str, guess) {\n var indices = [];\n for (var i = 0; i < str.length; i++) {\n if (str[i] === guess) {\n indices.push(i);\n }\n }\n return indices;\n}", "function evaluateGuess(letter) {\r\n var positions = [];\r\n\r\n for (var i = 0; i < transformersCharacters[computerPick].length; i++) {\r\n if(transformersCharacters[computerPick][i] === letter) {\r\n positions.push(i);\r\n }\r\n }\r\n\r\n if (positions.length <= 0) {\r\n guessesLeft--;\r\n } else {\r\n for(var i = 0; i < positions.length; i++) {\r\n wordGuessed[positions[i]] = letter;\r\n }\r\n }\r\n}", "function ceasarCipher3(alphabet) {\n for (var i = 0; i < alphabet.length; i++){\n console.log(alphabet[i].charCodeAt());\n }\n}", "function LetterCountI(str){\n // remove special characters from string\n str = str.replace(/[&\\!/\\\\#,+()$~%.:*?<>{}]/g, '');\n var strNew = [];\n // str to array\n var strArray = str.split(' ');\n // loop through each word of array\n for (var x = 0; x < strArray.length; x++) {\n var newWord = \"\";\n // declare variable for each word of strArray\n var strArrayWord = strArray[x];\n // loop through each letter of each word of strArray\n for (var y = 0; y < strArrayWord.length; y++) {\n // declare variable for letter this loop\n var letterThisLoop = strArrayWord[y];\n // use indexOf to determine if letter has been repeated \n if (newWord.indexOf(letterThisLoop) > -1) {\n return strArray[x];\n }\n newWord += letterThisLoop;\n }\n strNew.push(newWord);\n }\n return -1;\n}", "function charMap(str) {\n const charMap={};\n //iterate through each char of string\n for(let char of str.replace(/[^\\w]/g, '').toLowerCase()){\n /* check if key value exist and increment\n else initialize to 1\n */\n if(charMap[char]){\n charMap[char]= charMap[char]+1\n } else{\n charMap[char]= 1;\n }\n }\nreturn charMap;\n}", "function letterChanges(str) {\n\n let letters = 'abcdefghijklmnopqrstuvwxyz'\n let result = '';\n for(let i = 0; i < str.length; i++) {\n let letter = str[i];\n let index = letters.indexOf(letter)\n if (index === 25) {\n result += letters[0];\n } else if (index < 0) {\n result += letter;\n } else {\n letter = letters[index + 1]\n if (letter === 'a') {\n letter = 'A'\n }\n if (letter === 'e') {\n letter = 'E'\n }\n if (letter === 'i') {\n letter = 'I'\n }\n if (letter === 'o') {\n letter = 'O'\n }\n if (letter === 'u') {\n letter = 'U'\n }\n result += letter\n }\n }\n return result;\n\n}", "function caesarCipher(string, num){\n const characters = 'abcdefghijklmnopqrstuvwxyz'.split('')\n const lowerCaseString = string.toLowerCase()\n num = num % 26\n const stringArr =lowerCaseString.split('')\n let changingString = []\n\n stringArr.map(char => {\n let charIndex = characters.indexOf(char)\n if (charIndex > -1 && characters.includes(char)){\n \n //Verify if index > 25 then return in the first index of list\n let index = charIndex + num > 25 ? charIndex + num - 26 : charIndex + num < 0 ? charIndex + num + 26 : charIndex + num \n // verify if string is upper case\n // ??\n\n char = characters[index]\n changingString.push(char) \n }else{\n changingString.push(char) \n }\n })\n //console.log(changingString)\n return changingString.join('')\n}", "function filterLetters(arr, letter) {\n\tarr.reduce(function(acc, next){\n\t\tif next.toLowerCase() === letter.toLowerCase() {\n\t\t\tacc++;\n\t\t}\n\t\treturn acc;\n\t},0);\n}", "function evaluateGuess(letter) {\n // Array to store positions of letters in string\n var positions = [];\n\n // Loop through word finding all instances of guessed letter and store in an array.\n for (var i = 0; i < currentWord.length; i++) {\n if (currentWord[i] === letter) {\n positions.push(i);\n }\n }\n // Loop through all the matching keys pressed and replace the '_' with a letter.\n for (var i = 0; i < positions.length; i++) {\n guessingWord[positions[i]] = letter;\n \n }\n}", "function solve2(arr) {\n let arr2 = arr.map(ele => ele.toLowerCase());\n let alphabet = 'abcdefghijklmnopqrstuvwxyz';\n let returnArry = [];\n for (let idx = 0; idx < arr2.length; idx++) {\n let count = 0;\n for (let idx2 = 0; idx2 < arr2[idx].length; idx2++) {\n if (idx2 === alphabet.indexOf(arr2[idx][idx2])) {\n count++; \n }\n }\n returnArry.push(count);\n }\n return returnArry;\n}", "function letterIndex(letter) {\n var letter;\n letter = letter.toLowerCase(); \n var alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n alphabet = alphabet.split(\"\");\n\n for(i = 0; i < alphabet.length; i++) {\n if (alphabet[i] === letter) {\n return i;\n }\n }\n}", "function letterIndex(letter) {\n letter = letter.toLowerCase(); \n var alphabet = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n\n for(i = 0; i < alphabet.length; i++) {\n if (alphabet[i] === letter) {\n return i;\n }\n }\n}", "function getBetterChars(ranking, position) {\n var nextrank = \"Unranked\";\n var charlist = [];\n\n //obtain rank above\n for (let [key, value] of characters) {\n switch(ranking){\n case \"Unranked\":\n nextrank = \"C\"\n break;\n case \"C\":\n nextrank = \"B\"\n break;\n case \"B\":\n nextrank = \"A\"\n break;\n case \"A\":\n nextrank = \"S\"\n break;\n case \"S\":\n nextrank = \"SS\"\n break;\n }\n //put each character that is a rank above within an array\n if (value[position] == nextrank)\n charlist.push(key);\n }\n return charlist;\n }", "function o(str){\n\tvar letters = {}\n\tstr = str.replace(/\\s+/g,\"\");\n\tfor(var i=0,l=str.length;i<0;i++){\n\t\tif(letters[str[i]]){\n\t\t\tletters[str[i]] + 1;\n\t\t}else{\n\t\t\tletters[str[i]] = 1;\n\t\t}\n\t}\n\treturn letters;\n}", "function getLetterFromAlphabet(position) {\n if (position == 0) {\n return \"\";\n }\n return String.fromCharCode(64 + position);\n}", "function findIndexesOfOccurrencesOfLetterInWord(letter, str) {\n var occurrences = [];\n\n for (var i = 0; i < str.length; i++) {\n if (letter === str[i]) {\n occurrences.push(i);\n }\n }\n\n return occurrences;\n}", "function alphabetPosition(text) {\n return text\n .replace(/[^A-Za-z]/g, '')\n .replace(/./g, letter => (letter.toUpperCase().charCodeAt(0) - 64) + ' ')\n .trim();\n}", "function presses(phrase) {\r\n // let changed = phrase.toLowerCase();\r\n let counter = 0, alphas = [['','1'], ['','a','b','c','2'], ['','d','e','f','3'], ['','g','h','i','4'], ['','j','k','l','5'], ['','m','n','o','6'], ['','p','q','r','s','7'], ['','t','u','v','8'], ['','w','x','y','z','9'],['','','0']];\r\n for (let i = 0; i < changed.length; i++) {\r\n for (let j = 0; j < alphas.length; j++) {\r\n if (alphas[j].includes(changed[i])) {\r\n counter += alphas[j].indexOf(changed[i]);\r\n }\r\n }\r\n }\r\n for (let k = 0; k <= changed.length; k++) {\r\n if (changed[k] === \" \") {\r\n counter += 1;\r\n }\r\n }\r\n console.log(counter);\r\n}", "function letterCounts(word) {\n let counterHash = word.split('').reduce( (acc, ch) => {\n acc[ch] = 0;\n return acc;\n }, {});\n\n let result = word.split('').reduce( (acc, ch) => {\n acc[ch] += 1;\n return acc;\n }, counterHash);\n\n return result;\n}", "function LetterChanges(str) { \n\t\tstr = str.split('');\n\t\n\t\tvar offArr = [];\n\t\tfor(var i = 0; i < str.length; i++){\n\t\t\tif(str[i] !== \"z\"){\n\t\t\toffArr.push(str[i + 1]);\n\t\t\t}else{\n\t\t\t\toffArr.push(\"a\")\n\t\t\t}\n \t\tswitch(offArr[i]) {\n case 'a': case 'e': case 'i': case 'o': case 'u':\n offArr[i] = offArr[i].toUpperCase();\n }\n }\n offArr = offArr.join('')\n return offArr; \n}", "function recognize_map(character)\r\n{\r\n var temp_position={x=0,y=0}\r\n for(var row=0;row<map.length;row++)\r\n {\r\n for(var col=0;col<map[0].length;col++)\r\n {\r\n if(map[row][col]==character){temp_position.x=row;temp_position.y=col;}\r\n }\r\n }\r\n return temp_position;\r\n}", "function countAllCharacters(str) {\n // your code here\n var letters = {};\n\n for (var i = 0; i < str.length; i++) {\n var char = str[i];\n letters[char] = (letters[char] + 1) || 1;\n \n }\n return letters; \n}", "function countABC1(sentence) {\n let letterCounter = {};\n for (letter of sentence) {\n if (letter !== \" \") {\n if (!letterCounter[letter]) {\n letterCounter[letter] = 1;\n }\n else letterCounter[letter] += 1;\n }\n }\n return letterCounter;\n}", "function lookup_table(letter) {\n return board_col_labels.slice(0,size).indexOf(letter);\n}", "function check_letter() {\n var sentence = prompt(\"type a sentence\"); // \"test\"\n const output = {}\n\n for (let i = 0; i < sentence.length; i++) {\n const letter = sentence[i]\n\n // const val = ++this._nextId[letter];\n // //this needs to check the value of each letter, add a new variable if one dosent already exsist\n if (output[letter]) { \n // if the letter was previously added, increment count by 1\n output[letter]++\n } else {\n output[letter] = 1\n }\n }\n\n return output\n}", "function highlightLetters(letters) {\n\t\tunhighlightAll();\n\t\tfor (var row=0; row<cipher[which].length; row++) {\n\t\t\tfor (var col=0; col<cipher[which][row].length; col++) {\n\t\t\t\tid = row + \"_\" + col;\n\t\t\t\tletter = cipher[which][row].substring(col,col+1);\n\t\t\t\tfor (var i=0; i<letters.length; i++) {\n\t\t\t\t\tif (letter == letters.substring(i,i+1)) {\n\t\t\t\t\t\th(id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "function highlightLetters(letters) {\n\t\tunhighlightAll();\n\t\tfor (var row=0; row<cipher[which].length; row++) {\n\t\t\tfor (var col=0; col<cipher[which][row].length; col++) {\n\t\t\t\tid = row + \"_\" + col;\n\t\t\t\tletter = cipher[which][row].substring(col,col+1);\n\t\t\t\tfor (var i=0; i<letters.length; i++) {\n\t\t\t\t\tif (letter == letters.substring(i,i+1)) {\n\t\t\t\t\t\th(id);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "updateWordMap(word, wordMap, letter) {\n for (let i = 0; i < word.length; i++) {\n if (word[i] === letter) {\n wordMap[i] = letter;\n }\n }\n return wordMap;\n }", "function setupListeners() {\n var elements = document.getElementsByClassName('letterHolder');\n var innerElements = document.getElementsByClassName('innerLetterHolder');\n for (var idx = 0; idx < elements.length; idx++) {\n var o = elements[idx];\n var io = innerElements[idx];\n\n o.onclick = function(event) {\n var element = event.target || event.srcElement;\n var letter, index, setOuterElement = false, pickElement = element;\n\n if (!element.getAttribute('index')) {\n pickElement = element.getElementsByClassName('innerLetterHolder')[0];\n } else {\n setOuterElement = true;\n }\n\n // determine index and letter\n index = parseInt(pickElement.getAttribute('index'));\n letter = pickElement.textContent.replace(/[^\\x00-\\x7F]/g, '');\n\n if(letterStack[index])\n {\n Materialize.toast('You have already selected that letter.', 3000);\n return;\n }\n\n if (checkLen(playWord) && hasAdjacentLetter(lastLetterPosition, index)) {\n element.classList.remove('yellow');\n element.classList.add('orange');\n if (setOuterElement) {\n element.parentNode.classList.remove('yellow');\n element.parentNode.classList.add('orange');\n } else {\n pickElement.classList.remove('yellow');\n pickElement.classList.add('orange');\n }\n\n // set letter index as used\n letterStack[index] = 1;\n lastLetterPosition = index;\n // set letter to word\n setLetter(letter);\n }\n };\n }\n\n function hasAdjacentLetter(position1, position2) {\n if (Object.keys(letterStack).length == 0) {\n return true;\n }\n const isAdjacent = checkIfAdjacent(position1, position2);\n if (!isAdjacent) {\n Materialize.toast('Letter must be adjacent to previous letter.', 3000);\n }\n return isAdjacent;\n }\n\n function checkIfAdjacent(position1, position2) {\n const arrayofAdjacentPositions = makeArrayOfAdjacent(position1, position2);\n return arrayofAdjacentPositions.includes(position2);\n }\n\n function makeArrayOfAdjacent(position1, position2) {\n const adjacentPositions = [];\n\n if(position1 % 4 === 0) {\n adjacentPositions.push(position1+1, position1-3, position1-4, position1+4, position1+5)\n } else if (position1 % 4 === 3) {\n adjacentPositions.push(position1-1, position1+3, position1-4, position1+4, position1-5)\n } else {\n adjacentPositions.push(position1-1, position1+1, position1-3, position1+3, position1-4, position1+4, position1-5, position1+5)\n }\n\n return adjacentPositions;\n }\n\n\n\n // set letter\n function setLetter(letter) {\n playWord += letter;\n var playWordEl = document.getElementById('playWord');\n playWordEl.innerText = playWord;\n }\n\n // check length\n function checkLen(word) {\n var result = true;\n if (word && word.length >= maxWordLength) {\n Materialize.toast('Words can only be 10 letters in length.', 3000);\n result = false;\n }\n return result;\n }\n}", "function characterMap (target, source) {\n if (source.length > target) {\n var temp = target;\n target = source;\n source = temp;\n }\n\n var results = [];\n // for (var k = 0; k < target.length; k++) { results[0].push(k); }\n for (var i = 0; i < source.length; i++) {\n var sourceChar = source[i];\n var result = []\n\n for (var j = 0; j < target.length; j++) {\n targetChar = target[j];\n\n if (sourceChar === targetChar) {\n result.push(1);\n } else {\n result.push(0);\n }\n }\n results.push(result);\n }\n return results;\n}", "function firstAcc(letter, string) {\n\n var position = -1;\n\n for (var i = 0; i < string.length; i++){\n\n if (string[i] === letter){\n position = i + 1;\n \n }\n }\n return position;\n}", "function wordsToMarks(string) {\n const alphabet = \"_abcdefghijklmnopqrstuvwxyz\";\n let marks = 0;\n\n for (let letter of string) {\n marks += alphabet.indexOf(letter);\n }\n return marks;\n}", "function findLetterInWord(word, idx, element) {\n var indices = [];\n console.log(\"you pressed: \" + element);\n console.log(\"which is the \" + idx + \"of the word \" + word);\n while (idx != -1) {\n indices.push(idx);\n idx = word.indexOf(element, idx + 1);\n }\n console.log(indices);\n while (indices.length > 0) {\n var letterPos = indices.pop();\n currentWord[letterPos] = element;\n lettersFound++;\n }\n document.getElementById(\"curWord\").textContent = currentWord.join(\"\");\n}", "function rotWord(word) {\n var characters = word.split(\"\");\n var newWord = [];\n for (var i = 0; i < characters.length; i++) {\n\n //console.log(letterIndex(characters[i])); // WORKSS!!!!!!!!\n //return letterIndex(characters[i]); why does this not work?\n //console.log(letterIndex(characters[i]) + 13); // adds 13\n //console.log(reverseLetterIndex(letterIndex(characters[i]) + 13)); // works\n newWord.push(reverseLetterIndex(letterIndex(characters[i]) + 13));\n }\n newWord = newWord.join(\"\");\n return newWord;\n}", "function evaluateGuess(letter) {\n var positions = [];\n\n for (let i = 0; i < selectableWords[currentWordIndex].length; i++) {\n if (selectableWords[currentWordIndex][i] === letter) {\n positions.push(i);\n }\n }\n if (positions.length <= 0) {\n remainingGuesses--;\n } else {\n for (let i = 0; i < positions.length; i++) {\n guessingWord[positions[i]] = letter;\n }\n }\n}", "function lettersToGuess() {\n var toGuess = 0;\n for (i in progressWord) {\n if (progressWord[i] === \"_\")\n toGuess++;\n }\n return toGuess;\n }", "function letterOccurences(str, letter) {\n\n let totalOcurences = 0;\n for(let i = 0; i < str; i++) {\n if(str[i] == letter) totalOcurences++; \n }\n\n return totalOcurences;\n\n}", "function findIndex(letter,word){\n\tvar indexArray = [];\n\tfor(var i = 0; i < word.length; i++){\n\t\tif ( letter === word[i]){\n\t\t\tindexArray.push(i);\n\t\t}\n\t}\n\treturn indexArray;\n}", "function getTheCharacterPosition(name, letter) {\n let characterPosition = name.indexOf(letter);\n return characterPosition;\n}", "function getLetterCounts(board) {\n const count = {X: 0, O: 0};\n board.forEach(function(ele) {\n if (ele === 'X') {\n count.X ++;\n }\n else if (ele === 'O') {\n count.O ++;\n }\n });\n return count;\n}", "function countOcurrences(string,letter){\n let letter_number = 0\n for( let position = 0; position < string.length; position++){\n if(string.charAt(position) == letter){\n letter_number += 1;\n }\n }\n return letter_number\n}", "function getIndexOfLetterA(string){\n var indexArray = [];\n for(var i = 0; i <= string.length - 1; i++) {\n if (string[i] === \"a\") {\n // console.log(string[i], i);\n // console.log(string.indexOf(string[i]));\n // indexArray.push(string.indexOf(string[i]));\n indexArray.push(i);\n } \n }\n return indexArray;\n}", "function buildCharMap(str){\n const charMap={}\n for(let char of str){\n charMap[char] = charMap[char]+1 || 1\n }\n return charMap\n}", "function sol(chars) {\n let indexRes = 0;\n let index = 0;\n while (index < chars.length) {\n const cur = chars[index];\n let count = 1;\n while (index + 1 < chars.length && chars[index + 1] === cur) {\n index++;\n count++;\n }\n chars[indexRes] = cur;\n indexRes++;\n index++;\n if (count === 1) continue;\n for (let c of String(count).split(\"\")) {\n chars[indexRes] = c;\n indexRes++;\n }\n }\n return indexRes;\n}", "getLettersToBeGuessed() {\r\n let uniqueLetters = new Array();\r\n for (let i = 0; i < this.text.length; i++) {\r\n if (!uniqueLetters.includes(this.text.charAt(i)) && Utilities.alphabet.includes(this.text.charAt(i).toLowerCase())) {\r\n uniqueLetters.push(this.text.charAt(i));\r\n }\r\n }\r\n uniqueLetters.sort();\r\n return uniqueLetters;\r\n }", "function sherlockAndAnagrams(s) {\n \n var map = new Map();\n var totalCount = 0;\n\n for(var i = 0 ; i < s.length; i++) {\n for(var j=i+1 ; j <= s.length; j++) {\n var SubString = s.substring(i,j);\n\n var chars = [...SubString];\n chars.sort();\n \n SubString = String(chars);\n\n if(map.has(SubString)) {\n var value = map.get(SubString);\n totalCount = totalCount + value;\n\n map.set(SubString, value+1);\n } \n else {\n map.set(SubString, 1);\n }\n }\n }\n return totalCount;\n\n\n}", "function evaluateGuess(letter) {\n // Array to store positions of letters in string\n var positions = [];\n\n // Loop through word finding all instances of guessed letter, store the indicies in an array.\n for (var i = 0; i < villainsList[currentWordIndex].length; i++) {\n if(villainsList[currentWordIndex][i] === letter) {\n positions.push(i);\n }\n }\n\n // if there are no indicies, remove a guess and update the hangman image\n if (positions.length <= 0) {\n remainingGuesses--;\n updateHangmanImage();\n } else {\n // Loop through all the indicies and replace the '_' with a letter.\n for(var i = 0; i < positions.length; i++) {\n guessingWord[positions[i]] = letter;\n }\n }\n}", "function checkGuess(letter) {\n // Array to store letterPosition of letters in string\n var letterPosition = [];\n\n // Loop through word finding all instances of guessed letter, store the indicies in an array.\n for (var i = 0; i < word[randWord].length; i++) {\n if(word[randWord][i] === letter) {\n letterPosition.push(i);\n }\n\n }\n\n // if there are no indicies, remove a guess and update the hangman image\n if (letterPosition.length <= 0) {\n guessesLeft--;\n updateHangmanImage();\n } else {\n // Loop through all the indicies and replace the '_' with a letter.\n for(var i = 0; i < letterPosition.length; i++) {\n wordGuess[letterPosition[i]] = letter;\n \n }\n }\n}", "function letterOccurencesInString(word, letter) {\n let counter = 0;\n for (let a of word) {\n if (a === letter) {\n counter++\n }\n }\n console.log(counter);\n}", "function sameStart(arr, letter) {\n\n}", "function encodeDecodeLetter(char){\r\n var goTo; // this is the positon of the next component to which signal is passed\r\n // goes through input/output rotor 1 2 3 bounces back at reflector and goes back to input/output\r\n for (var i = 0; i < 26; i++) {\r\n if(inOut[i].val == char){\r\n goTo = inOut[i].prev;\r\n }\r\n }\r\n\r\n for (var i = 0; i < 26; i++) {\r\n if(rotor3[i].pos === goTo){\r\n goTo = parseInt(rotor3[i].prev);\r\n break;\r\n }\r\n }\r\n\r\n for (var i = 0; i < 26; i++) {\r\n if(rotor2[i].pos === goTo){\r\n goTo = parseInt(rotor2[i].prev);\r\n break;\r\n }\r\n }\r\n\r\n for (var i = 0; i < 26; i++) {\r\n if(rotor1[i].pos === goTo){\r\n goTo = parseInt(rotor1[i].pos);\r\n break;\r\n }\r\n }\r\n\r\n goTo = reflector[goTo -1].reflects;\r\n\r\n for (i = 0; i < 26; i++) {\r\n if(rotor1[i].pos == goTo){\r\n goTo = rotor1[i].next;\r\n break;\r\n }\r\n }\r\n\r\n for (i = 0; i < 26; i++) {\r\n if(rotor2[i].pos == goTo){\r\n goTo = rotor2[i].next;\r\n break;\r\n }\r\n }\r\n\r\n for (i = 0; i < 26; i++) {\r\n if(rotor3[i].pos == goTo){\r\n goTo = rotor3[i].next;\r\n break;\r\n }\r\n }\r\n\r\n return inOut[goTo -1].val;\r\n}" ]
[ "0.6755013", "0.66422486", "0.6616428", "0.6574098", "0.65410936", "0.65210015", "0.64767396", "0.6461616", "0.6398678", "0.6392144", "0.6272142", "0.6270464", "0.6260817", "0.62469214", "0.622445", "0.61895114", "0.61468196", "0.6142121", "0.6118236", "0.6077209", "0.6074336", "0.60577106", "0.60509056", "0.6035462", "0.6013808", "0.5986602", "0.59714925", "0.59316254", "0.59221935", "0.5886603", "0.5882827", "0.58781826", "0.5872095", "0.58604246", "0.5829713", "0.58080804", "0.5794553", "0.57923794", "0.5773684", "0.57680875", "0.57674825", "0.576125", "0.5743896", "0.5735098", "0.57341826", "0.57283705", "0.5722842", "0.5720203", "0.57180536", "0.57167864", "0.5702958", "0.56957483", "0.56894517", "0.56882983", "0.56874037", "0.5674716", "0.56683666", "0.56629896", "0.5655835", "0.56364733", "0.5629627", "0.5628552", "0.5626921", "0.56229496", "0.5620708", "0.5618206", "0.561495", "0.56110215", "0.5604562", "0.5595055", "0.558209", "0.5579388", "0.5571699", "0.557119", "0.5563126", "0.55433863", "0.55433863", "0.5543171", "0.5538467", "0.55297846", "0.55291754", "0.5528655", "0.552081", "0.54972786", "0.5492862", "0.5491029", "0.5489993", "0.54885805", "0.54878443", "0.5474274", "0.54674923", "0.5467294", "0.5451059", "0.5450788", "0.54472", "0.543858", "0.5427402", "0.54245746", "0.54235864", "0.54199296", "0.540986" ]
0.0
-1
find all repeated sequences
function repeatsfind() {repeats(cipher[which])}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function repeats(arr){\n var arrRepeted = arr.filter ((v,i,a) => a.indexOf(v) < i);\n return arr.filter(el => !(arrRepeted).includes(el)).reduce((a, b) => a + b);\n}", "function isThereRepeted () {\n var repeatedNumbers = []; //Array para ir guardando los repetidos.\n\n for (let i = 0, j, isOnARRAY; i < ARRAY.length-1; i++){\n isOnARRAY = false; // salir antes del While si hay un repetido\n j = i+1; //Mirarmos repetidos a partir de los que ha hemos comprobado.\n if (repeatedNumbers.indexOf (ARRAY[i]) === -1) { //Si el número ya está en los repetidos no hace falta buscarlos ni guardarlo\n while (j < ARRAY.length && isOnARRAY === false){ //Recorremos el array hasta que encontremos repetido o el final del array\n if (ARRAY[i] === ARRAY[j]) { // Si encontramos repetido se guarda y salimos del bucle.\n isOnARRAY = true;\n repeatedNumbers.push(ARRAY[i]);\n } else {\n j++;\n }//end if\n }//end while\n }//end if\n }//end for\n\n return (repeatedNumbers);\n}//end function", "function repeats(arr){\n\nreturn arr\n//I'll filter the elements from the array that follows this condition: arr.indexOf(element) === arr.lastIndexOf(element)\n.filter(element => arr.indexOf(element) === arr.lastIndexOf(element))\n//I will sum all the filtered values\n.reduce((accumulator, currentValue) => accumulator + currentValue)\n\n}", "function findRepeats(integers){\n\n\tconst set = new Set();\n\tconst duplicates = new Set();\n\n\tfor(let i = 0; i < integers.length; i++){\n\t\tif(set.has(integers[i])){\n\t\t\tduplicates.add(integers[i])\n\t\t}\n\n\t\tset.add(integers[i]);\n\t}\n\n\treturn duplicates;\n}", "function repeats (arr) {\n for (let i = 0; i < arr.length; i++) {\n for (let a = i+1; a < arr.length; a++) {\n if (equalArrays(arr[i], arr[a])) {\n return 'repeat';\n }\n }\n }\n return 'no repeat';\n}", "function uniqueInOrder(sequence) {\n let uniques = [];\n const seq = Array.from(sequence);\n for (let i = 0; i < seq.length; i++) {\n if (seq[i] !== seq[i + 1]) {\n uniques.push(seq[i])\n }\n }\n return uniques\n}", "function repeatedFind (str) {\n\t\tconst repeated = str.match(/(.)\\1+/gi);//. any character, \\1 match the first parenthesized pattern \n\t\treturn repeated; \n\t}", "function repeatedOnlyOnce(array) {\n \n}", "function findUniques(a){\n let result = []\n for (num of a){\n let match = false;\n for (unum of result){\n if (num == unum){\n match = true;\n }\n }\n if (!match){\n result.push(num);\n }\n }\n return result;\n}", "function func(array) {\n let length = array.length;\n let counter = 0;\n let repeatedArray = [], result = [];\n for (let i = 0; i < length; i++) {\n if (array[i] > 0) {\n repeatedArray = array.slice(i+1);\n counter = array[i];\n break;\n }\n }\n if (counter === 0) {\n return [];\n } else if (repeatedArray.length === 0) {\n return `[empty x ${counter}]`\n }\n\n for (let i = 0; i < counter; i++) {\n if (repeatedArray[i]) {\n result.push(repeatedArray[i])\n } else {\n result.push(repeatedArray[i%repeatedArray.length])\n }\n }\n return result\n}", "function reoccurring(arr){\n\tfor(let i = 0; i < arr.length; i++){\n\t\tfor(j = i+1; j < arr.length; j++){\n\t\t\tif(arr[i] === arr[j]){\n\t\t\t\treturn arr[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined\n} // O(n^2)", "repeat_match(password) {\n const matches = [];\n const greedy = /(.+)\\1+/g;\n const lazy = /(.+?)\\1+/g;\n const lazy_anchored = /^(.+?)\\1+$/;\n let lastIndex = 0;\n while (lastIndex < password.length) {\n var base_token, match;\n greedy.lastIndex = (lazy.lastIndex = lastIndex);\n const greedy_match = greedy.exec(password);\n const lazy_match = lazy.exec(password);\n if (greedy_match == null) {\n break;\n }\n if (greedy_match[0].length > lazy_match[0].length) {\n // greedy beats lazy for 'aabaab'\n // greedy: [aabaab, aab]\n // lazy: [aa, a]\n match = greedy_match;\n // greedy's repeated string might itself be repeated, eg.\n // aabaab in aabaabaabaab.\n // run an anchored lazy match on greedy's repeated string\n // to find the shortest repeated string\n base_token = lazy_anchored.exec(match[0])[1];\n } else {\n // lazy beats greedy for 'aaaaa'\n // greedy: [aaaa, aa]\n // lazy: [aaaaa, a]\n match = lazy_match;\n base_token = match[1];\n }\n const [i, j] = Array.from([match.index, (match.index + match[0].length) - 1]);\n // recursively match and score the base string\n const base_analysis = scoring.most_guessable_match_sequence(\n base_token,\n this.omnimatch(base_token)\n );\n const base_matches = base_analysis.sequence;\n const base_guesses = base_analysis.guesses;\n matches.push({\n pattern: 'repeat',\n i,\n j,\n token: match[0],\n base_token,\n base_guesses,\n base_matches,\n repeat_count: match[0].length / base_token.length\n });\n lastIndex = j + 1;\n }\n return matches;\n }", "function repeatedSubstringPatterm(string) {\n let subStr = '';\n\n for (let i = 1; i < string.length; i += 1) {\n subStr = string.slice(0, i);\n let substrings = [];\n [...string].reduce((str, char) => {\n if (str !== subStr) {\n str += char;\n } else {\n substrings.push(str)\n str = ''\n str += char;\n }\n\n return str;\n }, '');\n\n let regex = new RegExp(subStr, 'g')\n if (substrings.every(word => word === subStr)) {\n let array = [subStr, string.match(regex).length];\n console.log(array);\n return array;\n }\n\n return [string, 1];\n }\n}", "function allCombinations (a) {\n var poss = 0;\n for (var i = 1; i <= a; i++) {\n for (var j = 1; j <= a; j++) {\n if (i !== j) {\n poss++;\n console.log (i, j);\n }\n }\n }\n return poss;\n}", "function consecutive(array) {\n var newarray = []\n for(var i =0; i<array.length; i++){\n // console.log(array[0])\n if(array[i] == array[i+1]) {\n // console.log(array[i])\n return true\n }\n }\n return false\n}", "static cycle(repeated) {\n return new Seq(function* () {\n while (true)\n yield* repeated;\n });\n }", "function findRepeats1(integers){\n\t// sort array in place. Takes O(n log n) time and O(1) space\n\tintegers.sort((a, b) => {\n\t\treturn a - b;\n\t});\n\n\tfor(let i = 0; i < integers.length; i++){\n\t\tif(integers[i] === integers[i - 1]){\n\t\t\treturn integers[i];\n\t\t}\n\t}\n\n\treturn 'Error no duplicates';\n}", "function repeat(arr) {\n\tfor (let i = 0; i < arr.length; i++) {\n\t\tfor (let j = i + 1; j < arr.length; j++) {\n\t\t\tif (arr[i] === arr[j]) {\n\t\t\t\treturn arr[i];\n\t\t\t}\n\t\t}\n\t}\n\treturn undefined;\n}", "function subsequences(xs){\r\n return cons([], nonEmptySubsequences(xs));\r\n}", "function removePossibleDuplicates(matchesFound, sequences, numMatchesSeq) {\n \n const unique = (value, index, self) => {\n return self.indexOf(value) === index\n }\n\n sequences.forEach(seq => {\n\n for (let i = 0; i < matchesFound[seq].length; i++) {\n\n for (let j = i + 1; j < matchesFound[seq].length; j++) {\n // join the results to make it easier compare them\n let merge = matchesFound[seq][i].concat(matchesFound[seq][j]);\n\n // remove duplicated values. Ideally, the size of the filtered sequence is the size of the 2 concatenated arrays - 1 (the origin)\n let filter = merge.filter(unique);\n\n // if the filtered array has less positions than the 2 arrays combined minus the shared node, it's a duplicated match\n if (filter.length < (2 * seq.length - 1)) {\n numMatchesSeq--;\n }\n }\n }\n\n });\n\n return numMatchesSeq;\n}", "function noRepeats(str) {\n let arr = [];\n for(let i = 0; i < str.length; i++) {\n if(arr.includes(str[i])) {\n return false\n }else if(!arr.includes(str[i])) {\n arr.push(str[i]);\n }\n }\n return true;\n }", "function repeats(arr){\n\n return arr\n //I'll map thru the array in order to get rid of repeated elements. A new array (unnamed) is created inside the function.\n //The unnamed array contains the elements that passed the terciary operator condition.\n //The result is an array with unique values and zeros.\n .map((element, index, array) => { return array.indexOf(element) === array.lastIndexOf(element) ? element : 0 })\n //I will sum all the unique values and the zeros from the unnamed array using reduce.\n //In arrow functions with simple syntax we don't need return.\n .reduce((accumulator, currentValue) => accumulator + currentValue)\n \n}", "function duplicates(arr) {\n let result = []\n for(let i = 0; i < arr.length; i++) {\n if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i]) && \n !result.includes(arr[i])) {\n result.push(arr[i])\n }\n }\n return result;\n}", "function firstNonRepeating(str) {\n const repeating = new Set();\n let firsts = new Set();\n for (let char of str) {\n if (!repeating.has(char)) {\n firsts.add(char);\n repeating.add(char);\n } else firsts.delete(char);\n }\n console.log(firsts);\n return Array.from(firsts.values())[0];\n}", "function duplicates(arr) {\n var dupe = [];\n for (var i = 0; i < arr.length; i++) {\n var n = arr[i];\n if (arr.indexOf(n, i + 1) >= 0 && dupe.indexOf(n) < 0) {\n dupe.push(n);\n }\n }\n\n return dupe;\n}", "function findRepeats(arr) {\n // -------------------- Your Code Here --------------------\n\n // create an object to keep track of how many times we've seen words\n var words = {};\n\n // create the array we're going to be returning\n var repeated = [];\n\n // iterate through the argument\n for (var i=0; i<arr.length; i++) {\n\n // if we've already encountered the current word, increment the count of \n // of the number of times we've seen the word\n if (words.hasOwnProperty(arr[i])){\n words[arr[i]]++;\n\n // the first time we encounter the word again (count is 2), we add it to\n // the output array\n if (words[arr[i]] === 2) {\n repeated.push(arr[i]);\n }\n } else {\n\n // if this is our first time seeing the word, add it to the object with a\n // count of 1\n words[arr[i]] = 1;\n }\n }\n\n // sort the array and return it\n return repeated.sort();\n\n // --------------------- End Code Area --------------------\n}", "function allRepeats() { \n for (var i = 1; i < str.length; i++) {\n if (str.charAt(i) === first) {\n return 0;\n }\n }\n }", "function allRepeats() { \n for (var i = 1; i < str.length; i++) {\n if (str.charAt(i) === first) {\n return 0;\n }\n }\n }", "function allNonConsecutive(num){\n output = [];\n for(i = 0; i < num.length -1; i++){\n if(num[i] +1 !== num[i +1]){\n output.push({'idx': i+1, 'num': num[i+1]});\n }\n }\n return output;\n}", "function getSrepeatCount() {\r\n srepeat_examples = [];\r\n srepeats_for_sentences = [];\r\n result = [];\r\n for(i=0; i<sentences.length; i++) {\r\n sentence = [];\r\n sentence = sentences[i].replace(/[^a-zA-Zа-яА-ЯёЁ \\n']/g, \" \");\r\n sentence = sentence.replace(/\\s+/g, \" \");\r\n sentence = sentence.toLowerCase();\r\n sentence = sentence.substring(0,sentence.length-1);\r\n sentence = sentence.split(\" \");\r\n \r\n sub_result = sentence.reduce(function (acc, el) {\r\n acc[el] = (acc[el] || 0) + 1;\r\n return acc;\r\n }, {});\r\n\r\n tmp = [];\r\n for(key in sub_result) {\r\n if(sub_result[key] > 1 && unions.indexOf(key) == -1 && prepositions.indexOf(key) == -1) {\r\n tmp.push(key);\r\n result.push(key);\r\n }\r\n }\r\n srepeat_examples.push([sentences[i], tmp]);\r\n }\r\n tmp = []\r\n for(key in srepeat_examples) {\r\n tmp = []\r\n for(i=0; i<srepeat_examples[key][1].length; i++){\r\n if(srepeat_examples[key][1].length != 0) {\r\n if(srepeat_examples[key][1][i] != \"'\" || srepeat_examples[key][1][i] == \"i\") {\r\n tmp.push(srepeat_examples[key][1][i])\r\n }\r\n }\r\n }\r\n srepeat_examples[key][1] = tmp;\r\n }\r\n\r\n count = 0;\r\n for(i=0; i<srepeat_examples.length; i++) {\r\n if(srepeat_examples[i][1].length != 0) {\r\n for(j=0; j<srepeat_examples[i][1].length; j++) {\r\n count++;\r\n }\r\n }\r\n }\r\n\r\n return count;\r\n}", "function repeatedCharacter(find) {\n for(let i = 0; i <= find.length; i++){\n for(let m = i+1; m <= find.length; m++){\n if(find[m] === find[i]){\n return find[i].repeat(1);\n }\n }\n }\nreturn false;\n}", "function findDuplicate(frequencies) {\n const set = new Set()\n let sum = 0\n let i = 0\n\n while (true) {\n sum += format[i]\n if (set.has(sum)) {\n return sum\n }\n set.add(sum)\n i++\n if (i === format.length - 1) {\n i = 0\n }\n }\n}", "function checkSequence(arr) {\n const uniques = [arr[0]];\n\n function readRandoms() {\n const positionToCheck = uniques[uniques.length - 1];\n const nextRandomNum = arr[positionToCheck];\n const alreadyCheckedThisIndex = uniques.includes(nextRandomNum);\n\n if (alreadyCheckedThisIndex) {\n return uniques.length;\n }\n\n uniques.push(nextRandomNum);\n return readRandoms();\n }\n return readRandoms();\n}", "get unique() {\n const self = this;\n return new Seq(function* () {\n const u = new Set();\n for (const element of self) {\n if (!u.has(element)) {\n u.add(element);\n yield element;\n }\n }\n });\n }", "function repeatsFor(index, row, col) {\n\t\tvar r = new Array();\n\t\t\n\t\tvar directions = new Array(\n\t\t\tnew Array(0, 1), // right\n\t\t\tnew Array(1, 1), // right-down\n\t\t\tnew Array(1, 0), // down\n\t\t\tnew Array(1, -1), // left-down\n\t\t\tnew Array(0, -1), // left\n\t\t\tnew Array(-1, -1), // left-up\n\t\t\tnew Array(-1, 0), // up\n\t\t\tnew Array(-1, 1) // right-up\n\t\t);\n\t\t\n\t\t/* inspect each direction */\n\t\tvar key = get(row, col);\n\t\tvar candidates = index[key];\n\t\tif (candidates) {\n\t\t\tfor (var c=0; c<candidates.length; c++) {\n\t\t\t\tfor (var i=0; i<directions.length; i++) {\n\t\t\t\t\tfor (var j=0; j<directions.length; j++) {\n\t\t\t\t\t\tvar result = new Array();\n\t\t\t\t\t\tresult[0] = \"\";\n\t\t\t\t\t\tresult[1] = new Array();\n\t\t\t\t\t\tresult[2] = new Array(); \n\n\t\t\t\t\t\tif (row == candidates[c][0] && col == candidates[c][1] && i==j ) {\n\t\t\t\t\t\t\t; // do nothing, because we don't want to match the sequence at (row,col) with itself. \n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmatches(result, row, col, directions[i][0], directions[i][1], candidates[c][0], candidates[c][1], directions[j][0], directions[j][1]);\n\t\t\t\t\t\t\tr[r.length] = new Array(result[0], result[1], result[2], i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\t \n\t\treturn r;\n\t}", "function repeatsFor(index, row, col) {\n\t\tvar r = new Array();\n\t\t\n\t\tvar directions = new Array(\n\t\t\tnew Array(0, 1), // right\n\t\t\tnew Array(1, 1), // right-down\n\t\t\tnew Array(1, 0), // down\n\t\t\tnew Array(1, -1), // left-down\n\t\t\tnew Array(0, -1), // left\n\t\t\tnew Array(-1, -1), // left-up\n\t\t\tnew Array(-1, 0), // up\n\t\t\tnew Array(-1, 1) // right-up\n\t\t);\n\t\t\n\t\t/* inspect each direction */\n\t\tvar key = get(row, col);\n\t\tvar candidates = index[key];\n\t\tif (candidates) {\n\t\t\tfor (var c=0; c<candidates.length; c++) {\n\t\t\t\tfor (var i=0; i<directions.length; i++) {\n\t\t\t\t\tfor (var j=0; j<directions.length; j++) {\n\t\t\t\t\t\tvar result = new Array();\n\t\t\t\t\t\tresult[0] = \"\";\n\t\t\t\t\t\tresult[1] = new Array();\n\t\t\t\t\t\tresult[2] = new Array(); \n\n\t\t\t\t\t\tif (row == candidates[c][0] && col == candidates[c][1] && i==j ) {\n\t\t\t\t\t\t\t; // do nothing, because we don't want to match the sequence at (row,col) with itself. \n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tmatches(result, row, col, directions[i][0], directions[i][1], candidates[c][0], candidates[c][1], directions[j][0], directions[j][1]);\n\t\t\t\t\t\t\tr[r.length] = new Array(result[0], result[1], result[2], i, j);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} \n\n\t\t \n\t\treturn r;\n\t}", "function findIncreasingSequences2(arr) {\n if (arr.length === 1) return 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] < arr[i - 1]) {\n return 1 + findIncreasingSequences(arr.slice(i + 1));\n }\n }\n}", "function array_remove_repeat(a) {\n // 去重\n var r = [];\n for (var i = 0; i < a.length; i++) {\n var flag = true;\n var temp = a[i];\n for (var j = 0; j < r.length; j++) {\n if (temp === r[j]) {\n flag = false;\n break;\n }\n }\n if (flag) {\n r.push(temp);\n }\n }\n return r;\n}", "function printDuplicateNumber(arr) {\n var i, j;\n for (i = 0; i < arr.length; i++) {\n for (j = i + 1; j < arr.length; j++) {\n if (arr[i] === arr[j])\n document.write(\"Repeated Elements are :\" + arr[i] + \"<br>\");\n }\n }\n}", "function subsetsWithDups2( nums ) {\n nums.sort( ( a, b ) => a - b ); // Sort for duplicate checking\n\n const backtrack = ( subsets, partial, offset ) => {\n const completeSubset = Array.prototype.concat.call( partial );\n subsets.push( completeSubset );\n for ( let i = offset; i < nums.length; i++ ) {\n if ( i > offset && nums[i] === nums[i-1] ) {\n continue;\n }\n partial.push( nums[i] );\n backtrack( subsets, partial, i+1 );\n partial.pop();\n }\n return subsets;\n };\n\n return backtrack( [], [], 0 );\n}", "function contiguousSeq(arr) {\n\n}", "function inicioDaSeq(letras){ //verifica qual a posição no array do alfabeto que começa a sequencia de letras \n let inicio;\n for(let i=0; i<alfabeto.length; i++){\n if(alfabeto[i]==letras[0]) //verifica o primeiro elemento da sequência de letras com cada elemento do alfabeto\n inicio=i;\n }\n return inicio;\n}", "function solution(a) {\r\n // write your code in JavaScript (Node.js 0.12)\r\n var i, l=a.length-1;\r\n var arr=[];\r\n do{ \r\n arr[a[l]-1] = a[l];\r\n \r\n l--; \r\n if(l===0)\r\n for(j=0;j<arr.length;j++)\r\n if(!arr[j])\r\n return j+1;\r\n \r\n }while(l>=0)\r\n}", "function findSequence (n, start) {\n const result = [];\n let count = start;\n\n while (result.length < n) {\n const digitsSum = `${count}`.split('').reduce((acc, item) => acc + parseInt(item), 0);\n\n if (count % digitsSum === 0) result.push(count);\n\n count++;\n }\n\n return result;\n}", "function checkRepeats() {\n var v_ctr;\n for (v_ctr=0; v_ctr<7; v_ctr++) {\n/* console.log(\"340 [\" + v_ctr + \"] [\" +\n a_scaleNotes[v_ctr].substr(0,1) + \"] [\" +\n a_scaleNotes[(v_ctr + 1) % 7].substr(0,1) + \"]\");\n*/\n if (a_scaleNotes[v_ctr].substr(0,1) == a_scaleNotes[(v_ctr + 1) % 7].substr(0,1))\n return true;\n }\n return false;\n}", "function fL(a){var i,l,ret=[]\n for(i=0,l=a.length;i<l;){\n ret.push(a[i])\n while(a[i]+1 == a[++i] && i<l);\n if(a[i-1]!==0x10ffff)ret.push(a[i-1]+1)}\n return ret}", "function longestConsecutive(nums) {\n \n if(nums.length === 0) return 0;\n if(nums.length === 1) return 1;\n\n let longestConsecutiveSequenceNumber = [[]];\n let indexOfElement = 0;\n let maxLength = 0;\n \n nums = nums.sort((a,b) => a-b);\n noDuplicateNums = [];\n noDuplicateNums.push(nums[0]);\n\n for(let i = 1; i < nums.length; i++){\n if(nums[i - 1] !== nums[i]) {\n noDuplicateNums.push(nums[i]);\n }\n }\n\n longestConsecutiveSequenceNumber[0].push(noDuplicateNums[0]);\n \n for(let i = 1; i < noDuplicateNums.length; i++) {\n if(noDuplicateNums[i-1] + 1 !== noDuplicateNums[i]) {\n indexOfElement++;\n longestConsecutiveSequenceNumber.push([]);\n }\n longestConsecutiveSequenceNumber[indexOfElement].push(noDuplicateNums[i]);\n }\n \n longestConsecutiveSequenceNumber.forEach((seq) => {\n if (seq.length > maxLength) {\n maxLength = seq.length;\n };\n });\n \n return maxLength;\n}", "function findDuplicate(arr) {\n \n \n}", "function almostIncreasingSequence2(sequence) {\n var counter = 0\n var length = sequence.length\n const flag = false\n for (var i = 0; i < length - 1; i++)\n {\n if (sequence[i] == sequence[i+1]){\n \n counter++\n }\n if (sequence[i] > sequence[i+1])\n {\n counter++\n console.log(sequence.splice(i,1))\n if (counter == 1)\n {\n sequence.slice(i,1)\n if (sequence[i] > sequence[i+1])\n {\n counter++\n \n }\n }\n \n }\n }\n if (counter < 2)\n {\n return true;\n }\n else {\n return false\n }\n \n \n}", "function consecutive(array) {\n var newarray = []\n for(var i =0; i<array.length; i++){\n // console.log(array[0])\n if(array[i] == array[i+1]) {\n // console.log(array[i])\n // return true\n newarray.push(array[i])\n // console.log(newarray)\n }\n // console.log(newarray)\n }\n var sum = 0;\n for(var j=0; j<newarray.length; j++){\n // console.log(newarray[j])\n sum += newarray[j]\n // console.log(sum)\n }\n return sum\n }", "function getAltMaisRepetida(arrayAlt){\n var arrayAux = [];\n var arrayRepet = [];\n var arrayOcorrency = []; // Armazena o objeto ocorrency, onde o primeiro elemento é a alternativa e o segundo a sua ocorrência.\n \n // for i: Adiciona os números existentes do arrayAlt no arrayAux sem repetições\n for(var i = 0; i < arrayAlt.length; i++){\n if(arrayAux.length >= 1){\n var flag = false; // Para sinalizar, caso o dado elemento já exista na lista\n // Verifica se no arrayAux existe dado elemento, impossibilitando repetições\n for(var j = 0; j < arrayAux.length; j++){\n if(arrayAux[j] == arrayAlt[i]){ // Se o elemento já está na lista\n flag = true; // Sinaliza\n }\n }\n if(flag == false){ // Se estiver sinalizado(flag = true) não entra\n arrayAux.push(arrayAlt[i]);\n }\n } else {\n arrayAux.push(arrayAlt[i]);\n }\n } // fim for i\n \n // O elemento k do arrayAux terá n repetições no arrayAlt, o número de repetições, cont, será o contador da ocorrência de dada alternativa\n // no mesmo índice que o elemento k possui no arrayAux. Ex.: arrayAux = [A,B] arrayAlt = [A,A,B,B,B] arrayRepet = [2, 3]\n var cont = 0;\n for(var k = 0; k < arrayAux.length; k++){\n for(var l = 0; l < arrayAlt.length; l++){\n if(arrayAux[k] == arrayAlt[l]){\n cont++; // Quantidade de vezes que a alternativa se repete\n }\n } // fim for l\n \n var ocorrency = {\n 'alternativa': arrayAux[k],\n 'valor': cont\n };\n arrayOcorrency.push(ocorrency); // Adiciona o objeto ocorrency no arrayOcorrency\n \n arrayRepet.push(cont);\n cont = 0;\n } // fim for k\n \n // var maior = arrayOcorrency[0][1]; // Assume que o primeiro elemento é o maior\n var maior = arrayOcorrency[0].valor;\n var indice = 0; // guarda o índice do primeiro elemento\n for(var m = 1; m < arrayOcorrency.length; m++){\n if(arrayOcorrency[m].valor > maior){ // Se o próximo elemento for maior que o anterior(maior)\n maior = arrayOcorrency[m].valor; // Atualiza o valor de maior\n indice = m; // Atualiza o índice\n } \n }\n return arrayOcorrency;\n}", "function findDuplicates(input) {\n\t\t// TODO: Fix this.\n\t\t// eslint-disable-next-line unicorn/no-array-reduce\n\t\treturn input.reduce((accumulator, element, index, array) => {\n\t\t\tif (array.indexOf(element) !== index && !accumulator.includes(element)) {\n\t\t\t\taccumulator.push(element);\n\t\t\t}\n\n\t\t\treturn accumulator;\n\t\t}, []);\n\t}", "function dropRepeats(s) {\n var prev = sentinel;\n return s.map(function (x) {\n var cur = prev;\n prev = x;\n return cur === x ? Stream.SKIP : x;\n });\n}", "function arrayMode(sequence) {\n let uniqueNumbers = sequence.filter((num, i) => sequence.indexOf(num) === i);\n let numOccurrences = [];\n \n for(let i = 0; i < uniqueNumbers.length; i++) {\n numOccurrences.push(sequence.filter(num => num === uniqueNumbers[i]).length);\n }\n return uniqueNumbers[numOccurrences.indexOf(Math.max(...numOccurrences))];\n}", "function consecutiveDuplicates(inpt)\r\n{\r\n\t finalOutput=\"( \";\r\n\tfor(var i=0;i<inpt.length;i++)\r\n\t{\r\n\t\tvar temp=inpt.charAt(i);\r\n\t\tif(temp==inpt.charAt(i+1))\r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(temp);\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(temp);\r\n\t\t\tfinalOutput=finalOutput.concat(\" ) (\");\r\n\t\t}\r\n\t}\r\n\tvar len1=finalOutput.length;\r\n\tdocument.write(finalOutput.slice(0,len1-1));\r\n}", "function longestRepetition(s) {\n //console.log(s)\n var i = 0,\n seq = 0,\n results = [];\n \n if ( s === ('')){\n return ['', 0]\n }\n \n for(let i=0; i<s.length; i++) {\n var current = s[i],\n next = s[i + 1];\n \n if (typeof results[seq] === 'undefined') {\n results[seq] = [current, 0];\n }\n \n results[seq][1]++;\n \n if (current !== next) {\n seq++;\n }\n }\n \n return results.sort((a, b) => b[1] - a[1])[0];\n }", "function combinationWithRepetition(items, r) {\n const result = permutationWithRepetition(items, r);\n for (let i = result.length - 1; i > 0; i--) {\n for (let j = i - 1; j >= 0; j--) {\n if (isEqualComb(result[i], result[j])) {\n result.splice(i, 1);\n break;\n }\n }\n }\n return result;\n}", "function sumOfConsecutivePositiveIntegers(input) {\n //Total number of sequences to return\n let sequences = [];\n //Iterate up to input integer\n for (let i = 1; i < input; i++) {\n //Track current sequence\n let currentSequence = [];\n //Set sum to 0 since we're starting from 1\n let sum = 0;\n //Iterate up to input to figure out if current sequence is a valid sequence\n for (let j = i; j < input; j++) {\n //Add each integer to sum\n sum += j;\n //Push the integer to the current sequence\n currentSequence.push(j);\n //If sum is greater than input, then break\n if (sum > input) {\n break;\n //If sum is equal to input, return current sequence\n } else if (sum === input) {\n sequences.push(currentSequence);\n break;\n }\n //Assume that if sum is less than input, we keep iterating for the current sequence\n //We only push sequence if sum === input, so if it's under or over, we won't see that sequence in our result\n }\n }\n if (sequences.length === 0) {\n console.log('Error! No sequences!');\n } else {\n console.log(sequences);\n }\n}", "function solution(s) {\n return Array.from(new Set(s))\n}", "function findRepeatingCharacters(input) {\n const regex = /([^])(?=\\1)/g;\n return input.match(regex);\n}", "function firstRecurring(arr) {\n const repeats = new Set();\n for (let i = 0; i < arr.length; i++) {\n if (!repeats.has(arr[i])) {\n repeats.add(arr[i]);\n } else {\n return arr[i];\n }\n }\n return null;\n}", "function evaluation_get_sequence(group_by, sequence) {\n return _.map(\n sequence[0],\n function(first_index) {\n return _.filter(\n $.map(\n sequence[1],\n function(second_index) {\n return index_get_tile([\n group_by == 1 ? second_index : first_index,\n group_by == 1 ? first_index : second_index\n ])\n }),\n function(item) {\n return $(item).length > 0\n })\n })\n}", "function hasDuplicates(array) {\n let ticks = 0, result = false;\n for (let i = 0; i < array.length; i++) {\n ticks++;\n for (let j = 0; j < array.length; j++) {\n ticks++;\n if (array[i] === array[j] && i !== j) {\n result = true;\n }\n }\n }\n return {\n result: result,\n ticks: ticks\n };\n}", "function checkDups(alphabet) {\n count = 0; \n for (i = 0; i < alphabet.length; i++){\n for (j = 0; j < alphabet.length; j++){\n if (alphabet[i] === alphabet[j] && i != j) {\n return true;\n }\n }\n }\n }", "function allNonConsecutive(arr) {\n var newArr=[];\n \n for(var i=1;i<arr.length;i++){ \n if(arr[i] != arr[i+1]-1){ \n var nonConsecutive = {\n i:i+1,\n n:arr[i+1]\n };\n // nonConsecutive.i=i\n // nonConsecutive.n=arr[i]\n newArr.push(nonConsecutive);\n \n }\n }\n newArr.pop();\n return newArr;\n }", "function howManyRepeated(str){\n let sum = 0;\n const strArr = str.toLowerCase().split(\"\").sort().join(\"\").match(/(.)\\1+/g);\n return strArr;\n}", "function reg2(s) {\n let good = s.split(`\\n`).filter( e => {\n let pair = /(..)(?:.*)\\1/g.test(e);\n let repeat = /(.)(?:.)\\1/g.test(e);\n return pair && repeat;\n }).length;\n console.log(good);\n}", "function permutationsWithDupes(\n str,\n prefix = \"\",\n result = [],\n perms = new Set()\n) {}", "function findRepeat(numbers) {\n\n let floor = 1;\n let ceiling = numbers.length - 1;\n\n while (floor < ceiling) {\n\n // Divide our range 1..n into an upper range and lower range\n // (such that they don't overlap)\n // lower range is floor..midpoint\n // upper range is midpoint+1..ceiling\n const midpoint = Math.floor(floor + ((ceiling - floor) / 2));\n const lowerRangeFloor = floor;\n const lowerRangeCeiling = midpoint;\n const upperRangeFloor = midpoint + 1;\n const upperRangeCeiling = ceiling;\n\n const distinctPossibleIntegersInLowerRange = lowerRangeCeiling - lowerRangeFloor + 1;\n\n // Count number of items in lower range\n let itemsInLowerRange = 0;\n numbers.forEach(item => {\n\n // Is it in the lower range?\n if (item >= lowerRangeFloor && item <= lowerRangeCeiling) {\n itemsInLowerRange += 1;\n }\n });\n\n if (itemsInLowerRange > distinctPossibleIntegersInLowerRange) {\n\n // There must be a duplicate in the lower range\n // so use the same approach iteratively on that range\n floor = lowerRangeFloor;\n ceiling = lowerRangeCeiling;\n } else {\n\n // There must be a duplicate in the upper range\n // so use the same approach iteratively on that range\n floor = upperRangeFloor;\n ceiling = upperRangeCeiling;\n }\n }\n\n // Floor and ceiling have converged\n // We found a number that repeats!\n return floor;\n}", "function solution(A) {\n var terms = A.length;\n var match = 1;\n var prefix = \"\";\n while (match == 1) {\n for (var c = 0; c < 100; c++) {\n for (var i = 0; i < terms-1; i++) {\n if (A[i][c] != A[i+1][c]) {\n match = 0 \n }\n } \n }\n }\n return prefix;\n}", "function firstNonRepeat(n) {\n var map = {};\n for (var i = 0; i < n.length; i++) {\n //loop through and append\n append(n[i], i);\n }\n\n //check results, return first non repeat\n for(key in map) {\n if (map[key].count == 1) {\n return key;\n }\n }\n\n //utility function\n function append(c, i) {\n if (map[c] != null) {\n map[c].count++;\n } else {\n map[c] = {'index': i, 'count': 1};\n }\n }\n}", "function searchSequences(dna, sequences) {\n\n var numMatchesSeq = 0;\n // store the positions of the letters that were matched\n var matchesFound = [];\n sequences.forEach(seq => {\n matchesFound[seq] = [];\n });\n \n // go through all the sequences\n sequences.forEach(seq => {\n for (let r = 0; r < dna.length; r++) {\n for (let c = 0; c < dna.length; c++) {\n numMatchesSeq += searchOnDnaMatrix(dna, seq, r, c, matchesFound);\n }\n }\n });\n\n // if a sequence on the dna matrix is longer than the sequence to be matched, it will be duplicated. Let's fix that.\n numMatchesSeq = removePossibleDuplicates(matchesFound, sequences, numMatchesSeq);\n\n return numMatchesSeq;\n}", "function isValidSubsequence(array, sequence) {\r\n let i = 0; // índice da sequencia\r\n // varro o array de entrada\r\n for (const a of array) {\r\n // se encontrei \r\n if (a === sequence[i]) {\r\n // avanço para procurar o próximo na sequencia\r\n i += 1;\r\n }\r\n // se avacei na sequencia até o fim\r\n if (i === sequence.length) {\r\n // todos os números foram encontrados\r\n return true;\r\n }\r\n }\r\n return false;\r\n}", "function combine() {\n let arr = [].concat.apply([], arguments); //[1, 2, 2, 2, 3, 3]没有去重复的新数组 \n return Array.from(new Set(arr));//new Set(arr): Set(3) {1, 2, 3}\n}", "function findLongestRepeatingSubSeq(str) {\n let n = str.length;\n\n let dp = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n dp[i] = new Array(n + 1);\n for (let j = 0; j <= n; j++) dp[i][j] = 0;\n }\n\n // now use LCS function\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= n; j++) {\n if (str[i - 1] === str[j - 1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1];\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n return dp[n][n];\n}", "function groupsOf(n, seq, includeIncomplete = true) {\n let o = [], len = seq.length;\n let preferedLen = (includeIncomplete ? Math.floor : Math.ceil)(seq.length /\n n);\n\n o.length = preferedLen;\n\n for (let i = 0; i < preferedLen; ++i) {\n let g = [];\n o[i] = g;\n\n for (let j = 0; j < n; ++j) {\n let seqIdx = i * n + j;\n // stop if over the end\n if (seqIdx >= len) {\n break;\n }\n g.push(seq[seqIdx]);\n }\n }\n\n return o;\n}", "function makeThreeUnique() {\n console.log(justViewed, 'just viewed in line 59');\n var output = [];\n console.log(output);\n\n // makes first element\n var firstNum = makeRandom();\n // handles duplicates from last set of 3\n while (justViewed.includes(firstNum)) {\n firstNum = makeRandom(); // makes first again\n }\n // pushes to first num\n output.push(firstNum);\n\n // need to generate second element\n var secondNum = makeRandom();\n // if it matches 1st, \n while (output[0] === secondNum || justViewed.includes(secondNum)) {\n console.log('duplicate detected on second');\n // reroll\n secondNum = makeRandom();\n }\n output.push(secondNum);\n\n // generate 3rd number\n var thirdNum = makeRandom();\n // if it matches... \n while (output[0] === thirdNum || output[1] === thirdNum || justViewed.includes(thirdNum)) {\n console.log('duplicate detected on third');\n // reroll\n thirdNum = makeRandom();\n }\n output.push(thirdNum);\n\n justViewed = output;\n return output;\n}", "function allSequences(node) {\n\tconst result = [];\n\n\tif (!node) {\n\t\tresult.push([]);\n\t\treturn result;\n\t}\n\n\tconst weaved = [node.value];\n\n\tconst leftSeq = allSequences(node.left);\n\tconst rightSeq = allSequences(node.right);\n\n\tleftSeq.forEach(left => {\n\t\trightSeq.forEach(right =>{\n\t\t\tweave(left, right, weaved, result);\n\t\t})\n\t})\n\treturn result;\n}", "function onlyUniques(...c){\n var unicos = [];\n for (var i = 0,l = c.length; i < l ; i++){\n for (var e = 0, le = unicos.length; e < l; e++){\n if (!unicos.includes(c[i])){\n unicos.unshift(c[i]);\n }\n else{\n console.log('Hay algun elemento repetido');\n }\n }\n }\n console.log(unicos);\n}", "function reciprocalCycles(x){\nvar sequenceLength = 0;\n// we check the unique number we get with every division since at one point they will start repeating\n// the length of repetition can only be as long as there are unique combinations of numbers to divide, therefore we dont need to check the numbers once sequenceLength\n// becomes larger than i\n \nfor (var i = 1000; i > 1; i--) {\n if (sequenceLength >= i) {\n break;\n }\n \n var foundRemainders = new Array(i);\n foundRemainders.fill(0);\n var value = 1;\n var position = 0;\n \n while (foundRemainders[value] == 0 && value != 0) {\n foundRemainders[value] = position;\n value *= 10;\n value %= i;\n position++;\n }\n \n if (position - foundRemainders[value] > sequenceLength) {\n sequenceLength = position - foundRemainders[value];\n }\n return i;\n}\n}", "function countRepeats(string) {\n let count = 0;\n let i = 0;\n let j = 1;\n\n while (j < string.length) {\n if (string.charAt(i) === string.charAt(j)) {\n count++;\n }\n i++;\n j++;\n }\n return count;\n}", "function repeat(array){\n var repeat = []; // 1\n for (var j = 0; j < 10; j++){ // 1\n repeat[j] = []; // 1\n for (var i = 0; i < array.length; i++){ // n linear\n repeat[j].push(array[i]); // 1\n }\n }\n return repeat; \n}", "function uniqueElements(arr) {\n var uniqueArray = [];\n for (var i = 0; i < arr.length; i++) {\n var timesFound = 0;\n for (var j = 0; j < uniqueArray.length; j++) {\n if (arr[i] === uniqueArray[j]) {\n timesFound++;\n }\n }\n \n if (timesFound < 1) {\n uniqueArray.push(arr[i]);\n }\n }\n \n return uniqueArray;\n}", "function findMultipleDuplicates(numberArray) {\n var matches = [];\n var duplicates = [];\n for (var _i = 0, numberArray_2 = numberArray; _i < numberArray_2.length; _i++) {\n var num = numberArray_2[_i];\n if (matches.indexOf(num) == -1)\n matches.push(num);\n else\n duplicates.push(num);\n }\n return duplicates;\n}", "function isValidSubsequence(array, sequence) {\n \n let aIdx = 0\n let sIdx = 0\n \n while (aIdx < array.length && sIdx < sequence.length) {\n if (array[aIdx] === sequence[sIdx]) sIdx++\n aIdx++\n }\n return sIdx === sequence.length\n}", "function outcomes_repetition(sentences) {\n\tvar rep = {};\n\tfor (i = 0; i < sentences.length; i++) {\n\t\tfor (j = 0; j < sentences[i].length; j++) {\n\t\t\tif (sentences[i][j][1] <= 1) {\n\t\t\t\t/* Only worry about words greater than one syllable */\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tw = sentences[i][j][0];\n\t\t\tif (rep[w] == undefined) {\n\t\t\t\trep[w] = 0;\n\t\t\t}\n\t\t\trep[w]++;\n\t\t}\n\t}\n\n\tvar k = outcomes_objSortRev(rep);\n\tvar count = 0;\n\tvar ret = [];\n\tfor (i = 0; i < k.length && count < 3; i++) {\n\t\tif (rep[k[i]] > 3) {\n\t\t\tret.push(k[i]);\n\t\t\tcount++;\n\t\t}\n\t}\n\treturn ret;\n}", "function recurringCharacter(array){\n\n if(!array)\n return undefined;\n\n for(let i =0; i < array.length; i++){\n for(let j = i + 1; j< array.length; j++){\n if(array[i]===array[j])\n return array[i];\n }\n }\n return undefined;\n}", "function sequence(number) {\n let count = 1;\n let sequenceArray = [];\n\n do {\n sequenceArray.push(count);\n count += 1;\n } while (count <= number);\n return console.log(sequenceArray);\n}", "function missing1(A) {\n const N = A.length + 1;\n\n for (let i = 1; i < N; i++) {\n let found = false;\n for (let j = 0; j < A.length && !found; j++) {\n if (i === A[j]) {\n found = true;\n }\n }\n if (!found) {\n return i;\n }\n }\n}", "function containsRepeatedValues(array){\n var maxIndex = -1;\n array.forEach(function(element, index){\n if (array.indexOf(element, index + 1) > maxIndex){\n maxIndex = array.indexOf(element, index+1);\n };\n })\n if (maxIndex === -1){\n return false;\n } else {\n return true;\n }\n}", "function deDupe(arr) {\n\tvar r = [];\n\to:for(var i = 0, n = arr.length; i < n; i++) {\n\t\tfor(var x = 0, y = r.length; x < y; x++) {\n\t\t\tif (r[x] == arr[i]) {\n\t\t\t\tcontinue o;\n\t\t\t}\n\t\t}\n\t\tr[r.length] = Number(arr[i]);\n\t}\n\treturn r;\n}", "function checkRepeats( str ) {\n const regex = /(\\w)\\1+/g;\n return regex.test( str );\n}", "function isValidSubsequence1(array, sequence) {\n if (sequence.length > array.length) {\n return false;\n } else {\n for (let i = 0; i < sequence.length; i++) {\n if (array.indexOf(sequence[i]) === -1) {\n return false;\n }\n }\n return true;\n }\n}", "function ChangingSequence(arr) { \n var pattern = arr[1] > arr[0];\n \n for (var i = 2; i < arr.length; i++) {\n var sequence = arr[i] > arr[i-1];\n if (sequence !== pattern) {\n \tconsole.log(arr[i])\n return (i-1);\n }\n } \n return -1\n \n}", "function icecreamParlor(m, arr) {\n let result = [];\n let breakCondition = false;\n for (let i = 0; i < arr.length; i++) {\n for (let j = 0 ; j < arr.length; j++) {\n if (i !== j && arr[i] + arr[j] === m) {\n result.push(i+1);\n result.push(j+1);\n breakCondition = true;\n break;\n }\n }\n if (breakCondition) break;\n }\n return result;\n}", "function isValidSubsequence(array, sequence) {\n let i = 0;\n\tlet j = 0;\n\t\n\twhile (i < array.length && j < sequence.length) {\n\t\tif (array[i] === sequence[j]) j++;\n\t\ti++\n\t};\n\t\n\treturn j === sequence.length\n}", "function almostIncreasingSequence(sequence) {\nlet counter = 0;\n\n for (let i=0; i < sequence.length; i++) {\n if (sequence[i] <= sequence[i-1]) {\n counter++;\n if (counter > 1) return false;\n if(sequence[i] <= sequence[i-2] && sequence[i+1] <= sequence[i-1]) return false;\n }\n\n }\n return true;\n\n}", "function consecutiveDuplicatesWithCount(inpt)\r\n{\r\n\t finalOutput=\"(\";\r\n\tvar count=1;\r\n\tfor(var i=0;i<inpt.length;i++)\r\n\t{\r\n\t\tvar temp=inpt.charAt(i);\r\n\t\tif(temp==inpt.charAt(i+1))\r\n\t\t{\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(count);\r\n\t\t\tfinalOutput=finalOutput.concat(\" \"+temp);\r\n\t\t\tfinalOutput=finalOutput.concat(\" ) (\");\r\n\t\t\tcount=1;\r\n\t\t}\r\n\t}\r\n\tvar len1=finalOutput.length;\r\n\tdocument.write(finalOutput.slice(0,len1-1));\r\n}", "function solution(A) {\n var set = new Set(),\n arrayLength = A.length;\n for (var i =0; i < arrayLength; i++) {\n if (set.has(A[i])) {\n set.delete(A[i]);\n continue;\n }\n set.add(A[i]);\n }\n return (set.values()).next().value;\n}" ]
[ "0.66973406", "0.6563953", "0.6534063", "0.6279213", "0.6227788", "0.61428845", "0.6120168", "0.6046153", "0.60188544", "0.5967285", "0.5966341", "0.59513086", "0.59499645", "0.594715", "0.5937324", "0.59275925", "0.5912165", "0.5903671", "0.58881706", "0.5887738", "0.5869731", "0.5853647", "0.58489704", "0.58403146", "0.5833011", "0.58321923", "0.5827383", "0.5827383", "0.58252627", "0.5793722", "0.5783295", "0.57739973", "0.5768552", "0.5756916", "0.5751116", "0.5751116", "0.57426757", "0.57250035", "0.5721081", "0.57177985", "0.5697467", "0.56801784", "0.5673589", "0.5670788", "0.5653334", "0.5652693", "0.564642", "0.5638588", "0.56330377", "0.56185853", "0.5613646", "0.56069094", "0.5606701", "0.5571631", "0.55697143", "0.5568654", "0.55632055", "0.55430835", "0.55427843", "0.5541386", "0.5540836", "0.55227745", "0.551687", "0.5506983", "0.5502598", "0.5492658", "0.5491584", "0.54859096", "0.54827243", "0.5474045", "0.54716444", "0.5469347", "0.5445711", "0.5444276", "0.544411", "0.5426706", "0.5417244", "0.5415104", "0.5404294", "0.539919", "0.5394169", "0.5381572", "0.53684324", "0.53641135", "0.53619725", "0.5361381", "0.5351903", "0.53480697", "0.534552", "0.533983", "0.53328395", "0.5328366", "0.5316731", "0.5305507", "0.5297896", "0.5295386", "0.5291559", "0.5291082", "0.5289754" ]
0.5833896
25
find all repeated sequences for strings starting at [row, col]
function repeatsFor(index, row, col) { var r = new Array(); var directions = new Array( new Array(0, 1), // right new Array(1, 1), // right-down new Array(1, 0), // down new Array(1, -1), // left-down new Array(0, -1), // left new Array(-1, -1), // left-up new Array(-1, 0), // up new Array(-1, 1) // right-up ); /* inspect each direction */ var key = get(row, col); var candidates = index[key]; if (candidates) { for (var c=0; c<candidates.length; c++) { for (var i=0; i<directions.length; i++) { for (var j=0; j<directions.length; j++) { var result = new Array(); result[0] = ""; result[1] = new Array(); result[2] = new Array(); if (row == candidates[c][0] && col == candidates[c][1] && i==j ) { ; // do nothing, because we don't want to match the sequence at (row,col) with itself. } else { matches(result, row, col, directions[i][0], directions[i][1], candidates[c][0], candidates[c][1], directions[j][0], directions[j][1]); r[r.length] = new Array(result[0], result[1], result[2], i, j); } } } } } return r; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function repeatedSubstringPatterm(string) {\n let subStr = '';\n\n for (let i = 1; i < string.length; i += 1) {\n subStr = string.slice(0, i);\n let substrings = [];\n [...string].reduce((str, char) => {\n if (str !== subStr) {\n str += char;\n } else {\n substrings.push(str)\n str = ''\n str += char;\n }\n\n return str;\n }, '');\n\n let regex = new RegExp(subStr, 'g')\n if (substrings.every(word => word === subStr)) {\n let array = [subStr, string.match(regex).length];\n console.log(array);\n return array;\n }\n\n return [string, 1];\n }\n}", "function repeatedFind (str) {\n\t\tconst repeated = str.match(/(.)\\1+/gi);//. any character, \\1 match the first parenthesized pattern \n\t\treturn repeated; \n\t}", "function SearchingChallenge2(strArr) {\n let pos = [];\n\n for (let i = 0; i < strArr.length; i++) {\n for (let j = 0; j < strArr[i].length; j++) {\n if ([...strArr[i]][j] === \"0\") pos.push([j, i]);\n }\n }\n\n let count = 0;\n const x = 0;\n const y = 1;\n\n for (let i = 0; i < pos.length; i++) {\n for (let j = 0; j < pos.length; j++) {\n if (\n (pos[i][y] === pos[j][y] && pos[i][x] === pos[j][x] + 1) ||\n (pos[i][x] === pos[j][x] && pos[i][y] === pos[j][y] + 1)\n ) {\n count++;\n }\n }\n }\n\n return count;\n}", "function matrixGenerator(str) {\n // your code here\n let result = [];\n let jumlahArr = 1;\n for (let h = 1; h < str.length; h++) {\n if (h * h >= str.length) {\n jumlahArr = h;\n break;\n }\n }\n\n let selisih = jumlahArr * jumlahArr - str.length;\n let indexStr = 0;\n for (let i = 1; i <= jumlahArr; i++) {\n let tempArr = [];\n for (let j = 1; j <= jumlahArr; j++) {\n if (tempArr.length + 1 < jumlahArr) {\n if (selisih > 0) {\n tempArr.push('*');\n selisih--;\n } else {\n tempArr.push(str[indexStr]);\n indexStr++;\n }\n } else {\n result.push(tempArr);\n if (selisih > 0) {\n tempArr.push('*');\n selisih--;\n } else {\n tempArr.push(str[indexStr]);\n indexStr++;\n }\n }\n }\n }\n return result;\n}", "function repeatedCharacter(find) {\n for(let i = 0; i <= find.length; i++){\n for(let m = i+1; m <= find.length; m++){\n if(find[m] === find[i]){\n return find[i].repeat(1);\n }\n }\n }\nreturn false;\n}", "function findLongestRepeatingSubSeq(str) {\n let n = str.length;\n\n let dp = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n dp[i] = new Array(n + 1);\n for (let j = 0; j <= n; j++) dp[i][j] = 0;\n }\n\n // now use LCS function\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= n; j++) {\n if (str[i - 1] === str[j - 1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1];\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n return dp[n][n];\n}", "function solution(A) {\n var terms = A.length;\n var match = 1;\n var prefix = \"\";\n while (match == 1) {\n for (var c = 0; c < 100; c++) {\n for (var i = 0; i < terms-1; i++) {\n if (A[i][c] != A[i+1][c]) {\n match = 0 \n }\n } \n }\n }\n return prefix;\n}", "function firstNonRepeatingCharacter(string) {\n for (let i = 0; i < string.length; i++) {\n let foundDup = false;\n for (let j= 0; j < string.length; j++) {\n if (string[i] === string[j] && i !== j) foundDup = true; \n }\n \n if (!foundDup) return i;\n }\n return -1;\n}", "function allRepeats() { \n for (var i = 1; i < str.length; i++) {\n if (str.charAt(i) === first) {\n return 0;\n }\n }\n }", "function allRepeats() { \n for (var i = 1; i < str.length; i++) {\n if (str.charAt(i) === first) {\n return 0;\n }\n }\n }", "function doubleSubstring(line) {\n var count = 0;\n var longest;\n for (var i = 0; i < line.length; i++) {\n for (var j = 1; j < line.length; j++ ) {\n\n }\n }\n}", "function countRepeats(string) {\n let count = 0;\n let i = 0;\n let j = 1;\n\n while (j < string.length) {\n if (string.charAt(i) === string.charAt(j)) {\n count++;\n }\n i++;\n j++;\n }\n return count;\n}", "repeat_match(password) {\n const matches = [];\n const greedy = /(.+)\\1+/g;\n const lazy = /(.+?)\\1+/g;\n const lazy_anchored = /^(.+?)\\1+$/;\n let lastIndex = 0;\n while (lastIndex < password.length) {\n var base_token, match;\n greedy.lastIndex = (lazy.lastIndex = lastIndex);\n const greedy_match = greedy.exec(password);\n const lazy_match = lazy.exec(password);\n if (greedy_match == null) {\n break;\n }\n if (greedy_match[0].length > lazy_match[0].length) {\n // greedy beats lazy for 'aabaab'\n // greedy: [aabaab, aab]\n // lazy: [aa, a]\n match = greedy_match;\n // greedy's repeated string might itself be repeated, eg.\n // aabaab in aabaabaabaab.\n // run an anchored lazy match on greedy's repeated string\n // to find the shortest repeated string\n base_token = lazy_anchored.exec(match[0])[1];\n } else {\n // lazy beats greedy for 'aaaaa'\n // greedy: [aaaa, aa]\n // lazy: [aaaaa, a]\n match = lazy_match;\n base_token = match[1];\n }\n const [i, j] = Array.from([match.index, (match.index + match[0].length) - 1]);\n // recursively match and score the base string\n const base_analysis = scoring.most_guessable_match_sequence(\n base_token,\n this.omnimatch(base_token)\n );\n const base_matches = base_analysis.sequence;\n const base_guesses = base_analysis.guesses;\n matches.push({\n pattern: 'repeat',\n i,\n j,\n token: match[0],\n base_token,\n base_guesses,\n base_matches,\n repeat_count: match[0].length / base_token.length\n });\n lastIndex = j + 1;\n }\n return matches;\n }", "function matchPattern(pattern,genome) {\n //console.log(pattern);\n //console.log(genome);\n //console.log(\"genome length : \" + genome.length);\n var positions = [];\n for(var i=0;i<=genome.length-pattern.length;i++) {\n var str = computeText(genome,i,pattern.length);\n // console.log(str);\n if(str==pattern) {\n positions.push(i);\n }\n }\n return positions;\n /*\n var output = \"\";\n for(var i=0;i<positions.length;i++) {\n output = output + positions[i] + \" \";\n }\n return output;\n */\n}", "function searchOnDnaMatrix(dna, sequence, row, col, matchesFound) {\n var numSeq = 0;\n\n // try to search sequence only if the letter from the dna is part of the sequence\n // as the first position is already matched, start from the next one\n if (dna[row][col] === sequence[0]) {\n // there are only 4 possible directions to search: horizontal, vertical, main diagonal and secondary diagonal\n\n // Horizontal matches\n var n;\n var positions = [row + ',' + col];\n for (n = 1; n < sequence.length; n++) {\n if (col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row][col + n] === 'undefined' || dna[row][col + n] !== sequence[n])\n break;\n\n positions.push( row + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Vertical matches\n for (n = 1; n < sequence.length; n++) {\n if (row + n >= dna.length || row + n < 0) \n break;\n\n if (typeof dna[row + n][col] === 'undefined' || dna[row + n][col] !== sequence[n])\n break;\n\n positions.push( (row + n) + ',' + col );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Main diagonal matches \n for (n = 1; n < sequence.length; n++) {\n if (row + n >= dna.length || row + n < 0 || col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row + n][col + n] === 'undefined' || dna[row + n][col + n] !== sequence[n])\n break;\n\n positions.push( (row + n) + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Secondary diagonal matches \n for (n = 1; n < sequence.length; n++) {\n if (row - n >= dna.length || row - n < 0 || col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row - n][col + n] === 'undefined' || dna[row - n][col + n] !== sequence[n])\n break;\n\n positions.push( (row - n) + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n }\n\n return numSeq; \n}", "function repeatedSubstringPattern(string){\n let pattern = \"\";\n for(let i = 0; i < string.length/2; i++){\n pattern += string[i];\n if(pattern.repeat(string.length/pattern.length) === string){\n return true;\n }\n }\n return false;\n}", "function firstRecurringCharacter3(input) {\n for(let i = 0; i < input.length - 1; i++ ){\n for (let j = i + 1; j >= 0; j--) {\n if (input[i] === input[j] && i !== j) {\n return input[i];\n }\n }\n }\n return undefined;\n}", "function findRepeatingCharacters(input) {\n const regex = /([^])(?=\\1)/g;\n return input.match(regex);\n}", "allStringPositions(hay, ndl) {\n let off = 0 // offset\n let all = []\n let pos\n\n while ((pos = hay.indexOf(ndl, off)) !== -1) {\n off = pos + 1\n all.push(pos)\n }\n\n return all\n }", "function findDuplicateCharacters(input) {\n}", "function firstRecurringCharacter2(input) {\n for(let i = 0; i < input.length - 1; i++ ){\n for (let j = i + 1; j < input.length; j++) {\n if (input[i] === input[j]) {\n return input[i];\n }\n }\n }\n return undefined;\n}", "function repeatsfind() {repeats(cipher[which])}", "function repeatsfind() {repeats(cipher[which])}", "function checkGenerator(string,arr){\n let count=0;\n for (let i=0; i<string.length;i++){\n for (let j=0;j<arr.length;j++){\n if (string[i]===arr[j]){\n count++;\n }\n }\n }\n return count;\n}", "function checkRepetition(rLen, str) {\n var res = \"\", repeated = false;\n for (var i = 0; i < str.length; i++) {\n repeated = true;\n for (var j = 0; j < rLen && (j + i + rLen) < str.length; j++) {\n repeated = repeated && (str.charAt(j + i) === str.charAt(j + i + rLen));\n }\n if (j < rLen) {\n repeated = false;\n }\n if (repeated) {\n i += rLen - 1;\n repeated = false;\n }\n else {\n res += str.charAt(i);\n }\n }\n return res;\n }", "function firstNonRepeating(str) {\n const repeating = new Set();\n let firsts = new Set();\n for (let char of str) {\n if (!repeating.has(char)) {\n firsts.add(char);\n repeating.add(char);\n } else firsts.delete(char);\n }\n console.log(firsts);\n return Array.from(firsts.values())[0];\n}", "function consecutiveDuplicates(inpt)\r\n{\r\n\t finalOutput=\"( \";\r\n\tfor(var i=0;i<inpt.length;i++)\r\n\t{\r\n\t\tvar temp=inpt.charAt(i);\r\n\t\tif(temp==inpt.charAt(i+1))\r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(temp);\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(temp);\r\n\t\t\tfinalOutput=finalOutput.concat(\" ) (\");\r\n\t\t}\r\n\t}\r\n\tvar len1=finalOutput.length;\r\n\tdocument.write(finalOutput.slice(0,len1-1));\r\n}", "function characterMapping(str) {\n let repeat = [];\n let map = [];\n for (let i = 0; i < str.length; i++) {\n if (repeat.indexOf(str[i]) === -1) {\n repeat.push(str[i]);\n map.length === 0 ? map.push(0) : map.push(Math.max(...map) + 1)\n } else {\n map.push(repeat.indexOf(str[i]))\n }\n }\n return map \n}", "function checkRepetition(rLen, str) {\n var res = \"\", repeated = false;\n for (var i = 0; i < str.length; i++) {\n repeated = true;\n for (var j = 0; j < rLen && (j + i + rLen) < str.length; j++) {\n repeated = repeated && (str.charAt(j + i) === str.charAt(j + i + rLen));\n }\n if (j < rLen) {\n repeated = false;\n }\n if (repeated) {\n i += rLen - 1;\n repeated = false;\n }\n else {\n res += str.charAt(i);\n }\n }\n return res;\n }", "function firstRecurringCharacter(input) {\n for (let i = 0; i < input.length; i++) {\n for (let j = i + 1; j < input.length; j++) {\n if(input[i] === input[j]) {\n return input[i];\n }\n }\n }\n return undefined\n}//O(n^2) with Space Complexicity O(1)", "function contiguousSubstrings(string, number) {\r\n let result = [];\r\n for (let i = 0; i <= string.length - number; i++) {\r\n result.push(string.slice(i, number + i));\r\n }\r\n return result;\r\n }", "function recurringCharacter(array){\n\n if(!array)\n return undefined;\n\n for(let i =0; i < array.length; i++){\n for(let j = i + 1; j< array.length; j++){\n if(array[i]===array[j])\n return array[i];\n }\n }\n return undefined;\n}", "function none_repeating_char(str) {\n\tconst map = {};\n\tconst queue = [];\n\tfor (let i = 0; i < str.length; i++) {\n\t\tif (str[i] in map) {\n\t\t\tmap[str[i]] = map[str[i]] + 1;\n\t\t\tif (str[i] == queue[0]) {\n\t\t\t\tqueue.shift();\n\t\t\t}\n\t\t} else {\n\t\t\tmap[str[i]] = 1;\n\t\t\tqueue.push(str[i]);\n\t\t}\n\t}\n\tfor (key in map) {\n\t\tif (map[key] == 1) return key;\n\t}\n\treturn -1;\n}", "function buildPatternTable(word) {\n const patternTable = [0];\n let prefixIndex = 0;\n let suffixIndex = 1;\n while (suffixIndex < word.length) {\n if (word[prefixIndex] === word[suffixIndex]) {\n patternTable[suffixIndex] = prefixIndex + 1;\n suffixIndex += 1;\n prefixIndex += 1;\n }\n else if (prefixIndex === 0) {\n patternTable[suffixIndex] = 0;\n suffixIndex += 1;\n }\n else {\n prefixIndex = patternTable[prefixIndex - 1];\n }\n }\n return patternTable;\n}", "function firstRecurringCharacter(input) {\n for (let i = 0; i < input.length; i++) {\n for (let j = i + 1; j < input.length; j++) {\n if (input[i] === input[j]) {\n return input[i];\n }\n }\n }\n return undefined;\n}", "function part1(input) {\n var matches = [];\n var grid = input.split(\"\\n\").filter(a => a != \"\").map(a => a.split(\"\"));\n for (var i = 0; i < grid.length; i++) {\n for (var j = 0; j < grid[0].length; j++) {\n if (grid[i][j] == '#') {\n var gradients = {};\n for (var x = 0; x < grid.length; x++) {\n for (var y = 0; y < grid[0].length; y++) {\n if (!(x == i && y == j) && grid[x][y] == '#') {\n var deg = Math.atan2((y-j), (x-i)) / Math.PI * 360;\n if (!gradients[deg]) {\n gradients[deg] = [];\n }\n gradients[deg].push(Math.abs(x-i) + Math.abs(y-j))\n }\n }\n }\n matches.push({\n i,\n j,\n sum: gradients.toArray().length,\n gradients,\n })\n }\n }\n }\n return matches.sort((a, b) => Math.sign(b.sum - a.sum))[0].sum;\n}", "function soluation(string, row) {\n let nArr = []\n for (let index = 0; index < row; index++) {\n nArr.push([])\n }\n\n function covert(index, rowNum) {\n let x = Math.floor(index / (row + rowNum - 2))\n let y = Math.floor(index % (row + rowNum - 2))\n if (y < rowNum) {\n let column = x * (rowNum - 1) + 0\n let row = y\n return { column, row }\n } else {\n let column = x * (rowNum - 2) + y - rowNum + 1\n let row = rowNum - 2 - (y - rowNum)\n return { column, row }\n }\n }\n\n\n for (let index = 0; index < string.length; index++) {\n let res = covert(index, row)\n nArr[res.row].push(string[index])\n }\n var s = \"\"\n nArr.forEach((a, b) => {\n a.forEach((v, k) => {\n s += v\n })\n })\n return s\n}", "function sol(chars) {\n let indexRes = 0;\n let index = 0;\n while (index < chars.length) {\n const cur = chars[index];\n let count = 1;\n while (index + 1 < chars.length && chars[index + 1] === cur) {\n index++;\n count++;\n }\n chars[indexRes] = cur;\n indexRes++;\n index++;\n if (count === 1) continue;\n for (let c of String(count).split(\"\")) {\n chars[indexRes] = c;\n indexRes++;\n }\n }\n return indexRes;\n}", "function longestRepetition(s) {\n //console.log(s)\n var i = 0,\n seq = 0,\n results = [];\n \n if ( s === ('')){\n return ['', 0]\n }\n \n for(let i=0; i<s.length; i++) {\n var current = s[i],\n next = s[i + 1];\n \n if (typeof results[seq] === 'undefined') {\n results[seq] = [current, 0];\n }\n \n results[seq][1]++;\n \n if (current !== next) {\n seq++;\n }\n }\n \n return results.sort((a, b) => b[1] - a[1])[0];\n }", "function findDuplicate(str, n) {\n // we use hear map to find dupicate element in string\n let count = {};\n\n for (let i in str) count[str[i]] = 0;\n\n for (let i in str) count[str[i]]++;\n\n for (let j in count) {\n if (count[j] > 1) document.write(j + \" is repeat for \" + count[j] + \"<br>\");\n }\n}", "function firstNonRepeatedCharacter (string) {\n\n var array = string.split(\"\");\n var repeats = [];\n var result = array.shift();\n \n while(array.length > 1) {\n if(~array.indexOf(result) || ~repeats.indexOf(result)) {\n repeats.push(result)\n result = array.shift();\n } else\n return result;\n }\n \n return 'sorry';\n\n}", "function getCandidates(board, row, col) {\n // # For some empty cell board[row][col], what possible\n // # characters can be placed into this cell\n // # that aren't already placed in the same row,\n // # column, and sub-board?\n const candidates = [];\n\n // For each character add it to the candidate list only if there's no collision, i.e. that character\n // # doesn't already exist in the same row, column and sub-board.\n // Notice the top-left corner of (row, col)'s sub-board is (row - row%3, col - col%3).\n // for chr from '1' to '9':\n for (let chr = 1; chr <= 9; chr++) {\n let collision = false;\n for (let i = 0; i < 9; i++) {\n if (\n board[row][i] == chr ||\n board[i][col] == chr ||\n board[row - (row % 3) + Math.floor(i / 3)][\n col - (col % 3) + Math.floor(i / 3)\n ] == chr\n ) {\n collision = true;\n break;\n }\n }\n\n if (!collision) {\n candidates.push(chr);\n }\n }\n return candidates;\n}", "function consecutiveDuplicatesWithCount(inpt)\r\n{\r\n\t finalOutput=\"(\";\r\n\tvar count=1;\r\n\tfor(var i=0;i<inpt.length;i++)\r\n\t{\r\n\t\tvar temp=inpt.charAt(i);\r\n\t\tif(temp==inpt.charAt(i+1))\r\n\t\t{\r\n\t\t\tcount++;\r\n\t\t}\r\n\t\telse \r\n\t\t{\r\n\t\t\tfinalOutput=finalOutput.concat(count);\r\n\t\t\tfinalOutput=finalOutput.concat(\" \"+temp);\r\n\t\t\tfinalOutput=finalOutput.concat(\" ) (\");\r\n\t\t\tcount=1;\r\n\t\t}\r\n\t}\r\n\tvar len1=finalOutput.length;\r\n\tdocument.write(finalOutput.slice(0,len1-1));\r\n}", "function sameStart(arr, letter) {\n\n}", "function perimiter(matrix) {\n // O(N*N)\n let result = 0;\n let matrixLength = matrix.length;\n\n for (let i = 0; i < matrixLength; i++) {\n let line = matrix[i];\n let lineLength = line.length;\n\n for (let j = 0; j < lineLength; j++) {\n if (line[j] === symbol) {\n let left = 0;\n let right = 0;\n let top = 0;\n let bottom = 0;\n\n if (j === 0 || line[j - 1] === symbolO) {\n left = 1;\n }\n\n if (j === lineLength - 1 || line[j + 1] === symbolO) {\n right = 1;\n }\n\n if (i === 0 || matrix[i - 1][j] === symbolO) {\n top = 1;\n }\n\n if (i === matrixLength - 1 || matrix[i + 1][j] === symbolO) {\n bottom = 1;\n }\n\n result += left + right + top + bottom;\n }\n }\n }\n\n return result;\n}", "function norepeat(str) {\n\tvar newArr = str.split(\"\");\n\tfor (var i = 0; i < str.length; i++) {\n\t\tif (i > 0) {\n\t\t\tif (str[i - 1] !== str[i] && str[i] !== str[i + 1]) {\n\t\t\t\treturn str[i];\n\t\t\t}\n\t\t}\n\t}\n}", "function contiguousSeq(arr) {\n\n}", "function consecutivosSimilares(string) {\n let sum = 0;\n\n for (let i = 1; i < string.length; i++) {\n if (string[i - 1] === string[i]) {\n sum++;\n }\n }\n return sum;\n}", "function firstNonRepeatingCharacter(string) {\n let seenHash = {};\n\n for (const char of string){\n if (!seenHash[char]){\n seenHash[char] = 1;\n } else {\n seenHash[char]++;\n }\n }\n\n for (const key in seenHash){\n const value = seenHash[key];\n if (value === 1)return string.indexOf(key);\n }\n\n // for (const index in string){\n // const char = string[index];\n // if (seenHash[char] === 1) return index;\n // }\n\n return -1;\n}", "function getSrepeatCount() {\r\n srepeat_examples = [];\r\n srepeats_for_sentences = [];\r\n result = [];\r\n for(i=0; i<sentences.length; i++) {\r\n sentence = [];\r\n sentence = sentences[i].replace(/[^a-zA-Zа-яА-ЯёЁ \\n']/g, \" \");\r\n sentence = sentence.replace(/\\s+/g, \" \");\r\n sentence = sentence.toLowerCase();\r\n sentence = sentence.substring(0,sentence.length-1);\r\n sentence = sentence.split(\" \");\r\n \r\n sub_result = sentence.reduce(function (acc, el) {\r\n acc[el] = (acc[el] || 0) + 1;\r\n return acc;\r\n }, {});\r\n\r\n tmp = [];\r\n for(key in sub_result) {\r\n if(sub_result[key] > 1 && unions.indexOf(key) == -1 && prepositions.indexOf(key) == -1) {\r\n tmp.push(key);\r\n result.push(key);\r\n }\r\n }\r\n srepeat_examples.push([sentences[i], tmp]);\r\n }\r\n tmp = []\r\n for(key in srepeat_examples) {\r\n tmp = []\r\n for(i=0; i<srepeat_examples[key][1].length; i++){\r\n if(srepeat_examples[key][1].length != 0) {\r\n if(srepeat_examples[key][1][i] != \"'\" || srepeat_examples[key][1][i] == \"i\") {\r\n tmp.push(srepeat_examples[key][1][i])\r\n }\r\n }\r\n }\r\n srepeat_examples[key][1] = tmp;\r\n }\r\n\r\n count = 0;\r\n for(i=0; i<srepeat_examples.length; i++) {\r\n if(srepeat_examples[i][1].length != 0) {\r\n for(j=0; j<srepeat_examples[i][1].length; j++) {\r\n count++;\r\n }\r\n }\r\n }\r\n\r\n return count;\r\n}", "function howManyRepeated(str){\n let sum = 0;\n const strArr = str.toLowerCase().split(\"\").sort().join(\"\").match(/(.)\\1+/g);\n return strArr;\n}", "function noRepeats(str) {\n let arr = [];\n for(let i = 0; i < str.length; i++) {\n if(arr.includes(str[i])) {\n return false\n }else if(!arr.includes(str[i])) {\n arr.push(str[i]);\n }\n }\n return true;\n }", "function findInSequence() {\n\tvar beginMatch = 0;\n\tvar endMatch = 0;\n\tvar i = 0;\n\tvar specChar = RegExp('[X]');\n\tvar test = specChar.exec(searchMotif);\n\tconsole.log(test);\n\tvar xs = [];\n\tvar generalCase = false;\n\tvar splitMotif = searchMotif.split(\"\");\n\tif (test != null && searchMotif.length >= 2){\n\t\t\n\t\tfor (var i = 0; i < searchMotif.length; i++){\n\t\t\tvar char = searchMotif.charAt(i);\n\t\t\tif(char == \"X\"){\n\t\t\t\txs.push(i);\n\t\t\t}\n\t\t}\n\t\tgeneralCase = true;\n\t}\nwhile (endMatch < seq.length){\n\tendMatch = beginMatch + searchMotif.length;\n\tvar currentlyChecked = seq.substring(beginMatch, endMatch);\n\t//check for spaces or new lines within the search portion of the sequence\n\tif(generalCase){\n\t\tvar currCheckedSplit = currentlyChecked.split(\"\");\n\t\t//process out x's\n\t\tfor(var i = 0; i < splitMotif.length; i++){\n\t\t\tif(xs[i] != null){\n\t\t\tcurrCheckedSplit.splice(xs[i],1,\"X\");\n\t\t\t}\n\t\t}\n\t\tcurrentlyChecked = currCheckedSplit.join(\"\");\n\t}\n\tif(currentlyChecked === searchMotif){\n\t\tvar indices = [beginMatch, endMatch];\n\t\tindicesOfMatches.push(indices);\n\t\tbeginMatch = endMatch;\n\t}\n\telse{\n\t\tbeginMatch++;\n\t}\n\tcurrentlyChecked = \"\";\n}\n\tinsertHighlightSpans();\n}", "function FirstAppearingOnce() {\n // write code here\n let ch = stringstream.length ? stringstream.charAt(0) : '#'\n if (stringstream.length < 2) {\n return ch\n }\n // 创建一个和 string 一样大的数组空间标记重复情况\n let repeat = stringstream.split('').map(a => false)\n // 两重循环\n for (let i = 0; i < stringstream.length; i++) {\n // 直接跳过标记过重复的位置\n if (!repeat[i]) {\n ch = stringstream.charAt(i)\n for (let j = i + 1; j < stringstream.length; j++) {\n if (!repeat[j]) {\n if (ch === stringstream.charAt(j)) {\n repeat[j] = true\n repeat[i] = true\n }\n }\n }\n // 查完整个字符串都没找到重复,就直接返回整个字符\n if (!repeat[i]) {\n return ch\n }\n }\n }\n return '#'\n}", "function findWordConcatentation(str, words) {\n const indices = [];\n const wordCount = words.length;\n const wordLength = words[0].length;\n\n if (wordCount === 0 || wordLength === 0) return indices;\n\n const wordMap = createFrequenceMap(words);\n const maxConcatnationLength = str.length - (wordCount * wordLength) + 1;\n\n for (let wordStart = 0; wordStart < maxConcatnationLength; wordStart++) {\n\n const wordsSeen = {};\n\n for (let j = 0; j < wordCount; j++) {\n let word = makeWord(wordStart, wordLength, j, str)\n \n if (!checkWordValidityAndUpdate(word, wordMap, wordsSeen)) break;\n \n if (j + 1 === wordCount) {\n indices.push(wordStart)\n }\n }\n }\n\n return indices;\n}", "function firstRecurringCharacter(input = []) {\n for (let i = 0; i < input.length - 1; i++) {\n for (let j = i + 1; j < input.length; j++) {\n if (input[i] === input[j]) {\n return input[i];\n }\n }\n }\n\n return undefined;\n}", "function rowChecker() {\n var gap = false;\n var startWord = false;\n for(i = 0; i < 15; i++) {\n var current = $.grep(boardObj, function(e) {return e.boardPos === i}); // gets the position\n if (current.length == 1 && startWord == true) { // checks to see if the element has been used.\n return false;\n } else if (current.length == 0 && gap == true) {\n startWord = true;\n } else if (current.length == 1 && gap == false) {\n gap = true;\n }\n }\n return true;\n}", "function grabscrab(str, arr) {\n let matches = [];\n\n for (let idx = 0; idx < arr.length; idx += 1) {\n if (str.split('').sort().join('') === arr[idx].split('').sort().join('')) {\n matches.push(arr[idx]);\n }\n }\n\n return matches;\n}", "function solve(input) {\n let unique = {\n 2: '1',\n 4: '4',\n 3: '7',\n 7: '8'\n }\n let arr = input.split('\\n').map(r => r.split(' | ')[1]).map (r => r.split(' '));\n let count = 0;\n for (let row of arr) {\n for (let letters of row) {\n if (letters.length in unique) {\n count++;\n }\n }\n }\n return count;\n}", "function stringPermutation1(str, pattern) {\n let matches = 0;\n let start = 0;\n let strCountsPattern = createCharCount(pattern);\n let patternCharacters = Object.keys(strCountsPattern).length;\n\n for(let end = 0; end < str.length; end++) {\n const rightChar = str[end];\n const leftChar = str[start];\n\n if(rightChar in strCountsPattern) {\n strCountsPattern[rightChar]--;\n \n if(strCountsPattern[rightChar] === 0) {\n matches++;\n }\n }\n\n if( matches === patternCharacters ) {\n return true;\n }\n\n if( end >= pattern.length - 1 ) {\n \n if(strCountsPattern[leftChar] === 0) {\n matches--;\n }\n\n strCountsPattern[leftChar]++;\n start++;\n }\n }\n\n return false;\n}", "function reg2(s) {\n let good = s.split(`\\n`).filter( e => {\n let pair = /(..)(?:.*)\\1/g.test(e);\n let repeat = /(.)(?:.)\\1/g.test(e);\n return pair && repeat;\n }).length;\n console.log(good);\n}", "function convertToZigZag(str, rows) {\n\n if (rows === 1) {\n return str;\n }\n\n let convertedString = \"\";\n\n for (let offset = 0; offset < rows; offset++) {\n\n let position = offset;\n let firstJump = 2 * (rows - 1 - offset);\n let secondJump = offset * 2;\n\n if (firstJump === 0) {\n firstJump = secondJump\n } else if (secondJump === 0) {\n secondJump = firstJump;\n }\n\n let first = true;\n\n while (position < str.length) {\n\n convertedString += str[position];\n\n if (first) {\n position += firstJump;\n } else if (!first) {\n position += secondJump;\n }\n\n first = !first;\n }\n }\n\n return convertedString;\n\n //\n //\n // //first row, and last row\n // for (let i = 0; i < str.length; i += 2 * (rows - 1)) {\n // convertedString += str[i];\n // if (rows - 1 + i < str.length) {\n // endStr += str[rows - 1 + i];\n // }\n // }\n //\n // leftIndex++;\n // rightIndex--;\n //\n // while (leftIndex < rightIndex) {\n //\n // let i = leftIndex;\n // let bigJump = 2 * (rows - 2);\n // let smallJump = leftIndex * 2;\n // let big = true;\n //\n // while (i < str.length) {\n //\n // convertedString += str[i];\n //\n // if (big) {\n // i += bigJump;\n // } else {\n // i += smallJump;\n // }\n //\n // big = !big;\n // }\n //\n // i = rightIndex;\n // big = false;\n //\n // while (i < str.length) {\n //\n // endStr = endStr + str[i];\n //\n // if (big) {\n // i += bigJump;\n // } else {\n // i += smallJump;\n // }\n // }\n //\n // leftIndex++;\n // rightIndex--;\n //\n // }\n //\n // if (leftIndex === rightIndex) {\n //\n // for (let i = leftIndex; i < str.length; i += rows - 1) {\n // convertedString += str[i];\n // }\n //\n // }\n //\n // //second row\n // // let i = 1;\n // // while (i < str.length) {\n // //\n // // convertedString += str[i];\n // //\n // // if (i % 2) {\n // // i += 2;\n // // } else {\n // // i += 2 * (rows - 2);\n // // }\n // // }\n}", "function findRepeats(arr) {\n // -------------------- Your Code Here --------------------\n\n // create an object to keep track of how many times we've seen words\n var words = {};\n\n // create the array we're going to be returning\n var repeated = [];\n\n // iterate through the argument\n for (var i=0; i<arr.length; i++) {\n\n // if we've already encountered the current word, increment the count of \n // of the number of times we've seen the word\n if (words.hasOwnProperty(arr[i])){\n words[arr[i]]++;\n\n // the first time we encounter the word again (count is 2), we add it to\n // the output array\n if (words[arr[i]] === 2) {\n repeated.push(arr[i]);\n }\n } else {\n\n // if this is our first time seeing the word, add it to the object with a\n // count of 1\n words[arr[i]] = 1;\n }\n }\n\n // sort the array and return it\n return repeated.sort();\n\n // --------------------- End Code Area --------------------\n}", "function findDupe(string) { \n var dupeCheck = /(.)\\1/gi; // look for duplicated characters (character immediately followed by itself)\n var repeatTest = dupeCheck.test(string); // tests if dupe exists in string T/F\n if (repeatTest !== true) { // if doesn't exist\n counter++; // increase counter by 1\n console.log(\"counter is \" + counter);\n } \n }", "function pattern(n){\n var output='';\n var counter = 0;\n while (counter < n){\n counter++;\n for (var i = 1; i <= counter; i++){\n output += counter;\n }\n output += '\\n';\n }\n return output.trim();\n}", "function solve(s) {\n let subStrings = [];\n for (let index = 0; index < s.length; index++) {\n for (let index2 = index; index2 < s.length; index2++) {\n let subString = s.slice(index, index2 + 1);\n subStrings.push(subString);\n }\n }\n return subStrings.reduce((count, subStr) => {\n if (Number(subStr) % 2 === 1) {\n count += 1;\n }\n return count;\n }, 0);\n}", "function firstNotRepeatingCharacter(s) {\n let map = new Map()\n \n\n for (let i = 0; i < s.length; i++){\n let char = s[i]\n \n if (map.has(char)) {\n map.set(char, map[char]++)\n } else {\n map.set(char, 1)\n }\n }\n \n for (let [key, value] of map) {\n if (value === 1) {\n return key\n }\n }\n return '_'\n}", "function encontrarPalabra(palabra, cadenaSopa, filas, columnas){\n tamCadena = palabra.length;\n\t\tconsole.log(palabra.length);\n \n\t\tvar continuarCiclo = true;\n var seguirArriba = true;\n var seguirAbajo = true;\n var seguirDerecha = true;\n var seguirIzq = true;\n var seguirDiagonalAbajo = true;\n var seguirDiagonalArriba = true;\n\t\t\n var variable = 0;\n\t\t\n\t\tmatriz = pasarAmatriz(cadenaSopa, filas, columnas);\n\t\txy = crearArreglo(palabra);\n\t\txyTemp = crearArreglo(palabra);\n\t\txyLetras = new Array(4);\n\t\t\n console.log(\"La palabra es \" + palabra);\n \n for(var i = 0; i < matriz.length && continuarCiclo; i++){\n for(var j = 0; j < matriz[0].length && continuarCiclo; j++){\n console.log(\"La matriz i: \" + i + \" la j: \" + j + \" la letra: \" + matriz[i][j]);\n \n if(matriz[i][j] == palabra.charAt(0)){\n console.log(\"La palabra es \" + palabra.charAt(0));\n //Busca hacia abajo si la primera letra de la palabra coincide con la celda actual\n\t\t\t\t if(seguirAbajo){\n console.log(\"seguir ABAJO \" + matriz[i][j] + \"\\n\");\n \n for(var k = 0; k < tamCadena; k++){\n\t\t\t\t\t\t if(i+k < matriz.length){\n\t\t\t\t\t\t\t console.log(\"seguir de la matriz \" + matriz[i+k][j]);\n\t\t\t\t\t\t\t console.log(\"seguir de la palabra \" + palabra.charAt(k));\n\t\t\t\t\t\t\t if(matriz[i+k][j] == palabra.charAt(k)){\n\t\t\t\t\t\t\t\t xyTemp[0][k] = i+k;\n\t\t\t\t\t\t\t\t xyTemp[1][k] = j;\n\t\t\t\t\t\t\t\t xyLetras[k] = matriz[i+k][j];\n\t\t\t\t\t\t\t\t variable++;\n\t\t\t\t\t\t\t\t \n\t\t\t\t\t\t\t }else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n\t\t\t\t\t\t\t\t seguirAbajo = false;\n\t\t\t\t\t\t\t\t break;\n\t\t\t\t\t\t\t }\n\t\t\t\t\t\t }else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t }\n\t\t\t\t\t\t \n }\n }\n \n\t\t\t\t //Setea las varaiables\n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirAbajo = true;\n }\n \n\t\t\t\t //Busca hacia la derecha si la primera letra de la palabra coincide con la celda actual\n if(seguirDerecha && continuarCiclo){\n console.log(\"seguir DERECHA \" + matriz[i][j] + \"\\n\");\n for(var k = 0; k < tamCadena; k++){\n\t\t\t\t\t\t\tif(j+k < matriz[0].length){\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la matriz \" + matriz[i][j+k]);\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la palabra \" + palabra.charAt(k));\n\t\t\t\t\t\t\t\tif(matriz[i][j+k] == palabra.charAt(k)){\n\t\t\t\t\t\t\t\t\txyTemp[0][k] = i;\n\t\t\t\t\t\t\t\t\txyTemp[1][k] = j+k;\n\t\t\t\t\t\t\t\t\tconsole.log(\"La vara es \" + palabra.charAt(tamCadena-k-1) + \" res\"+ (tamCadena-k-1));\n\t\t\t\t\t\t\t\t\txyLetras[k] = palabra.charAt(tamCadena-k-1);\n\t\t\t\t\t\t\t\t\tvariable++;\n\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n\t\t\t\t\t\t\t\t\tseguirDerecha = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\t\n }\n }\n \n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirDerecha = true;\n }\n\t\t\t\t \n //Busca hacia arriba si la primera letra de la palabra coincide con la celda actual\n if(seguirArriba && continuarCiclo){\n console.log(\"seguir ARRIBA \" + matriz[i][j]+ \"\\n\");\n for(var k = 0; k < tamCadena; k++){\n\t\t\t\t\t\t\tif(i-k >= 0){\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la matriz \" + matriz[i][j+k]);\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la palabra \" + palabra.charAt(k));\n\t\t\t\t\t\t\t\tif(matriz[i-k][j] == palabra.charAt(k)){\n\t\t\t\t\t\t\t\t\txyTemp[0][k] = i-k;\n\t\t\t\t\t\t\t\t\txyTemp[1][k] = j;\n\t\t\t\t\t\t\t\t\txyLetras[k] = matriz[i-k][j];\n\t\t\t\t\t\t\t\t\tvariable++;\n\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n\t\t\t\t\t\t\t\t\tseguirArriba = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n }\n }\n \n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirArriba = true;\n }\n \n //Busca hacia la izquierda si la primera letra de la palabra coincide con la celda actual\n if(seguirIzq && continuarCiclo){\n console.log(\"seguir IZQ \" + matriz[i][j] + \"\\n\");\n for(var k = 0; k < tamCadena; k++){\n\t\t\t\t\t\t\tif(j-k >= 0){\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la matriz \" + matriz[i][j-k]);\n\t\t\t\t\t\t\t\tconsole.log(\"seguir de la palabra \" + palabra.charAt(k));\n\t\t\t\t\t\t\t\tif(matriz[i][j-k] == palabra.charAt(k)){\n\t\t\t\t\t\t\t\t\txyTemp[0][k] = i;\n\t\t\t\t\t\t\t\t\txyTemp[1][k] = j-k;\n\t\t\t\t\t\t\t\t\txyLetras[k] = matriz[i][j-k];\n\t\t\t\t\t\t\t\t\tvariable++;\n\t\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n\t\t\t\t\t\t\t\t\tseguirIzq = false;\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}else{\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n }\n }\n \n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirIzq = true;\n }\n\t\t\t\t \n\t\t\t\t //Busca en dirección diagona arriba si la primera letra de la palabra coincide con la celda actual\n\t\t\t\t if(seguirDiagonalArriba && continuarCiclo){\n console.log(\"seguir diagonal Arriba \" + matriz[i][j] + \"\\n\");\n for(var k = 0; k < tamCadena; k++){\n if(i-k >= 0 && j-k >= 0){\n console.log(\"seguir de la matriz \" + matriz[i-k][j-k]);\n console.log(\"seguir de la palabra \" + palabra.charAt(k));\n if(matriz[i-k][j-k] == palabra.charAt(k)){\n xyTemp[0][k] = i-k;\n xyTemp[1][k] = j-k;\n xyLetras[k] = matriz[i-k][j-k];\n variable++;\n }else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n seguirDiagonalArriba = false;\n break;\n }\n }else{\n break;\n }\n }\n }\n \n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirDiagonalArriba = true;\n }\n \n \n\t\t\t\t //Busca en digona abajo si la primera letra de la palabra coincide con la celda actual\n if(seguirDiagonalAbajo && continuarCiclo){\n console.log(\"seguir diagonal Abajp \" + matriz[i][j] + \"\\n\");\n for(var k = 0; k < tamCadena; k++){\n if(i+k < matriz.length && j+k < matriz[0].length){\n console.log(\"seguir de la matriz \" + matriz[i+k][j+k]);\n console.log(\"seguir de la palabra \" + palabra.charAt(k));\n if(matriz[i+k][j+k] == palabra.charAt(k)){\n xyTemp[0][k] = i+k;\n xyTemp[1][k] = j+k;\n xyLetras[k] = matriz[i+k][j+k];\n variable++;\n }else{\n\t\t\t\t\t\t\t\t\t//Ya no coincide\n seguirDiagonalAbajo = false;\n break;\n }\n }else{\n break;\n }\n }\n }\n \n if(variable == tamCadena){\n xy = xyTemp;\n continuarCiclo = false;\n }else{\n variable = 0;\n seguirDiagonalAbajo = true;\n }\n \n \n }\n }\n }\n\t\t\n\t\tif(continuarCiclo == false){\n\t\t\tpalabraEncontrada = true;\n\t\t}\n\t\t\n\t\treturn xy;\n }", "function firstNonRepeatedCharacter (string) {\n var repeatedValues = [];\n\n for(var i = string.length -1; i >= 0; i--) {\n if((i) !== string.indexOf(string[i])){\n repeatedValues.push(string[i]);\n }\n }\n var store;\n for(var a = 0; a < string.length-1; a++) {\n if(repeatedValues.indexOf(string[a]) === -1) {\n store = string[a];\n break;\n }\n }\n\n if(store) {\n return store;\n } else {\n return 'sorry';\n }\n}", "function SearchingChallenge1(str) {\n const array = [...str];\n const k = Number(array.shift());\n\n let substring = [];\n let n = 1;\n\n let index = 0;\n\n let res = [];\n\n while (index < array.length) {\n if (substring === [] || substring.includes(array[index])) {\n substring.push(array[index]);\n index++;\n console.log(\"substring\", substring);\n } else if (!substring.includes(array[index]) && n <= k) {\n substring.push(array[index]);\n n++;\n index++;\n console.log(\"substring\", substring);\n } else {\n res.push(substring.join(\"\"));\n console.log(\"res during\", res);\n substring = [];\n n = 1;\n index--;\n console.log(\"substring after []\", substring.length);\n }\n }\n\n res.push(substring.join(\"\"));\n\n console.log(\"res final\", res);\n\n const lengths = res.map((e) => e.length);\n\n return res[lengths.indexOf(Math.max(...lengths))];\n}", "function checkRepeats() {\n var v_ctr;\n for (v_ctr=0; v_ctr<7; v_ctr++) {\n/* console.log(\"340 [\" + v_ctr + \"] [\" +\n a_scaleNotes[v_ctr].substr(0,1) + \"] [\" +\n a_scaleNotes[(v_ctr + 1) % 7].substr(0,1) + \"]\");\n*/\n if (a_scaleNotes[v_ctr].substr(0,1) == a_scaleNotes[(v_ctr + 1) % 7].substr(0,1))\n return true;\n }\n return false;\n}", "function searchSequences(dna, sequences) {\n\n var numMatchesSeq = 0;\n // store the positions of the letters that were matched\n var matchesFound = [];\n sequences.forEach(seq => {\n matchesFound[seq] = [];\n });\n \n // go through all the sequences\n sequences.forEach(seq => {\n for (let r = 0; r < dna.length; r++) {\n for (let c = 0; c < dna.length; c++) {\n numMatchesSeq += searchOnDnaMatrix(dna, seq, r, c, matchesFound);\n }\n }\n });\n\n // if a sequence on the dna matrix is longer than the sequence to be matched, it will be duplicated. Let's fix that.\n numMatchesSeq = removePossibleDuplicates(matchesFound, sequences, numMatchesSeq);\n\n return numMatchesSeq;\n}", "function NonrepeatingCharacter(str) {\n str = str.replace(/ /g, \"\");\n if (str.length === 1) return str;\n // use two for loops\n const lookup = {};\n for (let i = 0; i < str.length; i++) {\n lookup[str[i]] ? lookup[str[i]]++ : (lookup[str[i]] = 1);\n }\n for (key in lookup) {\n if (lookup[key] === 1) return key;\n }\n}", "function firstNotRepeat(string){\n\tstring=string.toLowerCase()\n\tlist=\"\"\n\tvar letterCount=[]\n\tfor(var i=0;i<string.length;i++)\n\t{\n\t\tif(list.indexOf(string[i])== -1)\n\t\t{\n\t\t\tlist=list+string[i]\n\t\t}\n\t\tif(list.length == 26){\n\t\t\tbreak\n\t\t}\n\t}\n\tfor(var j=0;j<list.length;j++){\t\n\t\tvar count=0\n\t\tfor(var i=0; i< string.length;i++)\n\t\t{\n\t\t\tif(string[i]==list[j])\n\t\t\t\t{\n\t\t\t\t\tcount++\n\t\t\t\t}\n\t\t}\n\t\tletterCount.push([list[j],count])\n\t}\n\treturn letterCount.find(function(element) {\n\t\t return element[1] == 1\n\t})[0]\n}", "function findWordMatrix(matrix, word) {\n\tif (word == null || word === '') return false;\n\tif (matrix == null || matrix.length === 0) return false;\n\n\t//searching only from left-to-right\n\tfor (let i = 0; i < matrix.length; i++) {\n\t\tlet row = matrix[i].join('');\n\n\t\tif (row === word) {\n\t\t\treturn true; //break and return as soon is found\n\t\t}\n\t}\n\n\tlet c = 0; //column index\n\twhile (c < matrix.length) {\n\t\tlet col = '';\n\t\tfor (let i = 0; i < matrix.length; i++) {\n\t\t\tif (i === 0) {\n\t\t\t\tcol = matrix[i][c];\n\t\t\t} else {\n\t\t\t\tcol += matrix[i][c];\n\t\t\t}\n\t\t}\n\t\tif (col === word) {\n\t\t\treturn true; //break and return as soon is found\n\t\t}\n\t\tc++;\n\t}\n\n\treturn false;\n}", "function repeater(string) {\n var duplicatedString = '';\n\n for (var i = 0; i < string.length; i++) {\n duplicatedString += string[i];\n duplicatedString += string[i];\n }\n\n console.log(duplicatedString);\n}", "function occurence(A) {\n\tvar str = '';\n\tfor(var i = 0; i < A.length/2; i++) {\n\t\tstr = str + A[i];\n\t\tvar exp = new RegExp(str, 'g');\n\t\tvar count = A.match(exp); console.log(count);\n\t\tif(A.length/str.length == count.length)\n\t\t\treturn count[0];\n\t}\n}", "function longestCommonSubsequence(text1, text2) {\n /*\n - Think of the rows as the outer loop and the columns as the inner loop.\n - Use 2 pointers, one for each string (imagine it being a matrix). One is for rows and the other for columns.\n - Rows -> text1\n - Columns -> text2\n - Like in the Coin Change problem, build the matrix and traverse it backwards when necessary.\n - When initializing the matrix, add an additional row and column BEFORE and initialize them to 0s.\n - If both characters match, move 1 row and col forward and add 1 to it (down diagonally).\n - If characters don't match, calculate the max of going back in the col (cell above) and going back in the row (cell to the left). Doing this we carry forward the maximum common subsequence\n X a b c d e X a b c d e\n X 0 0 0 0 0 0 X 0 0 0 0 0 0\n a 0 1 0 0 0 0 a 0 1 1 1 1 1\n c 0 0 0 0 0 0 c 0 1 1 2 2 2\n e 0 0 0 0 0 0 e 0 3 3 3 3 3\n */\n\n const dp = []\n\n // Generate the starting matrix adding the additional row and col. Fill the matrix with 0s\n for (let i = 0; i < text1.length + 1; i++) {\n dp.push(Array(text2.length + 1).fill(0))\n }\n\n // Scan from left to right through the string\n for (let i = 0; i < text1.length; i++) {\n for (let j = 0; j < text2.length; j++) {\n // If the values match move 1 row and col forward and add 1 to it (down-right diagonally).\n if (text1[i] === text2[j]) {\n // The new value will be the diagonal\n const diagonal = dp[i][j]\n // Calculate the cell taking into account the offset of the additional row/col\n // Increment by the value of the diagonal\n dp[i + 1][j + 1] = diagonal + 1\n }\n // If characters don't match carry forward the maximum common subsequence\n else {\n const above = dp[i][j + 1]\n const left = dp[i + 1][j]\n // Calculate the max of the cell above and the one to the left\n dp[i + 1][j + 1] = Math.max(above, left)\n }\n }\n }\n\n // If we found the LCS the it's length would be saved in the bottom-right corner.\n // If no subsequence was found the value of the last cell will be 0\n return dp[text1.length][text2.length]\n}", "function firstRepeat(inputString) {\n var letterMemory = [];\n for (var i = 0; i < inputString.length; i++) {\n var currentLetter = (inputString.charAt(i));\n if (inArray(letterMemory, currentLetter)){\n return currentLetter;\n } else letterMemory.push(currentLetter)\n }\n return 'No repetitions'\n}", "function repeats (arr) {\n for (let i = 0; i < arr.length; i++) {\n for (let a = i+1; a < arr.length; a++) {\n if (equalArrays(arr[i], arr[a])) {\n return 'repeat';\n }\n }\n }\n return 'no repeat';\n}", "function strRepeatCount(str1, str2) {\n const str1Hash = {};\n let fragment = \"\";\n let lastIndex = -Infinity;\n let count = 0;\n\n //O(str1.length)\n\n for (let i = 0; i < str1.length; i++) {\n let letter = str1[i];\n if (str1Hash[letter]) {\n str1Hash[letter].push(i);\n } else {\n str1Hash[letter] = [i];\n }\n\n }\n\n //O(str2.length) * O(indices.length)\n\n for (let j = 0; j < str2.length; j++) {\n let letter = str2[j];\n \n if (str1Hash[letter]) {\n if (fragment.length === 0) {\n fragment = letter;\n lastIndex = str1Hash[letter][0];\n count++;\n } else {\n let letterIndices = str1Hash[letter];\n let foundIdx = false;\n\n for (let idx of letterIndices) {\n if (idx > lastIndex) {\n fragment += letter;\n lastIndex = idx;\n foundIdx = true;\n }\n }\n\n console.log(fragment, count);\n if (!foundIdx) {\n count++;\n fragment = letter;\n lastIndex = str1Hash[letter][0];\n } else if (foundIdx === str2.length - 1) {\n count ++;\n }\n \n }\n } else {\n return -1;\n }\n\n\n }\n\n return count;\n\n\n}", "function repeatChar (x, y)\n{ var z= x.split(\"\");\n var output = z.reduce( (c,l ) => \n {\n if (l===y)\n c++;\n return c;\n } , 0 ) \n\nreturn output\n }", "function repeatedChar(string) {\n var memo = {};\n var repeated = false;\n\n string.forEach(function(letter) {\n if (memo[letter]) {\n repeated = true;\n }\n memo[letter] = true;\n });\n return repeated;\n}", "function repeatedChars(str) {\n const charMap = {};\n // Go through each char in the string\n for (let char of str) {\n // If char exists in charMap, add 1 to it,\n // otherwise set it to 1.\n charMap[char] = charMap[char] + 1 || 1;\n }\n // Determine the repeated chars\n const repeated = Object.keys(charMap).reduce(\n (rep, key) => (charMap[key] > 1 ? [key, ...rep] : rep),\n []\n );\n // Return the repeated\n return repeated;\n}", "function duplicateCount(text) {\n let new_text = text.toLowerCase().split(\"\");\n console.log(new_text);\n\n let count = 0;\n for (let i = 0; i < new_text.length; i++) {\n let br = 1;\n for (let j = i + 1; j < new_text.length; j++) {\n if (new_text[i] == new_text[j]) {\n count++;\n br = 0;\n break;\n }\n }\n if (br == 0) {\n new_text = new_text.filter(elem => elem != new_text[i])\n i = -1; continue;\n }\n }\n return count;\n}", "function string(p1) {\n let string = p1.split(\"\")\n let sub = []\n let sub2 = []\n let count = 0\n for (i = 0; i < string.length; i++) {\n if (!sub.includes(string[i]) && count === 2) {\n if (sub2.length < sub.length) {\n sub2 = sub\n }\n count = 0\n sub = []\n let pos = 1\n let start = string[i - 1]\n for (j = i-1; j > 0; j--) {\n if (string[j] == start) {\n pos++\n } else {\n break;\n }\n }\n i = i - pos;\n } else if (sub.includes(string[i])) {\n sub.push(string[i])\n } else if (count < 2) {\n sub.push(string[i])\n count++\n }\n }\n\n return sub2\n}", "function find(s) {\n let map = {}\n for (let i = 0; i < s.length; i++) {\n map[s[i]] = 0\n }\n\n let start = 0\n let end = 0\n let maxLen = 0\n let counter = 0\n\n while (end < s.length) {\n let c1 = s[end]\n\n if (map[c1] === 0) counter++\n map[c1]++\n end++\n\n while (counter > 2) {\n let c2 = s[start]\n\n if (map[c2] === 1) counter--\n map[c2]--\n start++\n }\n maxLen = Math.max(maxLen, end - start);\n }\n return maxLen\n}", "function hasRepeatingChars() {\n //\n}", "function solve2(s) {\n // Write your code here\n let ret_str = ''\n for (let i = 0; i < s.length; i++) {\n if (s[i] !== s[i+1] || i + 1 > s.length) ret_str += s[i]\n }\n // console.log(ret_str)\n return ret_str\n}", "function repeatedString(s, n) {\n const length = s.length\n const times = Math.floor(n/length)\n const remain = n - times * length\n\n let as = 0\n for (let j = 0; j < s.length; j++) {\n if (s[j] === \"a\") {\n as++\n }\n }\n\n as *= times\n\n for (let i = 0; i < remain; i++) {\n if (s[i] === \"a\") {\n as++\n }\n }\n\n return as\n\n\n\n}", "function rowGood(board){\r\n for(var i = 0; i<9; i++){\r\n var cur = []\r\n for(var j = 0; j<9; j++){\r\n // determines whether a string contains the characters of a specified string\r\n if(cur.includes(board[i][j])){\r\n return false\r\n }\r\n else if(board[i][j] != null){\r\n //pushes new item to end of array\r\n cur.push(board[i][j])\r\n }\r\n }\r\n }\r\n return true\r\n}", "function runLength(string) {\n var output = [];\n var counter = 1;\n if (string === '' || string === null) {\n return string;\n }\n for (var i = 0; i < string.length; i++){\n if(string[i] === string[i+1]){\n counter++;\n }\n output.push(counter + string[i]);\n }\n counter = 1;\n }", "function checkRepeats( str ) {\n const regex = /(\\w)\\1+/g;\n return regex.test( str );\n}", "function exist(board, word) {\n word = word.split('');\n \n function verify(row, col, matrix, path) {\n if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length || matrix[row][col] !== word[path] || path > word.length) {\n return false;\n }\n\n matrix[row][col] = '#';\n path++;\n \n if (path === word.length) return true;\n if(verify(row-1, col, matrix, path)) return true;\n if(verify(row+1,col, matrix, path)) return true;\n if(verify(row, col-1, matrix, path)) return true;\n if(verify(row, col+1, matrix, path)) return true;\n\n matrix[row][col] = word[--path]; // Backtrack\n return false;\n }\n\n for (let i = 0; i < board.length; i++) {\n for (let j = 0; j < board[i].length; j++) {\n if (verify(i, j, board, 0)) return true; \n }\n }\n return false;\n}", "function permutationsWithDupes(\n str,\n prefix = \"\",\n result = [],\n perms = new Set()\n) {}", "function solution(str) {\n // write your code in JavaScript (Node.js 8.9.4)\n\n // substring - semi alternating - should not have more than 2 repititions\n // hmm so temo shuld be 2 and we should have a system to keep resetting it?\n // we need a result and a temp to keep count and need to update them as we find // consecutive characters\n\n let len = str.length;\n // corner condition\n if (len < 3) return len;\n\n let temp = 2,\n result = 2;\n\n for (let i = 2; i < len; i++) {\n if (str.charAt(i) !== str.charAt(i - 1) ||\n str.charAt(i) !== str.charAt(i - 2)) {\n temp++; // looking for consecutive characters\n } else {\n result = Math.max(result, temp);\n // reset temp\n temp = 2;\n }\n }\n result = Math.max(result, temp);\n return result;\n}", "function findColumn(string, col, tabSize, strict) {\n for (let i = 0, n = 0;;) {\n if (n >= col)\n return i;\n if (i == string.length)\n break;\n n += string.charCodeAt(i) == 9 ? tabSize - (n % tabSize) : 1;\n i = findClusterBreak(string, i);\n }\n return strict === true ? -1 : string.length;\n}", "function removeDupes2(str) {\n if (!str) {\n return \"please pass in valid input\";\n }\n\n var len = str.length,\n map = new Array(26),\n nodupe = \"\",\n i;\n\n for(i=0; i<len; i++) {\n if (map.indexOf(str[i]) === -1) {\n nodupe += str[i];\n map.push(str[i]);\n }\n }\n\n return nodupe;\n}", "function longestRun(str) {\n var longestLen = 1;\n var longRun = [0, 0];\n\n for (var i = 0; i < str.length - 1; i++) {\n var currRunLen = 0;\n j = i + 1;\n \n while (str[j] === str[i]) {\n currRunLen++;\n if (currRunLen > longestLen) {\n longRun = [i, j]\n }\n j++;\n }\n\n i = j;\n }\n\n return longRun;\n\n}" ]
[ "0.64090353", "0.6310678", "0.6158158", "0.6131276", "0.6004883", "0.5901247", "0.58641255", "0.5836641", "0.5804886", "0.5804886", "0.5772457", "0.57702786", "0.5694318", "0.5652316", "0.56475806", "0.5642972", "0.5632896", "0.56316215", "0.5631294", "0.5619154", "0.5592194", "0.5547972", "0.5547972", "0.5538055", "0.5530831", "0.55201155", "0.55110794", "0.5508387", "0.550512", "0.5487052", "0.54810613", "0.54539853", "0.5451905", "0.54281163", "0.5427536", "0.5425035", "0.54231447", "0.54130626", "0.5411794", "0.5396664", "0.5376982", "0.536006", "0.5354176", "0.5348104", "0.53468865", "0.5345059", "0.53369063", "0.5336837", "0.533217", "0.53316486", "0.5330141", "0.5292597", "0.5292338", "0.52743566", "0.5270187", "0.52680975", "0.52629954", "0.5262587", "0.5260334", "0.52541", "0.5228811", "0.52248776", "0.5216094", "0.52128345", "0.5199962", "0.5187065", "0.5176089", "0.5169729", "0.5161691", "0.5146113", "0.5140684", "0.5137122", "0.51333576", "0.51286644", "0.51253694", "0.51214325", "0.5113927", "0.51082003", "0.5105597", "0.51026446", "0.5096809", "0.50940406", "0.5083196", "0.507341", "0.5064592", "0.50622237", "0.5061621", "0.50614476", "0.50606614", "0.50594366", "0.5059058", "0.5054029", "0.50480497", "0.50478816", "0.5044482", "0.5044113", "0.5043294", "0.50415236", "0.50413215" ]
0.68606716
1
look for string match for sequences beginning at [r0,c0] and [r1,c1]. direction of sequences is determined by (dr0, dc0) and (dr1, dc1). "result" is an array that tracks the maximum matched sequence and occurrence positions.
function matches(result, r0, c0, dr0, dc0, r1, c1, dr1, dc1) { var ch1 = get(r0, c0); var ch2 = get(r1, c1); // alert("r0 " + r0 + " c0 " + c0 + " dr0 " + dr0 + " dc0 " + dc0 + " r1 " + r1 + " c1 " + c1 + " dr1 " + dr1 + " dc1 "+ dc1 + " ch1 " + ch1 + " ch2 " + ch2); if (ch1 == ch2) { result[0] += ch1; result[1][result[1].length] = new Array(getR(r0), getC(c0)); result[2][result[2].length] = new Array(getR(r1), getC(c1)); matches(result, (r0+dr0), (c0+dc0), dr0, dc0, (r1+dr1), (c1+dc1), dr1, dc1); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "findNextMatchSync(string, startPosition) {\r\n if (startPosition == null) {\r\n startPosition = 0;\r\n }\r\n startPosition = this.convertToNumber(startPosition);\r\n let onigNativeInfo = cache.get(this);\r\n let status = 0;\r\n if (!onigNativeInfo) {\r\n const regexTAddrRecieverPtr = onigasmH_1.onigasmH._malloc(4);\r\n const regexTPtrs = [];\r\n for (let i = 0; i < this.sources.length; i++) {\r\n const pattern = this.sources[i];\r\n status = onigasmH_1.onigasmH.ccall('compilePattern', 'number', ['string', 'number'], [pattern, regexTAddrRecieverPtr]);\r\n if (status !== 0) {\r\n const errString = onigasmH_1.onigasmH.ccall('getLastError', 'string');\r\n throw new Error(errString);\r\n }\r\n const regexTAddress = new Uint32Array(onigasmH_1.onigasmH.buffer, regexTAddrRecieverPtr, 1)[0];\r\n regexTPtrs.push(regexTAddress);\r\n }\r\n onigNativeInfo = {\r\n regexTPtrs: new Uint8Array(Uint32Array.from(regexTPtrs).buffer),\r\n };\r\n onigasmH_1.onigasmH._free(regexTAddrRecieverPtr);\r\n cache.set(this, onigNativeInfo);\r\n }\r\n const resultInfoReceiverPtr = onigasmH_1.onigasmH._malloc(8);\r\n const onigString = string instanceof OnigString_1.default ? string : new OnigString_1.default(this.convertToString(string));\r\n const strPtr = onigasmH_1.onigasmH._malloc(onigString.utf8Bytes.length);\r\n onigasmH_1.onigasmH.HEAPU8.set(onigString.utf8Bytes, strPtr);\r\n status = onigasmH_1.onigasmH.ccall('findBestMatch', 'number', ['array', 'number', 'number', 'number', 'number', 'number'], [\r\n // regex_t **patterns\r\n onigNativeInfo.regexTPtrs,\r\n // int patternCount\r\n this.sources.length,\r\n // UChar *utf8String\r\n strPtr,\r\n // int strLen\r\n onigString.utf8Bytes.length - 1,\r\n // int startOffset\r\n onigString.convertUtf16OffsetToUtf8(startPosition),\r\n // int *resultInfo\r\n resultInfoReceiverPtr,\r\n ]);\r\n if (status !== 0) {\r\n const errString = onigasmH_1.onigasmH.ccall('getLastError', 'string');\r\n throw new Error(errString);\r\n }\r\n const [\r\n // The index of pattern which matched the string at least offset from 0 (start)\r\n bestPatternIdx, \r\n // Begin address of capture info encoded as pairs\r\n // like [start, end, start, end, start, end, ...]\r\n // - first start-end pair is entire match (index 0 and 1)\r\n // - subsequent pairs are capture groups (2, 3 = first capture group, 4, 5 = second capture group and so on)\r\n encodedResultBeginAddress, \r\n // Length of the [start, end, ...] sequence so we know how much memory to read (will always be 0 or multiple of 2)\r\n encodedResultLength,] = new Uint32Array(onigasmH_1.onigasmH.buffer, resultInfoReceiverPtr, 3);\r\n onigasmH_1.onigasmH._free(strPtr);\r\n onigasmH_1.onigasmH._free(resultInfoReceiverPtr);\r\n if (encodedResultLength > 0) {\r\n const encodedResult = new Uint32Array(onigasmH_1.onigasmH.buffer, encodedResultBeginAddress, encodedResultLength);\r\n const captureIndices = [];\r\n let i = 0;\r\n let captureIdx = 0;\r\n while (i < encodedResultLength) {\r\n const index = captureIdx++;\r\n let start = encodedResult[i++];\r\n let end = encodedResult[i++];\r\n if (onigString.hasMultiByteCharacters) {\r\n start = onigString.convertUtf8OffsetToUtf16(start);\r\n end = onigString.convertUtf8OffsetToUtf16(end);\r\n }\r\n captureIndices.push({\r\n end,\r\n index,\r\n length: end - start,\r\n start,\r\n });\r\n }\r\n onigasmH_1.onigasmH._free(encodedResultBeginAddress);\r\n return {\r\n captureIndices,\r\n index: bestPatternIdx,\r\n scanner: this,\r\n };\r\n }\r\n return null;\r\n }", "findNextMatchSync(string, startPosition) {\n if (startPosition == null) {\n startPosition = 0;\n }\n startPosition = this.convertToNumber(startPosition);\n let onigNativeInfo = cache.get(this);\n let status = 0;\n if (!onigNativeInfo) {\n const regexTAddrRecieverPtr = onigasmH_1.onigasmH._malloc(4);\n const regexTPtrs = [];\n for (let i = 0; i < this.sources.length; i++) {\n const pattern = this.sources[i];\n const patternStrPtr = mallocAndWriteString(new OnigString_1.default(pattern));\n status = onigasmH_1.onigasmH._compilePattern(patternStrPtr, regexTAddrRecieverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const regexTAddress = onigasmH_1.onigasmH.HEAP32[regexTAddrRecieverPtr / 4];\n regexTPtrs.push(regexTAddress);\n onigasmH_1.onigasmH._free(patternStrPtr);\n }\n onigNativeInfo = {\n regexTPtrs: new Uint8Array(Uint32Array.from(regexTPtrs).buffer),\n };\n onigasmH_1.onigasmH._free(regexTAddrRecieverPtr);\n cache.set(this, onigNativeInfo);\n }\n const onigString = string instanceof OnigString_1.default ? string : new OnigString_1.default(this.convertToString(string));\n const strPtr = mallocAndWriteString(onigString);\n const resultInfoReceiverPtr = onigasmH_1.onigasmH._malloc(8);\n const regexTPtrsPtr = onigasmH_1.onigasmH._malloc(onigNativeInfo.regexTPtrs.length);\n onigasmH_1.onigasmH.HEAPU8.set(onigNativeInfo.regexTPtrs, regexTPtrsPtr);\n status = onigasmH_1.onigasmH._findBestMatch(\n // regex_t **patterns\n regexTPtrsPtr, \n // int patternCount\n this.sources.length, \n // UChar *utf8String\n strPtr, \n // int strLen\n onigString.utf8Bytes.length - 1, \n // int startOffset\n onigString.convertUtf16OffsetToUtf8(startPosition), \n // int *resultInfo\n resultInfoReceiverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const [\n // The index of pattern which matched the string at least offset from 0 (start)\n bestPatternIdx, \n // Begin address of capture info encoded as pairs\n // like [start, end, start, end, start, end, ...]\n // - first start-end pair is entire match (index 0 and 1)\n // - subsequent pairs are capture groups (2, 3 = first capture group, 4, 5 = second capture group and so on)\n encodedResultBeginAddress, \n // Length of the [start, end, ...] sequence so we know how much memory to read (will always be 0 or multiple of 2)\n encodedResultLength,] = new Uint32Array(onigasmH_1.onigasmH.HEAPU32.buffer, resultInfoReceiverPtr, 3);\n onigasmH_1.onigasmH._free(strPtr);\n onigasmH_1.onigasmH._free(resultInfoReceiverPtr);\n onigasmH_1.onigasmH._free(regexTPtrsPtr);\n if (encodedResultLength > 0) {\n const encodedResult = new Uint32Array(onigasmH_1.onigasmH.HEAPU32.buffer, encodedResultBeginAddress, encodedResultLength);\n const captureIndices = [];\n let i = 0;\n let captureIdx = 0;\n while (i < encodedResultLength) {\n const index = captureIdx++;\n let start = encodedResult[i++];\n let end = encodedResult[i++];\n if (onigString.hasMultiByteCharacters) {\n start = onigString.convertUtf8OffsetToUtf16(start);\n end = onigString.convertUtf8OffsetToUtf16(end);\n }\n captureIndices.push({\n end,\n index,\n length: end - start,\n start,\n });\n }\n onigasmH_1.onigasmH._free(encodedResultBeginAddress);\n return {\n captureIndices,\n index: bestPatternIdx,\n scanner: this,\n };\n }\n return null;\n }", "findNextMatchSync(string, startPosition) {\n if (startPosition == null) {\n startPosition = 0;\n }\n startPosition = this.convertToNumber(startPosition);\n let onigNativeInfo = cache.get(this);\n let status = 0;\n if (!onigNativeInfo) {\n const regexTAddrRecieverPtr = onigasmH_1.onigasmH._malloc(4);\n const regexTPtrs = [];\n for (let i = 0; i < this.sources.length; i++) {\n const pattern = this.sources[i];\n const patternStrPtr = mallocAndWriteString(new OnigString_1.default(pattern));\n status = onigasmH_1.onigasmH._compilePattern(patternStrPtr, regexTAddrRecieverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const regexTAddress = onigasmH_1.onigasmH.HEAP32[regexTAddrRecieverPtr / 4];\n regexTPtrs.push(regexTAddress);\n onigasmH_1.onigasmH._free(patternStrPtr);\n }\n onigNativeInfo = {\n regexTPtrs: new Uint8Array(Uint32Array.from(regexTPtrs).buffer),\n };\n onigasmH_1.onigasmH._free(regexTAddrRecieverPtr);\n cache.set(this, onigNativeInfo);\n }\n const onigString = string instanceof OnigString_1.default ? string : new OnigString_1.default(this.convertToString(string));\n const strPtr = mallocAndWriteString(onigString);\n const resultInfoReceiverPtr = onigasmH_1.onigasmH._malloc(8);\n const regexTPtrsPtr = onigasmH_1.onigasmH._malloc(onigNativeInfo.regexTPtrs.length);\n onigasmH_1.onigasmH.HEAPU8.set(onigNativeInfo.regexTPtrs, regexTPtrsPtr);\n status = onigasmH_1.onigasmH._findBestMatch(\n // regex_t **patterns\n regexTPtrsPtr, \n // int patternCount\n this.sources.length, \n // UChar *utf8String\n strPtr, \n // int strLen\n onigString.utf8Bytes.length - 1, \n // int startOffset\n onigString.convertUtf16OffsetToUtf8(startPosition), \n // int *resultInfo\n resultInfoReceiverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const [\n // The index of pattern which matched the string at least offset from 0 (start)\n bestPatternIdx, \n // Begin address of capture info encoded as pairs\n // like [start, end, start, end, start, end, ...]\n // - first start-end pair is entire match (index 0 and 1)\n // - subsequent pairs are capture groups (2, 3 = first capture group, 4, 5 = second capture group and so on)\n encodedResultBeginAddress, \n // Length of the [start, end, ...] sequence so we know how much memory to read (will always be 0 or multiple of 2)\n encodedResultLength,] = new Uint32Array(onigasmH_1.onigasmH.HEAPU32.buffer, resultInfoReceiverPtr, 3);\n onigasmH_1.onigasmH._free(strPtr);\n onigasmH_1.onigasmH._free(resultInfoReceiverPtr);\n onigasmH_1.onigasmH._free(regexTPtrsPtr);\n if (encodedResultLength > 0) {\n const encodedResult = new Uint32Array(onigasmH_1.onigasmH.HEAPU32.buffer, encodedResultBeginAddress, encodedResultLength);\n const captureIndices = [];\n let i = 0;\n let captureIdx = 0;\n while (i < encodedResultLength) {\n const index = captureIdx++;\n let start = encodedResult[i++];\n let end = encodedResult[i++];\n if (onigString.hasMultiByteCharacters) {\n start = onigString.convertUtf8OffsetToUtf16(start);\n end = onigString.convertUtf8OffsetToUtf16(end);\n }\n captureIndices.push({\n end,\n index,\n length: end - start,\n start,\n });\n }\n onigasmH_1.onigasmH._free(encodedResultBeginAddress);\n return {\n captureIndices,\n index: bestPatternIdx,\n scanner: this,\n };\n }\n return null;\n }", "findNextMatchSync(string, startPosition) {\n if (startPosition == null) {\n startPosition = 0;\n }\n startPosition = this.convertToNumber(startPosition);\n let onigNativeInfo = cache.get(this);\n let status = 0;\n if (!onigNativeInfo) {\n const regexTAddrRecieverPtr = onigasmH_1$1.onigasmH._malloc(4);\n const regexTPtrs = [];\n for (let i = 0; i < this.sources.length; i++) {\n const pattern = this.sources[i];\n const patternStrPtr = mallocAndWriteString(new OnigString_1$1.default(pattern));\n status = onigasmH_1$1.onigasmH._compilePattern(patternStrPtr, regexTAddrRecieverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1$1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const regexTAddress = onigasmH_1$1.onigasmH.HEAP32[regexTAddrRecieverPtr / 4];\n regexTPtrs.push(regexTAddress);\n onigasmH_1$1.onigasmH._free(patternStrPtr);\n }\n onigNativeInfo = {\n regexTPtrs: new Uint8Array(Uint32Array.from(regexTPtrs).buffer),\n };\n onigasmH_1$1.onigasmH._free(regexTAddrRecieverPtr);\n cache.set(this, onigNativeInfo);\n }\n const onigString = string instanceof OnigString_1$1.default ? string : new OnigString_1$1.default(this.convertToString(string));\n const strPtr = mallocAndWriteString(onigString);\n const resultInfoReceiverPtr = onigasmH_1$1.onigasmH._malloc(8);\n const regexTPtrsPtr = onigasmH_1$1.onigasmH._malloc(onigNativeInfo.regexTPtrs.length);\n onigasmH_1$1.onigasmH.HEAPU8.set(onigNativeInfo.regexTPtrs, regexTPtrsPtr);\n status = onigasmH_1$1.onigasmH._findBestMatch(\n // regex_t **patterns\n regexTPtrsPtr, \n // int patternCount\n this.sources.length, \n // UChar *utf8String\n strPtr, \n // int strLen\n onigString.utf8Bytes.length - 1, \n // int startOffset\n onigString.convertUtf16OffsetToUtf8(startPosition), \n // int *resultInfo\n resultInfoReceiverPtr);\n if (status !== 0) {\n const errMessage = convertUTF8BytesFromPtrToString(onigasmH_1$1.onigasmH._getLastError());\n throw new Error(errMessage);\n }\n const [\n // The index of pattern which matched the string at least offset from 0 (start)\n bestPatternIdx, \n // Begin address of capture info encoded as pairs\n // like [start, end, start, end, start, end, ...]\n // - first start-end pair is entire match (index 0 and 1)\n // - subsequent pairs are capture groups (2, 3 = first capture group, 4, 5 = second capture group and so on)\n encodedResultBeginAddress, \n // Length of the [start, end, ...] sequence so we know how much memory to read (will always be 0 or multiple of 2)\n encodedResultLength,] = new Uint32Array(onigasmH_1$1.onigasmH.HEAPU32.buffer, resultInfoReceiverPtr, 3);\n onigasmH_1$1.onigasmH._free(strPtr);\n onigasmH_1$1.onigasmH._free(resultInfoReceiverPtr);\n onigasmH_1$1.onigasmH._free(regexTPtrsPtr);\n if (encodedResultLength > 0) {\n const encodedResult = new Uint32Array(onigasmH_1$1.onigasmH.HEAPU32.buffer, encodedResultBeginAddress, encodedResultLength);\n const captureIndices = [];\n let i = 0;\n let captureIdx = 0;\n while (i < encodedResultLength) {\n const index = captureIdx++;\n let start = encodedResult[i++];\n let end = encodedResult[i++];\n if (onigString.hasMultiByteCharacters) {\n start = onigString.convertUtf8OffsetToUtf16(start);\n end = onigString.convertUtf8OffsetToUtf16(end);\n }\n captureIndices.push({\n end,\n index,\n length: end - start,\n start,\n });\n }\n onigasmH_1$1.onigasmH._free(encodedResultBeginAddress);\n return {\n captureIndices,\n index: bestPatternIdx,\n scanner: this,\n };\n }\n return null;\n }", "function matchPattern(pattern,genome) {\n //console.log(pattern);\n //console.log(genome);\n //console.log(\"genome length : \" + genome.length);\n var positions = [];\n for(var i=0;i<=genome.length-pattern.length;i++) {\n var str = computeText(genome,i,pattern.length);\n // console.log(str);\n if(str==pattern) {\n positions.push(i);\n }\n }\n return positions;\n /*\n var output = \"\";\n for(var i=0;i<positions.length;i++) {\n output = output + positions[i] + \" \";\n }\n return output;\n */\n}", "function findInSequence() {\n\tvar beginMatch = 0;\n\tvar endMatch = 0;\n\tvar i = 0;\n\tvar specChar = RegExp('[X]');\n\tvar test = specChar.exec(searchMotif);\n\tconsole.log(test);\n\tvar xs = [];\n\tvar generalCase = false;\n\tvar splitMotif = searchMotif.split(\"\");\n\tif (test != null && searchMotif.length >= 2){\n\t\t\n\t\tfor (var i = 0; i < searchMotif.length; i++){\n\t\t\tvar char = searchMotif.charAt(i);\n\t\t\tif(char == \"X\"){\n\t\t\t\txs.push(i);\n\t\t\t}\n\t\t}\n\t\tgeneralCase = true;\n\t}\nwhile (endMatch < seq.length){\n\tendMatch = beginMatch + searchMotif.length;\n\tvar currentlyChecked = seq.substring(beginMatch, endMatch);\n\t//check for spaces or new lines within the search portion of the sequence\n\tif(generalCase){\n\t\tvar currCheckedSplit = currentlyChecked.split(\"\");\n\t\t//process out x's\n\t\tfor(var i = 0; i < splitMotif.length; i++){\n\t\t\tif(xs[i] != null){\n\t\t\tcurrCheckedSplit.splice(xs[i],1,\"X\");\n\t\t\t}\n\t\t}\n\t\tcurrentlyChecked = currCheckedSplit.join(\"\");\n\t}\n\tif(currentlyChecked === searchMotif){\n\t\tvar indices = [beginMatch, endMatch];\n\t\tindicesOfMatches.push(indices);\n\t\tbeginMatch = endMatch;\n\t}\n\telse{\n\t\tbeginMatch++;\n\t}\n\tcurrentlyChecked = \"\";\n}\n\tinsertHighlightSpans();\n}", "function searchOnDnaMatrix(dna, sequence, row, col, matchesFound) {\n var numSeq = 0;\n\n // try to search sequence only if the letter from the dna is part of the sequence\n // as the first position is already matched, start from the next one\n if (dna[row][col] === sequence[0]) {\n // there are only 4 possible directions to search: horizontal, vertical, main diagonal and secondary diagonal\n\n // Horizontal matches\n var n;\n var positions = [row + ',' + col];\n for (n = 1; n < sequence.length; n++) {\n if (col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row][col + n] === 'undefined' || dna[row][col + n] !== sequence[n])\n break;\n\n positions.push( row + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Vertical matches\n for (n = 1; n < sequence.length; n++) {\n if (row + n >= dna.length || row + n < 0) \n break;\n\n if (typeof dna[row + n][col] === 'undefined' || dna[row + n][col] !== sequence[n])\n break;\n\n positions.push( (row + n) + ',' + col );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Main diagonal matches \n for (n = 1; n < sequence.length; n++) {\n if (row + n >= dna.length || row + n < 0 || col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row + n][col + n] === 'undefined' || dna[row + n][col + n] !== sequence[n])\n break;\n\n positions.push( (row + n) + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n // Secondary diagonal matches \n for (n = 1; n < sequence.length; n++) {\n if (row - n >= dna.length || row - n < 0 || col + n >= dna.length || col + n < 0) \n break;\n\n if (typeof dna[row - n][col + n] === 'undefined' || dna[row - n][col + n] !== sequence[n])\n break;\n\n positions.push( (row - n) + ',' + (col + n) );\n }\n\n // if the length of the sequence has the same value as n (length of the sequence in the dna) increment numSeq\n if (sequence.length === n) {\n numSeq++;\n matchesFound[sequence].push( positions );\n }\n\n }\n\n return numSeq; \n}", "function searchSequences(dna, sequences) {\n\n var numMatchesSeq = 0;\n // store the positions of the letters that were matched\n var matchesFound = [];\n sequences.forEach(seq => {\n matchesFound[seq] = [];\n });\n \n // go through all the sequences\n sequences.forEach(seq => {\n for (let r = 0; r < dna.length; r++) {\n for (let c = 0; c < dna.length; c++) {\n numMatchesSeq += searchOnDnaMatrix(dna, seq, r, c, matchesFound);\n }\n }\n });\n\n // if a sequence on the dna matrix is longer than the sequence to be matched, it will be duplicated. Let's fix that.\n numMatchesSeq = removePossibleDuplicates(matchesFound, sequences, numMatchesSeq);\n\n return numMatchesSeq;\n}", "function Match(m,n)\n{\n if(seq1.charAt(m)==seq2.charAt(n))\n return 1;\n else\n return -1;\n}", "matches(text) {\n let i = 0;\n let max_acc;\n const matches = [];\n\n while (i < text.length) {\n // simulate on input starting at idx i\n max_acc = this.nfa.simulate(text, i);\n\n if (max_acc == null) {\n // no match, move onto next idx\n i++;\n } else {\n // extract the longest match\n matches.push(new Match(i, max_acc, text.substring(i, max_acc)));\n\n if (i == max_acc) {\n // empty match, increment, so as to move along\n i++;\n } else {\n // jump to end position of match\n i = max_acc;\n }\n }\n }\n\n return matches;\n }", "function findPattern(start, src){\n\tif (start === src.length){\n\t\treturn \"No matching patterns\"; \n\t}\n\tvar l1, l2, l3; \n\tl1 = matchLinePattern(src, start, 5); \n\tif (matchLinePatternStrict(src, l1[0]+l1[1], 7)){\n\t\tl2 = matchLinePatternStrict(src, l1[0]+l1[1], 7)\n\t\tif (matchLinePatternStrict(src, l2[0]+l2[1], 5)){\n\t\t\tl3 = matchLinePatternStrict(src, l2[0]+l2[1], 5); \n\t\t\treturn [l1, l2, l3]; \n\t\t}\n\t}\n\treturn findPattern(start+1, src); \n}", "function getTextFromRegexMatch(resultArray, arrayOfMatchPositionsToReturn, lengthOfMatchPositions) {\n\n\n\n }", "function matchSegment(seg1, seg2, r, result) {\n var a = seg1[0],\n b = seg1[1],\n c = seg2[0],\n d = seg2[1],\n len = result.length;\n\n var ap = closePoint(a, c, d, r),\n bp = closePoint(b, c, d, r);\n\n // a----b\n // c---ap---bp---d\n if (ap !== null && bp !== null) return true; // fully covered\n\n var cp = closePoint(c, a, b, r),\n dp = closePoint(d, a, b, r);\n\n if (cp !== null && cp === dp) return false; // degenerate case, no overlap\n\n if (cp !== null && dp !== null) {\n var cpp = segPoint(a, b, cp);\n var dpp = segPoint(a, b, dp);\n\n if (equals(cpp, dpp)) return false; // degenerate case\n\n // a---cp---dp---b\n // c----d\n if (cp < dp) {\n if (!equals(a, cpp)) result.push([a, cpp]);\n if (!equals(dpp, b)) result.push([dpp, b]);\n\n // a---dp---cp---b\n // d----c\n } else {\n if (!equals(a, dpp)) result.push([a, dpp]);\n if (!equals(cpp, b)) result.push([cpp, b]);\n }\n\n } else if (cp !== null) {\n var cpp = segPoint(a, b, cp);\n\n // a----cp---b\n // d---ap---c\n if (ap !== null && !equals(a, cpp)) result.push([cpp, b]);\n\n // a---cp---b\n // c----bp---d\n else if (bp !== null && !equals(cpp, b)) result.push([a, cpp]);\n\n } else if (dp !== null) {\n var dpp = segPoint(a, b, dp);\n\n // a---dp---b\n // d----bp---c\n if (bp !== null && !equals(dpp, b)) result.push([a, dpp]);\n\n // a----dp---b\n // c---ap---d\n else if (ap !== null && !equals(a, dpp)) result.push([dpp, b]);\n }\n\n return result.length !== len; // segment processed\n}", "searchSync(string, startPosition) {\r\n let match;\r\n if (startPosition == null) {\r\n startPosition = 0;\r\n }\r\n match = this.scanner.findNextMatchSync(string, startPosition);\r\n return this.captureIndicesForMatch(string, match);\r\n }", "function lookAheadCount(nfa, testCombineIndex)\n{ var testString=inputString.value;// var s=inputString.value; \n var localCombineIndex={\n localIndex:[],\n localFinalIndex:[]\n\n };\nlocalCombineIndex.localIndex=testCombineIndex.myIndex;\n//localCombineIndex.myFinalIndex=testCombineIndex.myFinalIndex;\n var CurrentActive=[];\n var NextActive=[];\n var MatchCount=0;\n var temp=[];\n \n CurrentActive=_.union(CurrentActive, nfa.states);\n for(var i=0; i<testString.length-1; i=i+1)\n { for(var j=0; j<CurrentActive.length; j++)\n {\n if(CurrentActive[j]==0)\n continue;\n var t=localCombineIndex.localIndex[CurrentActive[j]][testString[i]][testString[i+1]];\n NextActive=_.union(NextActive, t);\n }\n\n // console.log(\"check1: \"+CurrentActive);\n \n temp=_.intersection(NextActive, [0]);\n if(temp[0]!=0)\n {\n MatchCount = MatchCount+1;\n }\n\n \n CurrentActive=NextActive;\n // console.log(\"count: \"+MatchCount);\n NextActive=[];\n }\n // var FinalDest=[];\n // console.log(\"temp0: \"+ temp);\n var bValue=false;\n if(MatchCount==testString.length-1 )\n {\n for(var k=0; k<CurrentActive.length; k++)\n {\n for(var l=0; l<nfa.trans.length; l++)\n {\n if(nfa.trans[l].src==CurrentActive[k] && nfa.trans[l].ch==testString[testString.length-1])\n {\n if(_.contains(nfa.trans[l].dest, 0))\n {\n bValue=true;\n break;\n \n }\n }\n }\n }\n\n } \n ///Print final value: \nconsole.log(\"Match or not: \"+bValue);\n}", "function matchingStrings(strings, queries) {\nstrings=strings.sort();\nlet x=0,n=0;\nlet arr=[];\nfor(let i of queries){\nif(strings.includes(i)){\n arr.push(1+strings.lastIndexOf(i)-strings.indexOf(i));\n}else{\n arr.push(0);\n}\n\n}\n return arr;\n}", "searchSync(string, startPosition) {\n let match;\n if (startPosition == null) {\n startPosition = 0;\n }\n match = this.scanner.findNextMatchSync(string, startPosition);\n return this.captureIndicesForMatch(string, match);\n }", "searchSync(string, startPosition) {\n let match;\n if (startPosition == null) {\n startPosition = 0;\n }\n match = this.scanner.findNextMatchSync(string, startPosition);\n return this.captureIndicesForMatch(string, match);\n }", "function match(title, q) {\n const ts = Array.from(title);\n const qs = Array.from(q);\n const matches = [{ next: 0, density: 0, length: 0 }];\n for (var i = 0; i < ts.length; i++) {\n var c; // Current match\n for (var j = 0; j < matches.length; j++) {\n c = matches[j]\n if (c.length === qs.length || !equalsCaseInsensitively(ts[i], qs[c.next])) {\n continue;\n }\n\n // Update the current match\n if (c.length === 0) {\n c.spans = [{start: i, end: i + 1}]\n } else {\n c.density += i - c.last;\n const lastSpan = c.spans[c.spans.length - 1]\n if (lastSpan.end === i)\n lastSpan.end = i + 1\n else\n c.spans.push({ start: i, end: i + 1 })\n }\n c.next += 1;\n c.last = i;\n c.length += 1;\n\n const p = matches[j - 1] // Previous match\n // Compare the current and previous matches\n if (j === 0 || c.length !== p.length) {\n continue\n }\n if (lt(c, p)) {\n console.debug(\"Comparing:\", \"text:\", title, \": q:\", q, \"current:\", JSON.stringify(c), \"< previous:\", JSON.stringify(matches[j - 1]))\n matches.splice(j - 1, 1);\n j--; \n } else if (p.last === i) {\n console.debug(\"Comparing:\", \"text:\", title, \": q:\", q, \"current:\", JSON.stringify(c), \">= previous:\", JSON.stringify(matches[j - 1]))\n matches.splice(j, 1);\n j--; \n }\n }\n // Ensure the last match to be a 'zero' awaiting\n if (c.length !== 0)\n matches.push({ next: 0, density: 0, length: 0 });\n }\n console.debug(\"Matching:\", \"text:\", title, \": q:\", q,\":final stacks:\", matches)\n return matches[0];\n}", "function longestCommonSubsequence(text1, text2) {\n /*\n - Think of the rows as the outer loop and the columns as the inner loop.\n - Use 2 pointers, one for each string (imagine it being a matrix). One is for rows and the other for columns.\n - Rows -> text1\n - Columns -> text2\n - Like in the Coin Change problem, build the matrix and traverse it backwards when necessary.\n - When initializing the matrix, add an additional row and column BEFORE and initialize them to 0s.\n - If both characters match, move 1 row and col forward and add 1 to it (down diagonally).\n - If characters don't match, calculate the max of going back in the col (cell above) and going back in the row (cell to the left). Doing this we carry forward the maximum common subsequence\n X a b c d e X a b c d e\n X 0 0 0 0 0 0 X 0 0 0 0 0 0\n a 0 1 0 0 0 0 a 0 1 1 1 1 1\n c 0 0 0 0 0 0 c 0 1 1 2 2 2\n e 0 0 0 0 0 0 e 0 3 3 3 3 3\n */\n\n const dp = []\n\n // Generate the starting matrix adding the additional row and col. Fill the matrix with 0s\n for (let i = 0; i < text1.length + 1; i++) {\n dp.push(Array(text2.length + 1).fill(0))\n }\n\n // Scan from left to right through the string\n for (let i = 0; i < text1.length; i++) {\n for (let j = 0; j < text2.length; j++) {\n // If the values match move 1 row and col forward and add 1 to it (down-right diagonally).\n if (text1[i] === text2[j]) {\n // The new value will be the diagonal\n const diagonal = dp[i][j]\n // Calculate the cell taking into account the offset of the additional row/col\n // Increment by the value of the diagonal\n dp[i + 1][j + 1] = diagonal + 1\n }\n // If characters don't match carry forward the maximum common subsequence\n else {\n const above = dp[i][j + 1]\n const left = dp[i + 1][j]\n // Calculate the max of the cell above and the one to the left\n dp[i + 1][j + 1] = Math.max(above, left)\n }\n }\n }\n\n // If we found the LCS the it's length would be saved in the bottom-right corner.\n // If no subsequence was found the value of the last cell will be 0\n return dp[text1.length][text2.length]\n}", "match(input, start, end){}", "function SearchingChallenge1(str) {\n const array = [...str];\n const k = Number(array.shift());\n\n let substring = [];\n let n = 1;\n\n let index = 0;\n\n let res = [];\n\n while (index < array.length) {\n if (substring === [] || substring.includes(array[index])) {\n substring.push(array[index]);\n index++;\n console.log(\"substring\", substring);\n } else if (!substring.includes(array[index]) && n <= k) {\n substring.push(array[index]);\n n++;\n index++;\n console.log(\"substring\", substring);\n } else {\n res.push(substring.join(\"\"));\n console.log(\"res during\", res);\n substring = [];\n n = 1;\n index--;\n console.log(\"substring after []\", substring.length);\n }\n }\n\n res.push(substring.join(\"\"));\n\n console.log(\"res final\", res);\n\n const lengths = res.map((e) => e.length);\n\n return res[lengths.indexOf(Math.max(...lengths))];\n}", "match(word) {\n if (this.pattern.length == 0)\n return this.ret(-100 /* NotFull */, []);\n if (word.length < this.pattern.length)\n return false;\n let { chars, folded, any, precise, byWord } = this;\n // For single-character queries, only match when they occur right\n // at the start\n if (chars.length == 1) {\n let first = state.codePointAt(word, 0), firstSize = state.codePointSize(first);\n let score = firstSize == word.length ? 0 : -100 /* NotFull */;\n if (first == chars[0]) ;\n else if (first == folded[0])\n score += -200 /* CaseFold */;\n else\n return false;\n return this.ret(score, [0, firstSize]);\n }\n let direct = word.indexOf(this.pattern);\n if (direct == 0)\n return this.ret(word.length == this.pattern.length ? 0 : -100 /* NotFull */, [0, this.pattern.length]);\n let len = chars.length, anyTo = 0;\n if (direct < 0) {\n for (let i = 0, e = Math.min(word.length, 200); i < e && anyTo < len;) {\n let next = state.codePointAt(word, i);\n if (next == chars[anyTo] || next == folded[anyTo])\n any[anyTo++] = i;\n i += state.codePointSize(next);\n }\n // No match, exit immediately\n if (anyTo < len)\n return false;\n }\n // This tracks the extent of the precise (non-folded, not\n // necessarily adjacent) match\n let preciseTo = 0;\n // Tracks whether there is a match that hits only characters that\n // appear to be starting words. `byWordFolded` is set to true when\n // a case folded character is encountered in such a match\n let byWordTo = 0, byWordFolded = false;\n // If we've found a partial adjacent match, these track its state\n let adjacentTo = 0, adjacentStart = -1, adjacentEnd = -1;\n let hasLower = /[a-z]/.test(word), wordAdjacent = true;\n // Go over the option's text, scanning for the various kinds of matches\n for (let i = 0, e = Math.min(word.length, 200), prevType = 0 /* NonWord */; i < e && byWordTo < len;) {\n let next = state.codePointAt(word, i);\n if (direct < 0) {\n if (preciseTo < len && next == chars[preciseTo])\n precise[preciseTo++] = i;\n if (adjacentTo < len) {\n if (next == chars[adjacentTo] || next == folded[adjacentTo]) {\n if (adjacentTo == 0)\n adjacentStart = i;\n adjacentEnd = i + 1;\n adjacentTo++;\n }\n else {\n adjacentTo = 0;\n }\n }\n }\n let ch, type = next < 0xff\n ? (next >= 48 && next <= 57 || next >= 97 && next <= 122 ? 2 /* Lower */ : next >= 65 && next <= 90 ? 1 /* Upper */ : 0 /* NonWord */)\n : ((ch = state.fromCodePoint(next)) != ch.toLowerCase() ? 1 /* Upper */ : ch != ch.toUpperCase() ? 2 /* Lower */ : 0 /* NonWord */);\n if (!i || type == 1 /* Upper */ && hasLower || prevType == 0 /* NonWord */ && type != 0 /* NonWord */) {\n if (chars[byWordTo] == next || (folded[byWordTo] == next && (byWordFolded = true)))\n byWord[byWordTo++] = i;\n else if (byWord.length)\n wordAdjacent = false;\n }\n prevType = type;\n i += state.codePointSize(next);\n }\n if (byWordTo == len && byWord[0] == 0 && wordAdjacent)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0), byWord, word);\n if (adjacentTo == len && adjacentStart == 0)\n return this.ret(-200 /* CaseFold */ - word.length + (adjacentEnd == word.length ? 0 : -100 /* NotFull */), [0, adjacentEnd]);\n if (direct > -1)\n return this.ret(-700 /* NotStart */ - word.length, [direct, direct + this.pattern.length]);\n if (adjacentTo == len)\n return this.ret(-200 /* CaseFold */ + -700 /* NotStart */ - word.length, [adjacentStart, adjacentEnd]);\n if (byWordTo == len)\n return this.result(-100 /* ByWord */ + (byWordFolded ? -200 /* CaseFold */ : 0) + -700 /* NotStart */ +\n (wordAdjacent ? 0 : -1100 /* Gap */), byWord, word);\n return chars.length == 2 ? false\n : this.result((any[0] ? -700 /* NotStart */ : 0) + -200 /* CaseFold */ + -1100 /* Gap */, any, word);\n }", "function main() {\n\tvar t = parseInt(readLine());\n\tfor(var a0 = 0; a0 < t; a0++){\n var R_temp = readLine().split(' ');\n var R = parseInt(R_temp[0]);\n var C = parseInt(R_temp[1]);\n var G = [];\n for(var G_i = 0; G_i < R; G_i++){\n G[G_i] = readLine();\n }\n var r_temp = readLine().split(' ');\n var r = parseInt(r_temp[0]);\n var c = parseInt(r_temp[1]);\n var P = [];\n for(var P_i = 0; P_i < r; P_i++){\n P[P_i] = readLine();\n }\n // console.log('G');\n // console.log(G);\n // console.log('P');\n // console.log(P);\n\n //////////////////////////////////\n // Begin Parsing and Check Code //\n\t // Find all matches to the given RegExp based on the first line of the given search parameter\n\t var query = new RegExp(P[0], 'g');\n\t\tvar result;\n\t\tvar total;\n\t\tvar finds = [];\n\t\tvar Answer = [];\n\t\tvar Binary = [];\n\t // var result = query.exec(G);\n\t\twhile ((result = query.exec(G)) !== null) {\n\t\t // var msg = 'Found ' + result[0] + '. ';\n\t\t // msg += 'Next match starts at ' + query.lastIndex;\n\t\t // console.log(msg);\n\t\t finds.push(result.index);\n\t\t}\n\n\t\t// Locate found matches\n\t var GLength = G[0].length + 1; // account for commas\n\t var ExtensionIndex = P[0].length;\n\t var ArrayIndex = [];\n\t var StringIndex = [];\n\n\t // For each match, confirm the match and convert into a 2D coordinate system\n\t\tfor (var ii = 0; ii < finds.length; ii++) {\n\t\t\tAnswer[ii] = [];\n\t\t ArrayIndex[ii] = Math.floor(finds[ii]/GLength);\n\n\t\t StringIndex[ii] = finds[ii] % GLength;\n\t\t // console.log('[ArrayIndex, StringIndex] = [' + ArrayIndex[ii] + ',' + StringIndex[ii] + ']');\n\n\t\t // Check that proper string was found\n\t\t var FoundString = G[ArrayIndex[ii]].substring(StringIndex[ii], StringIndex[ii]+ExtensionIndex);\n\t\t\t// console.log(' > FoundString = ' + FoundString);\n\n\t\t\t// Check each line of the search query\n\t\t\tfor (var jj = 1; jj < r; jj++) {\n\t\t\t\tif ( jj+ArrayIndex[ii] >= R ) {\n\t\t\t\t\tvar NextString = '';\n\t\t\t\t} else {\n\t\t\t \tvar NextString = G[ ArrayIndex[ii] + jj].substring(StringIndex[ii], StringIndex[ii]+ExtensionIndex);\n\t\t\t }\n\t\t\t var NextQuery = new RegExp(P[0 + jj]);\n\t\t\t // console.log(' > ' + NextString + ' vs ' + NextQuery);\n\t\t\t var check = NextQuery.test(NextString);\n\t\t\t Answer[ii].push( check );\n\t\t\t\t// Abort loop if false\n\t\t\t\tif (!check) {\n\t\t\t\t\tjj = r;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// console.log(' Answers = [' + Answer[ii] + ']');\n\n\t\t\t// Flatten answer array\n\t\t\tBinary[ii] = Answer[ii].indexOf(false);\n\t\t}\n\t\t// console.log( ' Binary Conversion -> ' + Binary );\n\n\t\t// console.log( Binary.indexOf(-1) > 0 );\n\t console.log( ( Binary.indexOf(-1) >= 0 ) ? 'YES' : 'NO');\n // End Parsing and Check Code //\n\t\t// console.log(' ');\n ////////////////////////////////\n\t}\n}", "function compute_lcd_of_matches(matches) {\n for (var i = 0; i < matches[0].length; i++) {\n for (var j = 1; j < matches.length; j++) {\n if (matches[j].charCodeAt(i) != matches[0].charCodeAt(i)) {\n return matches[0].substring(0, i);\n }\n }\n }\n return matches[0];\n}", "function grabscrab(str, arr) {\n let matches = [];\n\n for (let idx = 0; idx < arr.length; idx += 1) {\n if (str.split('').sort().join('') === arr[idx].split('').sort().join('')) {\n matches.push(arr[idx]);\n }\n }\n\n return matches;\n}", "function findLongestRepeatingSubSeq(str) {\n let n = str.length;\n\n let dp = new Array(n + 1);\n for (let i = 0; i <= n; i++) {\n dp[i] = new Array(n + 1);\n for (let j = 0; j <= n; j++) dp[i][j] = 0;\n }\n\n // now use LCS function\n for (let i = 1; i <= n; i++) {\n for (let j = 1; j <= n; j++) {\n if (str[i - 1] === str[j - 1] && i != j) dp[i][j] = 1 + dp[i - 1][j - 1];\n else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n return dp[n][n];\n}", "function search(w1, w2)\n{\n let l1 = w1.length;\n let l2 = w2.length;\n console.log(w1, w2);\n let ch,c,maxc=0;\n let i,j;\n\n for(i=0;i<l1;i++)\n {\n ch = w1.charAt(i);\n\n for(j=0;j<l2;j++)\n {\n if(ch === w2.charAt(j))\n {\n c=1;\n tempi = i;\n tempj = j;\n\n\n while (w1.charAt(++tempi) === w2.charAt(++tempj))\n {\n c++;\n if(tempi+1>l1 || tempj+1>l2)\n {\n c--;\n break;\n }\n\n }\n\n\n }\n\n\n if(c>maxc)\n {\n maxc = c;\n }\n\n }\n }\n let perc_match = maxc/l1*100;\n console.log(perc_match)\n return perc_match;\n}", "findNextMatch(string, startPosition, callback) {\n if (startPosition == null) {\n startPosition = 0;\n }\n if (typeof startPosition === 'function') {\n callback = startPosition;\n startPosition = 0;\n }\n try {\n const match = this.findNextMatchSync(string, startPosition);\n callback(null, match);\n }\n catch (error) {\n callback(error);\n }\n }", "findNextMatch(string, startPosition, callback) {\n if (startPosition == null) {\n startPosition = 0;\n }\n if (typeof startPosition === 'function') {\n callback = startPosition;\n startPosition = 0;\n }\n try {\n const match = this.findNextMatchSync(string, startPosition);\n callback(null, match);\n }\n catch (error) {\n callback(error);\n }\n }", "findNextMatch(string, startPosition, callback) {\n if (startPosition == null) {\n startPosition = 0;\n }\n if (typeof startPosition === 'function') {\n callback = startPosition;\n startPosition = 0;\n }\n try {\n const match = this.findNextMatchSync(string, startPosition);\n callback(null, match);\n }\n catch (error) {\n callback(error);\n }\n }", "search (string) {\n\t\tlet lines = this.output.split('\\n');\n\t\tlet rgx = new RegExp(string);\n\t\tlet matched = [];\n\t\t// can't use a simple Array.prototype.filter() here\n\t\t// because we need to add the line number\n\t\tfor (let i = 0; i < lines.length; i++) {\n\t\t\tlet addr = `[${i}] `;\n\t\t\tif (lines[i].match(rgx)) {\n\t\t\t\tmatched.push(addr + lines[i]);\n\t\t\t}\n\t\t}\n\t\tlet result = matched.join('\\n');\n\t\tif (result.length == 0) result = `Nothing found for \"${string}\".`;\n\t\treturn result\n\t}", "findNextMatch(string, startPosition, callback) {\r\n if (startPosition == null) {\r\n startPosition = 0;\r\n }\r\n if (typeof startPosition === 'function') {\r\n callback = startPosition;\r\n startPosition = 0;\r\n }\r\n try {\r\n const match = this.findNextMatchSync(string, startPosition);\r\n callback(null, match);\r\n }\r\n catch (error) {\r\n callback(error);\r\n }\r\n }", "function kmp(text,pattern) {\n\tvar tlen = text.length,\n\t\t\tplen = pattern.length,\n\t\t\tm = 0,//Beginning of current match\n\t\t\ti = 0; //Index of pattern\n\n\tvar partialMatchTable = (function() {\n\n\t\tvar table = new Array (plen),\n\t\t\tcnd = 0;\n\n\t\ttable[0] = -1;\n\t\ttable[1] = 0;\n\n\t\tvar pos = 2; //Start at pos 2 of table because pos 0,1 are equal to -1,0\n\n\t\twhile (pos < plen) {\n\t\t\tif (pattern[pos - 1] == pattern[cnd]) {\n\t\t\t\tcnd++;\n\t\t\t\ttable[pos] = cnd;\n\t\t\t\tpos++;\n\t\t\t}\n\t\t\telse if (cnd > 0) {\n\t\t\t\tcnd = table[cnd]; //XXX ????\n\t\t\t}\n\t\t\telse {\n\t\t\t\ttable[pos] = 0;\n\t\t\t\tpos++;\n\t\t\t}\n\t\t}\n\n\t\t\treturn table;\n\t})();\n\n\n\twhile (m+i < tlen) {\n\t\tif (text[m+i] === pattern[i]) { //pattern/text Character match\n\t\t\tif (i == plen - 1) { //End of pattern reached\n\t\t\t\treturn m;\n\t\t\t}\n\t\t\telse {\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\telse { //Char match fail\n\t\t\t//Where to start search from . m + index of chars matched - prefix offset \n\t\t\t//If i == 0, then pfxtbl[0] == -1, and m = m + 0 -(-1) == m + 1 -> next char\n\t\t\t//if i == 1, then pfxtbl[1] == 0, and m = m + 1 - 0 == m + 1 -> next char\n\t\t\t//if i > 1, then pfxtbl[i] is an offset. \n\t\t\tm = m + i - partialMatchTable[i]; \n\t\t\t\n\t\t\tif (partialMatchTable[i] > -1 ) { \n\t\t\t\t//Start from offset (m + i where i >= 0)\n\t\t\t\ti = partialMatchTable[i]; \n\t\t\t}\n\t\t\telse {//prfxTbl == -1 means failed on 1st char of pattern\n\t\t\t\ti = 0;\n\t\t\t}\n\t\t}\n\t} //End while\n\n}", "function populateAndFindLongestCommonSubstring(arr, s1, s2) {\n\tvar diagonal, newCommonLen, retStr;\n\tvar longestStrLen = -1,\n\t\tlongestStrLenRow = -1,\n\t\tlongestStrLenCol = -1,\n\t\trowLen = s1.length + 1,\n\t\tcolLen = s2.length + 1;\n\n\tfor(var i = 1; i < rowLen; i++) {\n\t\tfor(var j = 1; j < colLen; j++) {\n\t\t\t// If the letter of the column and the row are the same then\n\t\t\t// take 1 + the diagonal else just use zero\n\t\t\tif(s1[i - 1] === s2[j - 1]) {\n\t\t\t\tdiagonal = arr[i - 1][j - 1];\n\t\t\t\tnewCommonLen = 1 + diagonal;\n\n\t\t\t\t// Keeping track of the index and length of the longest common substring\n\t\t\t\tif(newCommonLen > longestStrLen) {\n\t\t\t\t\tlongestStrLen = newCommonLen;\n\t\t\t\t\t[longestStrLenRow, longestStrLenCol] = [i, j];\n\t\t\t\t}\n\n\t\t\t\tarr[i].push(newCommonLen);\n\t\t\t} else {\n\t\t\t\tarr[i].push(0);\n\t\t\t}\n\t\t}\n\t}\n\n\tretStr = traverseDiagonal(arr, s1, longestStrLenRow, longestStrLenCol);\n\treturn retStr;\n}", "function longestCommonSubstring(string1, string2) {\n\t// Convert strings to arrays to treat unicode symbols length correctly.\n\t// For example:\n\t// '𐌵'.length === 2\n\t// [...'𐌵'].length === 1\n\tconst s1 = [...string1];\n\tconst s2 = [...string2];\n\n\t// Init the matrix of all substring lengths to use Dynamic Programming approach.\n\tconst substringMatrix = Array(s2.length + 1)\n\t\t.fill(null)\n\t\t.map(() => {\n\t\t\treturn Array(s1.length + 1).fill(null);\n\t\t});\n\n\t// Fill the first row and first column with zeros to provide initial values.\n\tfor (let columnIndex = 0; columnIndex <= s1.length; columnIndex += 1) {\n\t\tsubstringMatrix[0][columnIndex] = 0;\n\t}\n\n\tfor (let rowIndex = 0; rowIndex <= s2.length; rowIndex += 1) {\n\t\tsubstringMatrix[rowIndex][0] = 0;\n\t}\n\n\t// Build the matrix of all substring lengths to use Dynamic Programming approach.\n\tlet longestSubstringLength = 0;\n\tlet longestSubstringColumn = 0;\n\tlet longestSubstringRow = 0;\n\n\t//creates a table comparing each character in the strings\n\tfor (let rowIndex = 1; rowIndex <= s2.length; rowIndex += 1) {\n\t\tfor (let columnIndex = 1; columnIndex <= s1.length; columnIndex += 1) {\n\t\t\t//if (s1[columnIndex - 1] === s2[rowIndex - 1]) {\n\t\t\t//hack to change rowIndex to <= 6 since that was the longest substring...so it stops looking after the 6th match\n\t\t\tif (s1[columnIndex - 1] === s2[rowIndex - 1] && rowIndex <= 6) {\n\t\t\t\tsubstringMatrix[rowIndex][columnIndex] =\n\t\t\t\t\tsubstringMatrix[rowIndex - 1][columnIndex - 1] + 1;\n\t\t\t} else {\n\t\t\t\tsubstringMatrix[rowIndex][columnIndex] = 0;\n\t\t\t}\n\n\t\t\t// Try to find the biggest length of all common substring lengths\n\t\t\t// and to memorize its last character position (indices)\n\t\t\t// if (substringMatrix[rowIndex][columnIndex] > longestSubstringLength) {\n\t\t\tif (substringMatrix[rowIndex][columnIndex] > longestSubstringLength) {\n\t\t\t\tlongestSubstringLength = substringMatrix[rowIndex][columnIndex];\n\t\t\t\tlongestSubstringColumn = columnIndex;\n\t\t\t\tlongestSubstringRow = rowIndex;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (longestSubstringLength === 0) {\n\t\t// Longest common substring has not been found.\n\t\treturn \"\";\n\t}\n\n\t// Detect the longest substring from the matrix.\n\tlet longestSubstring = \"\";\n\n\twhile (substringMatrix[longestSubstringRow][longestSubstringColumn] > 0) {\n\t\t//\twhile (substringMatrix[longestSubstringRow][longestSubstringColumn] > 0 &&\tlongestSubstringRow <= 2) {\n\t\tlongestSubstring = s1[longestSubstringColumn - 1] + longestSubstring;\n\t\tlongestSubstringRow -= 1;\n\t\tlongestSubstringColumn -= 1;\n\t}\n\n\treturn longestSubstring;\n}", "function analyze(str) {\n function createResultRecord() {\n resultsArr.push(`(${getToken(currentState)}, ${tokenString})`)\n }\n const initStrArr = str.trim().split(\"\")\n\n // Array contains previous states. Used to go back if sequence failed\n let statesBuffer = []\n let currentState = 0\n let tokenString = \"\"\n let resultsArr = [] // Results array in format [\"(number, 2)\", (id, asd), ...]\n \n for(let index = 0; index < initStrArr.length; index++) {\n function iterateBack() {\n let prevStep = 1\n let revercedBufferArr = statesBuffer.slice(1).reverse()\n\n // From the end of buffered states iterate and find first successful state\n while(!getToken(revercedBufferArr[prevStep]) &&\n prevStep <= revercedBufferArr.length) {\n prevStep += 1\n }\n // Set params to last known successfull state\n currentState = revercedBufferArr[prevStep]\n tokenString = tokenString.substr(0, tokenString.length - prevStep)\n createResultRecord()\n tokenString = \"\"\n currentState = 0\n index -= prevStep + 1\n }\n\n const char = initStrArr[index]\n const newState = getNewState(currentState, char)\n statesBuffer.push(currentState)\n\n if (char == \" \") { continue; }\n \n if (newState) {\n currentState = newState\n tokenString += char\n } else {\n if (!tokenTable[currentState]) {\n iterateBack(); continue;\n }\n createResultRecord()\n tokenString = char\n currentState = 0\n currentState = getNewState(currentState, char)\n }\n \n if(index === initStrArr.length - 1) {\n if(getToken(currentState)) {\n createResultRecord()\n } else {\n statesBuffer.push(currentState)\n index += 1\n iterateBack()\n }\n }\n }\n return resultsArr.join(\"; \") \n}", "_getNextLookup(sequence, start) {\n const result = {\n index: null,\n first: Infinity,\n last: -1\n };\n // Loop through each glyph and find the first valid lookup for it\n for (let i = 0; i < sequence.length; i++) {\n const lookups = this._glyphLookups[sequence[i]];\n if (!lookups) {\n continue;\n }\n for (let j = 0; j < lookups.length; j++) {\n const lookupIndex = lookups[j];\n if (lookupIndex >= start) {\n // Update the lookup information if it's the one we're\n // storing or earlier than it.\n if (result.index === null || lookupIndex <= result.index) {\n result.index = lookupIndex;\n if (result.first > i) {\n result.first = i;\n }\n result.last = i + 1;\n }\n break;\n }\n }\n }\n return result;\n }", "function SearchingChallenge2(strArr) {\n let pos = [];\n\n for (let i = 0; i < strArr.length; i++) {\n for (let j = 0; j < strArr[i].length; j++) {\n if ([...strArr[i]][j] === \"0\") pos.push([j, i]);\n }\n }\n\n let count = 0;\n const x = 0;\n const y = 1;\n\n for (let i = 0; i < pos.length; i++) {\n for (let j = 0; j < pos.length; j++) {\n if (\n (pos[i][y] === pos[j][y] && pos[i][x] === pos[j][x] + 1) ||\n (pos[i][x] === pos[j][x] && pos[i][y] === pos[j][y] + 1)\n ) {\n count++;\n }\n }\n }\n\n return count;\n}", "function findMatch(slicedDNA, lookup) {\n for (let i=0; i<slicedDNA.length;i++) {\n for (let j=0;j<lookup.length;j++) {\n if (slicedDNA[i]==lookup[j].codons) {\n //console.log(lookup[j].abbr, lookup[j].codons);\n matched.push(lookup[j].abbr);\n }\n }\n }\n //console.log(matched);\n return matched;\n}", "function exmaple3 (str = 'I am abcabx') {\n function match(string) {\n let state = start;\n \n for(let c of string) {\n // Iteratelly change value of state\n // If variable is 'a', then state will be record that A is found, and start found B.\n state = state(c);\n }\n \n return state === end;\n }\n \n function start(c) {\n if (c === 'a')\n return foundA;\n else\n return start;\n }\n \n function end(c) {\n return end;\n }\n \n function foundA(c) {\n if (c === 'b') \n return foundB;\n else\n return start;\n }\n \n function foundB(c) {\n if (c === 'c')\n return foundC;\n else\n return start(c);\n }\n \n function foundC(c) {\n if (c === 'a') \n return foundA2;\n else\n return start;\n }\n \n function foundA2(c) {\n if (c === 'b') \n return foundB2;\n else\n return start(c);\n }\n\n function foundB2(c) {\n if (c === 'x')\n return end;\n else\n return start(c);\n }\n \n console.log(match(str));\n}", "function matchingStrings(strings, queries) {\n var sindex;\n var qindex;\n var count;\n var slen = strings.length;\n var qlen = queries.length;\n var a = [];\n var i = 0;\n\n for (qindex = 0; qindex < qlen; qindex++) {\n count = 0;\n for (sindex = 0; sindex < slen; sindex++) {\n if (queries[qindex].localeCompare(strings[sindex]) == 0) {\n\n count++;\n }\n }\n a[i] = count;\n i++;\n }\n return a;\n}", "function commonChild(a, b) {\r\n \r\n \r\n var len = a.length;\r\n \r\n var pre = [];\r\n var now = [];\r\n \r\n \r\n \r\n for(var i=0;i<len;i++) pre[i] = 0;\r\n \r\n \r\n for(var i=0;i<len;i++){\r\n for(var j=0;j<len;j++){\r\n if(a[i].charAt(0) == b[j].charAt(0)){\r\n if(i==0) now[j] = 1;\r\n else if(j==0) now[j] = 1;\r\n else now[j] = pre[j-1] + 1;\r\n }\r\n else{\r\n var max = 0;\r\n if(i>0 && max < pre[j]) max = pre[j];\r\n if(j>0 && max < now[j-1]) max = now[j-1];\r\n if(i>0 && j>0 && max < pre[j-1]) max = pre[j-1];\r\n now[j] = max;\r\n }\r\n }\r\n for(j=0;j<len;j++)\r\n pre[j] = now[j];\r\n }\r\n\r\n \r\n \r\n \r\n return now[len-1];\r\n\r\n\r\n}", "function LongestCommonSub_Iterative(str1, str2, m, n) {\n\n var tabulation = [];\n\n for (var i = 0; i <= m; i++) {\n for (var j = 0; j <= n; j++) {\n // initialize i=0 and j=0 rows and cols with 0, as we need these as initial state \n if (i === 0 || j === 0) {\n if (tabulation[i] === undefined) {\n tabulation[i] = [];\n }\n //takes care of populating a row with all Zero\n //Happens only for first row and first column i.e., i=0 || j=0\n tabulation[i][j] = 0;\n } else {\n if (str1.charAt(i - 1) === str2.charAt(j - 1)) {\n //If they match then its reduced to 1 + LCS( str1 - 1char, str2 - 1char)\n tabulation[i][j] = 1 + tabulation[i - 1][j - 1]\n } else {\n //If they don't match then its reduced to Max of [ LCS( str1 - 1char, str2) , LCS( str1, str2 - 1char) ] \n tabulation[i][j] = Math.max(tabulation[i - 1][j], tabulation[i][j - 1]);\n }\n }\n }\n }\n\n printLCS(str1, str2, m, n, tabulation);\n return tabulation;\n\n}", "function exmaple4 (str = 'I am abababx') {\n function match(string) {\n let state = start;\n \n for(let c of string) {\n // Iteratelly change value of state\n // If variable is 'a', then state will be record that A is found, and start found B.\n state = state(c);\n }\n \n return state === end;\n }\n \n function start(c) {\n if (c === 'a')\n return foundA;\n else\n return start;\n }\n \n function end(c) {\n return end;\n }\n \n function foundA(c) {\n if (c === 'b') \n return foundB;\n else\n return start;\n }\n \n function foundB(c) {\n if (c === 'a')\n return foundA2;\n else\n return start(c);\n }\n \n function foundA2(c) {\n if (c === 'b') \n return foundB2;\n else\n return start;\n }\n \n function foundB2(c) {\n if (c === 'a') \n return foundA3;\n else\n return start(c);\n }\n\n function foundA3(c) {\n if (c === 'b') \n return foundB3;\n else\n return start(c);\n }\n \n function foundB3(c) {\n if (c === 'x') \n return end;\n else\n return start(c);\n }\n \n console.log(match(str));\n}", "function findMatchStarts(text, pattern, matches) {\n var patRev = reverse(pattern);\n return matches.map(function (m) {\n // Find start of each match by reversing the pattern and matching segment\n // of text and searching for an approx match with the same number of\n // errors.\n var minStart = Math.max(0, m.end - pattern.length - m.errors);\n var textRev = reverse(text.slice(minStart, m.end));\n // If there are multiple possible start points, choose the one that\n // maximizes the length of the match.\n var start = findMatchEnds(textRev, patRev, m.errors).reduce(function (min, rm) {\n if (m.end - rm.end < min) {\n return m.end - rm.end;\n }\n return min;\n }, m.end);\n return {\n start: start,\n end: m.end,\n errors: m.errors\n };\n });\n}", "function getMatchIndices(text, match) {\n\t\tt = text.replace(/<DELETED>/g, \" \");\n\t\tt = t.replace(/<\\/DELETED>/g, \" \");\n\t\tt = t.replace(/<plus-minus>/g, \" \");\n\t\tt = t.replace(/[\\W|_]/g,\" \");\n\t\tt = t.toLowerCase();\n\t\t\n\t\tvar m = match.replace(/[\\s-]/g,\"\");\n\t\tm = m.replace(/\\\\/g,\"\");\n\t\t\n\t\tif (m.length > 600) {\n\t\t\tvar mStart = m.substr(0,500);\n\t\t\tvar mEnd = m.substr(m.length - 500,m.length);\n\t\t\tmStart = mStart.split(\"\").join(\"\\\\s*\");\n\t\t\tmStart = afterDotOptional(mStart);\n\t\t\tmEnd = mEnd.split(\"\").join(\"\\\\s*\");\n\t\t\tmEnd = afterDotOptional(mEnd);\n\t\t\tvar matchExpStart = new RegExp(mStart, \"g\");\n\t\t\tvar matchExpEnd = new RegExp(mEnd, \"g\");\n\t\t\n\t\t\tvar start = t.search(matchExpStart);\n\t\t\tvar end = t.search(matchExpEnd) + t.match(matchExpEnd)[0].length;\n\t\t\treturn [start, end];\n\t\t} else {\n\t\t\tm = m.split(\"\").join(\"\\\\s*\");\n\t\t\tm = afterDotOptional(m);\n\t\t\tvar matchExp = new RegExp(m, \"g\");\n\t\t\n\t\t\t//console.log(matchExp);\n\t\t\n\t\t\tvar start = t.search(matchExp);\n\t\t\tvar end = start + t.match(matchExp)[0].length;\n\t\t\treturn [start, end];\n\t\t}\n\t}", "function compoundMatch(words, target) {\n for (let i = 0; i < target.length; i++) {\n if (words.includes(target.slice(0, i)) && words.includes(target.slice(i))) {\n let res = [target.slice(0, i), target.slice(i)];\n let pair = words.filter(a => res.includes(a));\n let ids = [words.indexOf(target.slice(0, i)), words.indexOf(target.slice(i))];\n pair.push(ids);\n return pair;\n }\n }\n return null;\n}", "function seqSearchM(arr,data){\n var max =0;\n for (var i=0;i<arr.length;i++){\n\n if (arr[i]==data&&i>(arr.length*0.2)){\n return i;\n }\n }\n return -1;\n}", "match(input, start, end){\n start = start || 0\n end = end || input.length\n if(typeof input === 'string') input = new Source(input)\n if(!this.startsWith(input.get(start)))\n return this.error(input,start,start+1)\n var n=end\n end=start+1\n while(end<n && this.valid(input.get(end))) end++\n var s = (this.useStarter)?start+1:start\n var m = (end-s)%4\n if(s==end || m==1) return this.error(input,start,end)\n if(m>0) {\n while(end<n && m<4 && input.get(end)=='=') {\n end++\n m++\n }\n if(m<4) return this.error(input,start,end)\n }\n return this.token(input,start,end,Base64.decode(input.substring(s,end)))\n }", "function longest_match(s,cur_match){var chain_length=s.max_chain_length;/* max hash chain length */var scan=s.strstart;/* current string */var match;/* matched string */var len;/* length of current match */var best_len=s.prev_length;/* best match length so far */var nice_match=s.nice_match;/* stop if match long enough */var limit=s.strstart>s.w_size-MIN_LOOKAHEAD?s.strstart-(s.w_size-MIN_LOOKAHEAD):0/*NIL*/;var _win=s.window;// shortcut\n var wmask=s.w_mask;var prev=s.prev;/* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */var strend=s.strstart+MAX_MATCH;var scan_end1=_win[scan+best_len-1];var scan_end=_win[scan+best_len];/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n /* Do not waste too much time if we already have a good match: */if(s.prev_length>=s.good_match){chain_length>>=2;}/* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */if(nice_match>s.lookahead){nice_match=s.lookahead;}// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n do{// Assert(cur_match < s->strstart, \"no future\");\n match=cur_match;/* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */if(_win[match+best_len]!==scan_end||_win[match+best_len-1]!==scan_end1||_win[match]!==_win[scan]||_win[++match]!==_win[scan+1]){continue;}/* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */scan+=2;match++;// Assert(*scan == *match, \"match[2]?\");\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */do{/*jshint noempty:false*/}while(_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&_win[++scan]===_win[++match]&&scan<strend);// Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n len=MAX_MATCH-(strend-scan);scan=strend-MAX_MATCH;if(len>best_len){s.match_start=cur_match;best_len=len;if(len>=nice_match){break;}scan_end1=_win[scan+best_len-1];scan_end=_win[scan+best_len];}}while((cur_match=prev[cur_match&wmask])>limit&&--chain_length!==0);if(best_len<=s.lookahead){return best_len;}return s.lookahead;}", "function diff(stringX, stringY, user) {\n var x = stringX.split('');\n var y = stringY.split('');\n\n // m is row dimension, n is column dimension \n var m = x.length;\n var n = y.length;\n var lcs = '';\n // Create an LCS table where x-axis is string 1 and y-axis is string 2 to hold \n var c = [];\n\n\n // calculate LCS table via dynamic programming\n for (var i = 0; i <= m; i++) {\n c[i] = [];\n for (var j = 0; j <= n; j++) {\n if (i === 0 || j === 0) {\n c[i][j] = 0;\n }\n else if (x[i-1] === y[j-1]) {\n c[i][j] = c[i - 1][j - 1] + 1;\n }\n else {\n c[i][j] = Math.max(c[i-1][j], c[i][j-1]);\n }\n\n }\n\n }\n\n lcs = backtrace(c, x, y, m, n);\n\n var results = [];\n var diff_results = findDiff(c, x, y, m, n, results, user);\n\n // for (var i = 0; i < diff_result.length; i++) {\n // if (diff_result[i][])\n // }\n // console.log(diff_results);\n return diff_results;\n}", "function longest_match(cur_match) {\n\t\tvar chain_length = max_chain_length; // max hash chain length\n\t\tvar scanp = strstart; // current string\n\t\tvar matchp; // matched string\n\t\tvar len; // length of current match\n\t\tvar best_len = prev_length; // best match length so far\n\n\t\t// Stop when cur_match becomes <= limit. To simplify the code,\n\t\t// we prevent matches with the string of window index 0.\n\t\tvar limit = (strstart > MAX_DIST ? strstart - MAX_DIST : NIL);\n\n\t\tvar strendp = strstart + MAX_MATCH;\n\t\tvar scan_end1 = window[scanp + best_len - 1];\n\t\tvar scan_end = window[scanp + best_len];\n\n\t\tvar i, broke;\n\n\t\t// Do not waste too much time if we already have a good match: */\n\t\tif (prev_length >= good_match) {\n\t\t\tchain_length >>= 2;\n\t\t}\n\n\t\t// Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, \"insufficient lookahead\");\n\n\t\tdo {\n\t\t\t// Assert(cur_match < encoder->strstart, \"no future\");\n\t\t\tmatchp = cur_match;\n\n\t\t\t// Skip to next match if the match length cannot increase\n\t\t\t// or if the match length is less than 2:\n\t\t\tif (window[matchp + best_len] !== scan_end ||\n\t\t\t\t\twindow[matchp + best_len - 1] !== scan_end1 ||\n\t\t\t\t\twindow[matchp] !== window[scanp] ||\n\t\t\t\t\twindow[++matchp] !== window[scanp + 1]) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// The check at best_len-1 can be removed because it will be made\n\t\t\t// again later. (This heuristic is not always a win.)\n\t\t\t// It is not necessary to compare scan[2] and match[2] since they\n\t\t\t// are always equal when the other bytes match, given that\n\t\t\t// the hash keys are equal and that HASH_BITS >= 8.\n\t\t\tscanp += 2;\n\t\t\tmatchp++;\n\n\t\t\t// We check for insufficient lookahead only every 8th comparison;\n\t\t\t// the 256th check will be made at strstart+258.\n\t\t\twhile (scanp < strendp) {\n\t\t\t\tbroke = false;\n\t\t\t\tfor (i = 0; i < 8; i += 1) {\n\t\t\t\t\tscanp += 1;\n\t\t\t\t\tmatchp += 1;\n\t\t\t\t\tif (window[scanp] !== window[matchp]) {\n\t\t\t\t\t\tbroke = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (broke) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlen = MAX_MATCH - (strendp - scanp);\n\t\t\tscanp = strendp - MAX_MATCH;\n\n\t\t\tif (len > best_len) {\n\t\t\t\tmatch_start = cur_match;\n\t\t\t\tbest_len = len;\n\t\t\t\tif (FULL_SEARCH) {\n\t\t\t\t\tif (len >= MAX_MATCH) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tif (len >= nice_match) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tscan_end1 = window[scanp + best_len - 1];\n\t\t\t\tscan_end = window[scanp + best_len];\n\t\t\t}\n\t\t} while ((cur_match = prev[cur_match & WMASK]) > limit && --chain_length !== 0);\n\n\t\treturn best_len;\n\t}", "function vis_shift_and(p, text) {\n $(\"#the-haystack\").html(\"\");\n $(\"#the-needle\").html(\"\").css('left', 'inherit');\n $(\"#bitmask-table\").html(\"\");\n $(\"#match-run pre\").html(\"\");\n\n var b = {};\n var l = p.length;\n var tl = text.length;\n var alphabet = [];\n\n // initialize bitmask table\n // build alphabet array\n for (var i = 0; i < l; i++) {\n var ch = p.charAt(i);\n add_to_alphabet(alphabet, ch);\n b[ch] = 0;\n }\n\n //build bitmask table;\n for (var i = 0; i < l; i++) {\n b[p.charAt(i)] = b[p.charAt(i)] | (1 << i);\n }\n\n for (var i = 0; i < alphabet.length; i++) {\n var padded = pad_num(l, b[alphabet[i]].toString(2));\n display_mask(alphabet[i], padded);\n }\n \n display_mask('*', pad_num(l, (0).toString(2)));\n\n display_text(text);\n display_pattern(p);\n \n tx_as_array = text.split(\"\");\n\n var haystack_pos = $(\"#the-haystack\").position();\n var d = 0;\n var matchMask = 1 << l-1;\n var text_index = 0;\n var pat_letter_index = -1;\n\n function read_next_char(d, matchMask, text_index) {\n var ch = tx_as_array.shift();\n\n $.when(do_shift(d), get_from_table(b, ch)).done(function(shifted, from_table) {\n var d2 = shifted & from_table;\n\n function display_shift_table() {\n var deferred = $.Deferred();\n var d2_padded = pad_num(l, d2.toString(2));\n var pattern_pos = d2_padded.indexOf(\"1\");\n \n if (pattern_pos > -1) {\n pat_letter_index = pat_letter_index + 1;\n }\n\n $(\"div#match-run pre\").html(\"\");\n $(\"div#match-run pre\").append('D: <span id=\"d_val\">' + pad_num(l, d.toString(2)) + '</span> <span id=\"shift_op\"><< 1 | 1</span>\\n');\n\n // first_step: << 1 | 1 animation\n $.when(first_step(l, shifted)).done(function () {\n $(\"div#match-run pre\").append('Reading: ');\n\n $.when(highlight_read_letter(text_index)).done(function (){\n $(\"div#match-run pre\").append('\"' + ch + '\"');\n\n $.when(highlight_bitmask_row(b, ch)).done(function () {\n $(\"div#match-run pre\").append(' <span id=\"pad_from_table\">' + pad_num(l, from_table.toString(2)) + \"</span>\\n\");\n $.when(highlight_pad_from_table()).done(function() {\n $(\"div#match-run pre\").append('D & \"' + ch + '\" mask <span id=\"match_result\">' + d2_padded + \"</span>\\n\");\n $.when(highlight_match_result(pattern_pos)).done(function () {\n var pattern_anim = $.Deferred();\n if (pattern_pos > -1) {\n // change pattern color to green when prefixes are matched\n highlight_pattern_letter(pattern_anim, pat_letter_index, 'green');\n } else {\n // restore all the letters;\n $.when(flash_colors(\"#pattern-letter-\" + (pat_letter_index + 1), 'red', '#ffffff', 500)).done(function () {\n pat_letter_index = -1;\n restore_pattern_letters(l, pattern_pos);\n move_pattern_letters(pattern_anim, tl, text_index);\n });\n }\n\n $.when(pattern_anim).done(function () {\n setTimeout(function(){\n deferred.resolve();\n }, 300);\n });\n });\n });\n });\n });\n });\n\n return deferred.promise();\n }\n\n $.when(display_shift_table()).done(function () {\n var matched = do_and(d2, matchMask);\n\n if (matched != 0) {\n $(\"div#match-run pre\").append(\"Match at: \" + (text_index - l + 1));\n } else if (eol(tl, text_index)) {\n $(\"div#match-run pre\").append(\"No Match\");\n } else {\n read_next_char(d2, matchMask, text_index+1);\n }\n \n enable_form();\n })\n });\n }\n\n read_next_char(d, matchMask, text_index);\n}", "function lcs(word1, word2) {\r\n\tvar max = 0;\r\n\tvar index = 0;\r\n\tvar lcsarr = new Array(word1.length+1);\r\n\tfor (var i = 0; i <= word1.length+1; ++i) {\r\n\t\tlcsarr[i] = new Array(word2.length+1);\r\n\t\tfor (var j = 0; j <= word2.length+1; ++j) {\r\n\t\tlcsarr[i][j] = 0;\r\n\t\t}\r\n\t}\r\n\tfor (var i = 0; i <= word1.length; ++i) {\r\n\t\tfor (var j = 0; j <= word2.length; ++j) {\r\n\t\t\tif (i == 0 || j == 0) {\r\n\t\t\t\tlcsarr[i][j] = 0;\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tif (word1[i-1] == word2[j-1]) {\r\n\t\t\t\t\tlcsarr[i][j] = lcsarr[i-1][j-1] + 1;\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tlcsarr[i][j] = 0;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (max < lcsarr[i][j]) {\r\n\t\t\t\tmax = lcsarr[i][j];\r\n\t\t\t\tindex = i;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tvar str = \"\";\r\n\tif (max == 0) {\r\n\t\treturn \"\";\r\n\t}\r\n\telse {\r\n\t\tfor (var i = index-max; i <= max; ++i) {\r\n\t\t\tstr += word2[i];\r\n\t}\r\n\treturn str;\r\n\t}\r\n}", "function jwdistance(s1, s2) {\n if (typeof(s1) != \"string\" || typeof(s2) != \"string\") return 0;\n if (s1.length == 0 || s2.length == 0) return 0;\n s1 = s1.toLowerCase(), s2 = s2.toLowerCase();\n var matchWindow = (Math.floor(Math.max(s1.length, s2.length) / 2.0)) - 1;\n var matches1 = new Array(s1.length);\n var matches2 = new Array(s2.length);\n var m = 0; // number of matches\n var t = 0; // number of transpositions\n //debug helpers\n //console.log(\"s1: \" + s1 + \"; s2: \" + s2);\n //console.log(\" - matchWindow: \" + matchWindow);\n // find matches\n for (var i = 0; i < s1.length; i++) {\n var matched = false;\n // check for an exact match\n if (s1[i] == s2[i]) {\n matches1[i] = matches2[i] = matched = true;\n m++\n }\n // check the \"match window\"\n else {\n // this for loop is a little brutal\n for (k = (i <= matchWindow) ? 0 : i - matchWindow;\n (k <= i + matchWindow) && k < s2.length && !matched;\n k++) {\n if (s1[i] == s2[k]) {\n if (!matches1[i] && !matches2[k]) {\n m++;\n }\n matches1[i] = matches2[k] = matched = true;\n }\n }\n }\n }\n if (m == 0) return 0.0;\n // count transpositions\n var k = 0;\n for (var i = 0; i < s1.length; i++) {\n if (matches1[k]) {\n while (!matches2[k] && k < matches2.length)\n k++;\n if (s1[i] != s2[k] && k < matches2.length) {\n t++;\n }\n k++;\n }\n }\n //debug helpers:\n //console.log(\" - matches: \" + m);\n //console.log(\" - transpositions: \" + t);\n t = t / 2.0;\n return (m / s1.length + m / s2.length + (m - t) / m) / 3;\n}", "function reduceGenCodeRNA(sequence, start, end){\n return geneticCode.reduce(function (codon, geneticCode){ return (codon.RNA === sequence.substring(start, end)) ? codon : geneticCode;},{});\n}", "prevMatchInRange(state, from, to) {\n for (let pos = to;;) {\n let start = Math.max(from, pos - 10000 /* ChunkSize */ - this.spec.unquoted.length);\n let cursor = stringCursor(this.spec, state, start, pos), range = null;\n while (!cursor.nextOverlapping().done)\n range = cursor.value;\n if (range)\n return range;\n if (start == from)\n return null;\n pos -= 10000 /* ChunkSize */;\n }\n }", "function solve(line) {\n var fragments = line.split(\";\");\n var matches = findMatches(fragments);\n\n while (matches.length > 0) {\n\n // sort to use longest first\n matches.sort(function (a, b) { return b.len - a.len });\n\n if (matches[0].len == 0)\n {\n fragments.sort(function (a, b) { return b.length - a.length });\n return fragments[0];\n }\n\n // join best\n joinFragments(fragments, matches[0].index, matches[0].targetIndex, matches[0].len);\n\n var index = matches[0].index;\n\n // remove used index and targer\n matches = matches.filter(function (item) {\n return item.index != matches[0].index &&\n item.index != matches[0].targetIndex &&\n item.targetIndex != matches[0].index &&\n item.targetIndex != matches[0].targetIndex\n });\n\n // look for more matches for index\n for (var i = 0; i < fragments.length; i++) {\n if (i != index) {\n if (fragments[i] != \"\") {\n var overlap = findLongestOverlap(fragments[index], fragments[i]);\n if (overlap > 0) {\n matches.push({ len: overlap, targetIndex: i, index: index });\n }\n }\n }\n }\n }\n\n fragments.sort(function (a, b) { return b.length - a.length });\n return fragments[0];\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length;\n /* max hash chain length */\n\n var scan = s.strstart;\n /* current string */\n\n var match;\n /* matched string */\n\n var len;\n /* length of current match */\n\n var best_len = s.prev_length;\n /* best match length so far */\n\n var nice_match = s.nice_match;\n /* stop if match long enough */\n\n var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0\n /*NIL*/\n ;\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n\n\n if (nice_match > s.lookahead) {\n nice_match = s.lookahead;\n } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {\n continue;\n }\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n\n\n scan += 2;\n match++; // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n\n if (len >= nice_match) {\n break;\n }\n\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n\n return s.lookahead;\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length;\n /* max hash chain length */\n\n var scan = s.strstart;\n /* current string */\n\n var match;\n /* matched string */\n\n var len;\n /* length of current match */\n\n var best_len = s.prev_length;\n /* best match length so far */\n\n var nice_match = s.nice_match;\n /* stop if match long enough */\n\n var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0\n /*NIL*/\n ;\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n\n\n if (nice_match > s.lookahead) {\n nice_match = s.lookahead;\n } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {\n continue;\n }\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n\n\n scan += 2;\n match++; // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n\n if (len >= nice_match) {\n break;\n }\n\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n\n return s.lookahead;\n }", "function matchingStrings(strings, queries) {\n \n var n = strings.length;\n var q= queries.length;\n \n var s = \"\";\n for(var i=0;i<n;i++){\n s+=strings[i];\n }\n \n var temp = [];\n \n for(let i=0;i<q;i++){\n if(s.search(q[i]!=-1)){\n var count=0;\n for(let j=0;j<n;j++){\n if(strings[j]==queries[i]){\n count++;\n }\n temp[i]=count;\n } \n }\n \n }\n \n return temp;\n\n}", "function name_match(knownNames, name) {\n let incomingNameParts = name.split(' ');\n //Reduce the matches to a true or false\n return R.reduce((match, value) => {\n return value === true ? true : match;\n }, false,\n //Map over known names and run comparisons return match status back into a new arr\n R.map((knownName, index) => {\n //console.log(\"KNOWN\", knownName, \"INCOMING\", name);\n //Exact match\n if (knownName === name) return true;\n //Split strings into word parts\n let knownNameParts = knownName.split(' ');\n //Find common words\n let intersection = R.intersection(incomingNameParts, knownNameParts);\n //If we have a common length between the intersection and the incoming words\n if (knownNameParts.length === intersection.length\n || incomingNameParts.length === intersection.length) return true;\n //If we know we have three parts and the intersection is missing one part\n if (knownNameParts.length == 3 && incomingNameParts.length === 3 && intersection.length === 2) {\n //Compare the first letter of the middle part\n if (R.head(knownNameParts[1]) === R.head(incomingNameParts[1])) return true;\n }\n //Find the difference between the two word arrays so we can look in more detail at why we aren't finding a middle name match\n let difference = R.difference(incomingNameParts, knownNameParts);\n //We know two words match but we have a difference\n if (intersection.length == 2 && difference.length > 0) {\n let matcher = false;\n //For all the known name parts\n knownNameParts.forEach((value) => {\n //Check to see if another part of the name matches the first char of the difference.\n if (R.head(value) === R.head(difference[0])) matcher = true;\n });\n //Return if the matcher is true, other wise we need to consider this Not a match.\n if (matcher) return true;\n else return false;\n }\n\n if (incomingNameParts.length === knownNameParts.length) {\n let distanceArr = incomingNameParts.map((word, index) => {\n let {steps} = LD(word, knownNameParts[index]);\n return steps;\n });\n let distanceTotal = R.reduce(R.add, 0, distanceArr);\n if (distanceTotal <= incomingNameParts.length &&\n distanceArr.indexOf(2) === -1) return true;\n }\n\n if (intersection.length < 2) return false;\n }, knownNames)\n );\n // console.log(matcheResults);\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length;\n /* max hash chain length */\n\n var scan = s.strstart;\n /* current string */\n\n var match;\n /* matched string */\n\n var len;\n /* length of current match */\n\n var best_len = s.prev_length;\n /* best match length so far */\n\n var nice_match = s.nice_match;\n /* stop if match long enough */\n\n var limit = s.strstart > s.w_size - MIN_LOOKAHEAD ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0\n /*NIL*/\n ;\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n\n\n if (nice_match > s.lookahead) {\n nice_match = s.lookahead;\n } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) {\n continue;\n }\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n\n\n scan += 2;\n match++; // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n\n if (len >= nice_match) {\n break;\n }\n\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n\n return s.lookahead;\n }", "function findMarker(buffer, position) {\n var index;\n for (index = position; index < buffer.length; index++) {\n if ((buffer[index] == marker1) && (buffer[index + 1] == marker2))\n return index;\n }\n return -1;\n}", "function lcsDynamicProg(str1,str2,m,n){\n var lengthMatrix = [];\n\n for(var i=0;i<m+1;i++){\n\t lengthMatrix[i] = [];\n }\n for(var i=0;i<m+1;i++){\n for(var j=0;j<n+1;j++){\n lengthMatrix[i][j] = 0;\n }\n }\n \n for(var i=0;i<m;i++){\n for(var j=0;j<n;j++){\n if(i==0 || j==0){\n lengthMatrix[i][j] = 0;\n }\n else if(str1[i-1] == str2[j-1]){\n lengthMatrix[i][j] = 1+lengthMatrix[i-1][j-1];\n }\n else{\n lengthMatrix[i][j] = Math.max(lengthMatrix[i-1][j], lengthMatrix[i][j-1])\n }\n }\n }\n return lengthMatrix[m][n];\n}", "nextOverlapping() {\n for (;;) {\n let next = this.peek();\n if (next < 0) {\n this.done = true;\n return this;\n }\n let str = state.fromCodePoint(next), start = this.bufferStart + this.bufferPos;\n this.bufferPos += state.codePointSize(next);\n let norm = this.normalize(str);\n for (let i = 0, pos = start;; i++) {\n let code = norm.charCodeAt(i);\n let match = this.match(code, pos);\n if (match) {\n this.value = match;\n return this;\n }\n if (i == norm.length - 1)\n break;\n if (pos == start && i < str.length && str.charCodeAt(i) == code)\n pos++;\n }\n }\n }", "function distance(s1, s2) {\r\n if (typeof(s1) != \"string\" || typeof(s2) != \"string\") return 0;\r\n if (s1.length == 0 || s2.length == 0) \r\n return 0;\r\n s1 = s1.toLowerCase(), s2 = s2.toLowerCase();\r\n var matchWindow = (Math.floor(Math.max(s1.length, s2.length) / 2.0)) - 1;\r\n var matches1 = new Array(s1.length);\r\n var matches2 = new Array(s2.length);\r\n var m = 0; // number of matches\r\n var t = 0; // number of transpositions\r\n\r\n //debug helpers\r\n //console.log(\"s1: \" + s1 + \"; s2: \" + s2);\r\n //console.log(\" - matchWindow: \" + matchWindow);\r\n\r\n // find matches\r\n for (var i = 0; i < s1.length; i++) {\r\n\tvar matched = false;\r\n\r\n\t// check for an exact match\r\n\tif (s1[i] == s2[i]) {\r\n\t\tmatches1[i] = matches2[i] = matched = true;\r\n\t\tm++\r\n\t}\r\n\r\n\t// check the \"match window\"\r\n\telse {\r\n \t// this for loop is a little brutal\r\n \tfor (k = (i <= matchWindow) ? 0 : i - matchWindow;\r\n \t\t(k <= i + matchWindow) && k < s2.length && !matched;\r\n\t\t\tk++) {\r\n \t\tif (s1[i] == s2[k]) {\r\n \t\tif(!matches1[i] && !matches2[k]) {\r\n \t \t\tm++;\r\n \t\t}\r\n\r\n \t matches1[i] = matches2[k] = matched = true;\r\n \t }\r\n \t}\r\n\t}\r\n }\r\n\r\n if(m == 0)\r\n return 0.0;\r\n\r\n // count transpositions\r\n var k = 0;\r\n\r\n for(var i = 0; i < s1.length; i++) {\r\n \tif(matches1[k]) {\r\n \t while(!matches2[k] && k < matches2.length)\r\n k++;\r\n\t if(s1[i] != s2[k] && k < matches2.length) {\r\n t++;\r\n }\r\n\r\n \t k++;\r\n \t}\r\n }\r\n \r\n //debug helpers:\r\n //console.log(\" - matches: \" + m);\r\n //console.log(\" - transpositions: \" + t);\r\n t = t / 2.0;\r\n return (m / s1.length + m / s2.length + (m - t) / m) / 3;\r\n}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/ ;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH$1;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) {\n\t nice_match = s.lookahead;\n\t }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH$1 - (strend - scan);\n\t scan = strend - MAX_MATCH$1;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function autoCorrelate( buf, sampleRate ) {\n\tvar SIZE = buf.length;\n\tvar MAX_SAMPLES = Math.floor(SIZE/2);\n\tvar best_offset = -1;\n\tvar best_correlation = 0;\n\tvar rms = 0;\n\tvar foundGoodCorrelation = false;\n\tvar correlations = new Array(MAX_SAMPLES);\n\n\tfor (var i=0;i<SIZE;i++) {\n\t\tvar val = buf[i];\n\t\trms += val*val;\n\t}\n\trms = Math.sqrt(rms/SIZE);\n\tif (rms<0.01) // not enough signal\n\t\treturn -1;\n\n\tvar lastCorrelation=1;\n\tfor (var offset = MIN_SAMPLES; offset < MAX_SAMPLES; offset++) {\n\t\tvar correlation = 0;\n\n\t\tfor (var i=0; i<MAX_SAMPLES; i++) {\n\t\t\tcorrelation += Math.abs((buf[i])-(buf[i+offset]));\n\t\t}\n\t\tcorrelation = 1 - (correlation/MAX_SAMPLES);\n\t\tcorrelations[offset] = correlation; // store it, for the tweaking we need to do below.\n\t\tif ((correlation>GOOD_ENOUGH_CORRELATION) && (correlation > lastCorrelation)) {\n\t\t\tfoundGoodCorrelation = true;\n\t\t\tif (correlation > best_correlation) {\n\t\t\t\tbest_correlation = correlation;\n\t\t\t\tbest_offset = offset;\n\t\t\t}\n\t\t} else if (foundGoodCorrelation) {\n\t\t\t// short-circuit - we found a good correlation, then a bad one, so we'd just be seeing copies from here.\n\t\t\t// Now we need to tweak the offset - by interpolating between the values to the left and right of the\n\t\t\t// best offset, and shifting it a bit. This is complex, and HACKY in this code (happy to take PRs!) -\n\t\t\t// we need to do a curve fit on correlations[] around best_offset in order to better determine precise\n\t\t\t// (anti-aliased) offset.\n\n\t\t\t// we know best_offset >=1, \n\t\t\t// since foundGoodCorrelation cannot go to true until the second pass (offset=1), and \n\t\t\t// we can't drop into this clause until the following pass (else if).\n\t\t\tvar shift = (correlations[best_offset+1] - correlations[best_offset-1])/correlations[best_offset]; \n\t\t\treturn sampleRate/(best_offset+(8*shift));\n\t\t}\n\t\tlastCorrelation = correlation;\n\t}\n\tif (best_correlation > 0.01) {\n\t\t// console.log(\"f = \" + sampleRate/best_offset + \"Hz (rms: \" + rms + \" confidence: \" + best_correlation + \")\")\n\t\treturn sampleRate/best_offset;\n\t}\n\treturn -1;\n//\tvar best_frequency = sampleRate/best_offset;\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n \n var _win = s.window; // shortcut\n \n var wmask = s.w_mask;\n var prev = s.prev;\n \n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n \n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n \n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n \n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n \n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n \n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n \n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n \n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n \n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n \n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n \n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n \n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n \n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n \n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n }", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\t\n\t var _win = s.window; // shortcut\n\t\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\t\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\t\n\t var strend = s.strstart + MAX_MATCH$1;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\t\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\t\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\t\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\t\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\t\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\t\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\t\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\t\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\t\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\t\n\t len = MAX_MATCH$1 - (strend - scan);\n\t scan = strend - MAX_MATCH$1;\n\t\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\t\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t }", "function longest_match$1(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD$1)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD$1) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH$3;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH$3 - (strend - scan);\n\t scan = strend - MAX_MATCH$3;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "async function lower_bound(searchString, fd, bytes) {\n // IMPORTANT NOTE: Requires log file to have a EOL at the very end, otherwise this breaks.\n let ans = null;\n let start_byte = null; //store the byte at which the ans starts\n let len = 0;\n\n let buffer = Buffer.alloc(258);\n\n let lo = 0;\n let hi = bytes - 1;\n\n while (lo < hi) {\n\n const mid = lo + Math.floor((hi - lo) / 2);\n let pos;\n let bytesToNext = 0;\n if (mid > 0) {\n pos = await read(fd, buffer, 0, buffer.length, mid); // read 258 bytes and fill my buffer\n const cur = buffer.slice(0, pos.bytesRead).toString();\n for (let i = 0; i < cur.length; i++) {\n if (cur[i] === EOL) {\n bytesToNext = i + 1;\n break; // break at first line break\n }\n }\n }\n\n // mid + bytesToNext now points at start of line after the line mid is on\n let currentLogLine = \"\";\n // will store from mid + bytesToNext to mid + bytesToNext + 256 bytes or wherever\n // line break occurs earlier\n\n\n pos = await read(fd, buffer, 0, buffer.length, mid + bytesToNext);\n const current = buffer.slice(0, pos.bytesRead).toString();\n for (let i = 0; i < current.length; i++) {\n currentLogLine += current[i];\n if (current[i] === EOL) break;\n // only want upto the first line break, makes one whole log\n }\n\n const dt = currentLogLine.substr(0, 19); // extract the date and time part from the log line //OK\n // console.log(\"current comparators : \", dt, searchString);\n\n // update bounds\n if (dt >= searchString) {\n hi = mid - 1;\n ans = currentLogLine;\n start_byte = mid + bytesToNext;\n len = currentLogLine.length;\n }\n else {\n lo = mid + 1;\n }\n }\n // if (start_byte >= bytes) ans = null;\n return {\n ans,\n start_byte,\n len\n }\n}", "function Occurence(count,searchstr,mainstr)\n{\n //console.log(\"Occurance:\"+count+\"/\"+searchstr+\"/\"+ mainstr)\n let offset=0;\n for (let i=0;i<count;i++)\n {\n let n = mainstr.substring(offset).indexOf(searchstr);\n if (n>=0)\n {\n offset+=n+ searchstr.length;\n }\n else\n {\n //console.log(\"error\");\n return -1\n }\n //console.log(offset);\n //console.log(mainstr.substring(offset)) \n }\n let ret= offset-searchstr.length;\n //console.log(\"Occurance:\"+mainstr.substring(ret))\n return ret;\n}", "function handleMatch(match, loopNdx, quantifierRecurse) {\n\t function isFirstMatch(latestMatch, tokenGroup) {\n\t var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;\n\t if (!firstMatch) {\n\t $.each(tokenGroup.matches, function (ndx, match) {\n\t if (match.isQuantifier === true) {\n\t firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]);\n\t if (firstMatch) return false;\n\t }\n\t });\n\t }\n\t return firstMatch;\n\t }\n\n\t function resolveNdxInitializer(pos, alternateNdx) {\n\t var bestMatch = selectBestMatch(pos, alternateNdx);\n\t return bestMatch ? bestMatch.locator.slice(bestMatch.alternation + 1) : [];\n\t }\n\t if (testPos > 10000) {\n\t throw \"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. \" + getMaskSet().mask;\n\t }\n\t if (testPos === pos && match.matches === undefined) {\n\t matches.push({\n\t \"match\": match,\n\t \"locator\": loopNdx.reverse(),\n\t \"cd\": cacheDependency\n\t });\n\t return true;\n\t } else if (match.matches !== undefined) {\n\t if (match.isGroup && quantifierRecurse !== match) { //when a group pass along to the quantifier\n\t match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx);\n\t if (match) return true;\n\t } else if (match.isOptional) {\n\t var optionalToken = match;\n\t match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);\n\t if (match) {\n\t latestMatch = matches[matches.length - 1].match;\n\t if (isFirstMatch(latestMatch, optionalToken)) {\n\t insertStop = true; //insert a stop\n\t testPos = pos; //match the position after the group\n\t } else return true;\n\t }\n\t } else if (match.isAlternator) {\n\t var alternateToken = match,\n\t\t\t\t\t\t\t\t\tmalternateMatches = [],\n\t\t\t\t\t\t\t\t\tmaltMatches,\n\t\t\t\t\t\t\t\t\tcurrentMatches = matches.slice(),\n\t\t\t\t\t\t\t\t\tloopNdxCnt = loopNdx.length;\n\t var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;\n\t if (altIndex === -1 || typeof altIndex === \"string\") {\n\t var currentPos = testPos,\n\t\t\t\t\t\t\t\t\t\tndxInitializerClone = ndxInitializer.slice(),\n\t\t\t\t\t\t\t\t\t\taltIndexArr = [],\n\t\t\t\t\t\t\t\t\t\tamndx;\n\t if (typeof altIndex == \"string\") {\n\t altIndexArr = altIndex.split(\",\");\n\t } else {\n\t for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {\n\t altIndexArr.push(amndx);\n\t }\n\t }\n\t for (var ndx = 0; ndx < altIndexArr.length; ndx++) {\n\t amndx = parseInt(altIndexArr[ndx]);\n\t matches = [];\n\t //set the correct ndxInitializer\n\t ndxInitializer = resolveNdxInitializer(testPos, amndx);\n\t match = handleMatch(alternateToken.matches[amndx] || maskToken.matches[amndx], [amndx].concat(loopNdx), quantifierRecurse) || match;\n\t if (match !== true && match !== undefined && (altIndexArr[altIndexArr.length - 1] < alternateToken.matches.length)) { //no match in the alternations (length mismatch) => look further\n\t var ntndx = maskToken.matches.indexOf(match) + 1;\n\t if (maskToken.matches.length > ntndx) {\n\t match = handleMatch(maskToken.matches[ntndx], [ntndx].concat(loopNdx.slice(1, loopNdx.length)), quantifierRecurse);\n\t if (match) {\n\t altIndexArr.push(ntndx.toString());\n\t $.each(matches, function (ndx, lmnt) {\n\t lmnt.alternation = loopNdx.length - 1;\n\t });\n\t }\n\t }\n\t }\n\t maltMatches = matches.slice();\n\t testPos = currentPos;\n\t matches = [];\n\t //cloneback\n\t for (var i = 0; i < ndxInitializerClone.length; i++) {\n\t ndxInitializer[i] = ndxInitializerClone[i];\n\t }\n\t //fuzzy merge matches\n\t for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {\n\t var altMatch = maltMatches[ndx1];\n\t altMatch.alternation = altMatch.alternation || loopNdxCnt;\n\t for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {\n\t var altMatch2 = malternateMatches[ndx2];\n\t //verify equality\n\t if (altMatch.match.def === altMatch2.match.def && (typeof altIndex !== \"string\" || $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1)) {\n\t if (altMatch.match.mask === altMatch2.match.mask) {\n\t maltMatches.splice(ndx1, 1);\n\t ndx1--;\n\t }\n\t if (altMatch2.locator[altMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {\n\t altMatch2.locator[altMatch.alternation] = altMatch2.locator[altMatch.alternation] + \",\" + altMatch.locator[altMatch.alternation];\n\t altMatch2.alternation = altMatch.alternation; //we pass the alternation index => used in determineLastRequiredPosition\n\t }\n\t break;\n\t }\n\t }\n\t }\n\t malternateMatches = malternateMatches.concat(maltMatches);\n\t }\n\n\t if (typeof altIndex == \"string\") { //filter matches\n\t malternateMatches = $.map(malternateMatches, function (lmnt, ndx) {\n\t if (isFinite(ndx)) {\n\t var mamatch,\n\t\t\t\t\t\t\t\t\t\t\t\t\talternation = lmnt.alternation,\n\t\t\t\t\t\t\t\t\t\t\t\t\taltLocArr = lmnt.locator[alternation].toString().split(\",\");\n\t lmnt.locator[alternation] = undefined;\n\t lmnt.alternation = undefined;\n\t for (var alndx = 0; alndx < altLocArr.length; alndx++) {\n\t mamatch = $.inArray(altLocArr[alndx], altIndexArr) !== -1;\n\t if (mamatch) { //rebuild the locator with valid entries\n\t if (lmnt.locator[alternation] !== undefined) {\n\t lmnt.locator[alternation] += \",\";\n\t lmnt.locator[alternation] += altLocArr[alndx];\n\t } else lmnt.locator[alternation] = parseInt(altLocArr[alndx]);\n\n\t lmnt.alternation = alternation;\n\t }\n\t }\n\t if (lmnt.locator[alternation] !== undefined) return lmnt;\n\t }\n\t });\n\t }\n\n\t matches = currentMatches.concat(malternateMatches);\n\t testPos = pos;\n\t insertStop = matches.length > 0; //insert a stopelemnt when there is an alternate - needed for non-greedy option\n\t } else {\n\t // if (alternateToken.matches[altIndex]) { //if not in the initial alternation => look further\n\t match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [altIndex].concat(loopNdx), quantifierRecurse);\n\t // } else match = false;\n\t }\n\t if (match) return true;\n\t } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {\n\t var qt = match;\n\t for (var qndx = (ndxInitializer.length > 0) ? ndxInitializer.shift() : 0;\n\t\t\t\t\t\t\t\t\t(qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max)) && testPos <= pos; qndx++) {\n\t var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];\n\t match = handleMatch(tokenGroup, [qndx].concat(loopNdx), tokenGroup); //set the tokenGroup as quantifierRecurse marker\n\t if (match) {\n\t //get latest match\n\t latestMatch = matches[matches.length - 1].match;\n\t latestMatch.optionalQuantifier = qndx > (qt.quantifier.min - 1);\n\t if (isFirstMatch(latestMatch, tokenGroup)) { //search for next possible match\n\t if (qndx > (qt.quantifier.min - 1)) {\n\t insertStop = true;\n\t testPos = pos; //match the position after the group\n\t break; //stop quantifierloop\n\t } else return true;\n\t } else {\n\t return true;\n\t }\n\t }\n\t }\n\t } else {\n\t match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);\n\t if (match) return true;\n\t }\n\t } else testPos++;\n\t }", "function matchPatternOrExact(patternStrings, candidate) {\n var patterns = [];\n for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {\n var patternString = patternStrings_1[_i];\n var pattern = tryParsePattern(patternString);\n if (pattern) {\n patterns.push(pattern);\n }\n else if (patternString === candidate) {\n // pattern was matched as is - no need to search further\n return patternString;\n }\n }\n return findBestPatternMatch(patterns, function (_) { return _; }, candidate);\n }", "function ArrayMatching(strArr) {\n var a = strArr[0].match(/d+/g).map(Number);\n var b = strArr[1].match(/d+/g).map(Number);\n\n var longest = a.length >= b.length ? a : b;\n var other = longest === a ? b : a;\n\n return longest.map((e, i) => (other[i] ? e + other[i] : e)).join(\"-\");\n}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH - (strend - scan);\n\t scan = strend - MAX_MATCH;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "match(input, start, end) {\n start = start || 0\n end = end || input.length\n if(typeof input === 'string') input = new Source(input)\n for(var i=0; i<this.word.length; i++) {\n var x = input.substring(start,Math.min(end, start+this.word[i].length))\n if(this.word[i]==x) return this.token(input,start,start+x.length,x)\n }\n return this.error(input,start,start+1)\n }", "function matchString(st, ind, arr){\n if ((st == queArray[0])&&\n (arr[ind+(queArray.length-1)]==queArray[queArray.length-1]))\n {return true;}else return false;\n }", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n }", "function exmaple1(str = 'I am abcdef') {\n function match(string) {\n let state = start;\n \n for(let c of string) {\n // Iteratelly change value of state\n // If variable is 'a', then state will be record that A is found, and start found B.\n state = state(c);\n }\n \n return state === end;\n }\n \n function start(c) {\n if (c === 'a')\n return foundA;\n else\n return start(c);\n }\n \n function end(c) {\n return end;\n }\n \n function foundA(c) {\n if (c === 'b') \n return foundB;\n else\n return start(c);\n }\n \n function foundB(c) {\n if (c === 'c')\n return foundC;\n else\n return start(c);\n }\n \n function foundC(c) {\n if (c === 'd') \n return foundD;\n else\n return start(c);\n }\n \n function foundD(c) {\n if (c === 'e') \n return end;\n else\n return start(c);\n }\n \n console.log(match(str));\n}", "function searchAll(str, search, substr = null, resultArr = []){\n const result = substr ? substr.search(search) : str.search(search);\n if(result === -1) {return resultArr}\n // difference is used to account for the decreasing length of the substring when computing the index\n const difference = substr ? str.length - substr.length : 0;\n // the next search will start right after the starting position of the current match instead of the last position like in String.matchAll\n const slicedStr = str.slice(result + difference + 1);\n return searchAll(str, search, slicedStr, [...resultArr, result + difference])\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}", "function longest_match(s, cur_match) {\n\t var chain_length = s.max_chain_length; /* max hash chain length */\n\t var scan = s.strstart; /* current string */\n\t var match; /* matched string */\n\t var len; /* length of current match */\n\t var best_len = s.prev_length; /* best match length so far */\n\t var nice_match = s.nice_match; /* stop if match long enough */\n\t var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n\t s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n\t var _win = s.window; // shortcut\n\n\t var wmask = s.w_mask;\n\t var prev = s.prev;\n\n\t /* Stop when cur_match becomes <= limit. To simplify the code,\n\t * we prevent matches with the string of window index 0.\n\t */\n\n\t var strend = s.strstart + MAX_MATCH$1;\n\t var scan_end1 = _win[scan + best_len - 1];\n\t var scan_end = _win[scan + best_len];\n\n\t /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n\t * It is easy to get rid of this optimization if necessary.\n\t */\n\t // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n\t /* Do not waste too much time if we already have a good match: */\n\t if (s.prev_length >= s.good_match) {\n\t chain_length >>= 2;\n\t }\n\t /* Do not look for matches beyond the end of the input. This is necessary\n\t * to make deflate deterministic.\n\t */\n\t if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n\t // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n\t do {\n\t // Assert(cur_match < s->strstart, \"no future\");\n\t match = cur_match;\n\n\t /* Skip to next match if the match length cannot increase\n\t * or if the match length is less than 2. Note that the checks below\n\t * for insufficient lookahead only occur occasionally for performance\n\t * reasons. Therefore uninitialized memory will be accessed, and\n\t * conditional jumps will be made that depend on those values.\n\t * However the length of the match is limited to the lookahead, so\n\t * the output of deflate is not affected by the uninitialized values.\n\t */\n\n\t if (_win[match + best_len] !== scan_end ||\n\t _win[match + best_len - 1] !== scan_end1 ||\n\t _win[match] !== _win[scan] ||\n\t _win[++match] !== _win[scan + 1]) {\n\t continue;\n\t }\n\n\t /* The check at best_len-1 can be removed because it will be made\n\t * again later. (This heuristic is not always a win.)\n\t * It is not necessary to compare scan[2] and match[2] since they\n\t * are always equal when the other bytes match, given that\n\t * the hash keys are equal and that HASH_BITS >= 8.\n\t */\n\t scan += 2;\n\t match++;\n\t // Assert(*scan == *match, \"match[2]?\");\n\n\t /* We check for insufficient lookahead only every 8th comparison;\n\t * the 256th check will be made at strstart+258.\n\t */\n\t do {\n\t /*jshint noempty:false*/\n\t } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n\t scan < strend);\n\n\t // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n\t len = MAX_MATCH$1 - (strend - scan);\n\t scan = strend - MAX_MATCH$1;\n\n\t if (len > best_len) {\n\t s.match_start = cur_match;\n\t best_len = len;\n\t if (len >= nice_match) {\n\t break;\n\t }\n\t scan_end1 = _win[scan + best_len - 1];\n\t scan_end = _win[scan + best_len];\n\t }\n\t } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n\t if (best_len <= s.lookahead) {\n\t return best_len;\n\t }\n\t return s.lookahead;\n\t}", "function find(str1, str2) {\n //创建存放重复内容的数组\n var all = new Array();\n //字符串转字符数组\n var str_1 = str1.split(\"\");\n var str_2 = str2.split(\"\");\n for (var i = 0; i < str_1.length; i++) {\n for (var l = 0; l < str_2.length; l++) {\n //判断是否重复\n var lo = all.length;\n all[lo] = \"\";\n //判断之后的字符串是否相同\n for (var k = 0; str_1[i + k] == str_2[l + k]; k++) {\n all[lo] = all[lo] + str_1[i + k];\n //防止数组越界,提前停止循环\n if (i + k == str_1.length-1||i+k==str_2.length-1) {\n break;\n }\n }\n }\n }\n \n var most = 0;\n var fu = new Array();\n for (var j = 0; j < all.length; j++) {\n //去除空的内容\n if (all[j] != \"\") {\n //按照大小排序(删除部分小的)\n if (all[j].split(\"\").length >= most) {\n most = all[j].split(\"\").length;\n fu[fu.length] = all[j];\n }\n }\n }\n \n //将不重复内容写到新数组\n var wu=new Array();\n for(var i=0;i<fu.length;i++){\n var c=false;\n for(var l=0;l<wu.length;l++){\n if(fu[i]==wu[l]){\n c=true;\n }\n }\n if(!c){\n wu[wu.length]=fu[i];\n }\n }\n \n //将最长的内容写到新数组\n var ml=new Array();\n //获得最后一个字符串的长度(最长)\n var longest=wu[wu.length-1].split(\"\").length;\n //长度等于最长的内容放到新数组\n for(var i=wu.length-1;i>=0;i--){\n if(wu[i].split(\"\").length==longest){\n ml[ml.length]=wu[i];\n }else{\n //提前结束循环\n break;\n }\n }\n \n return ml\n }", "function generateLCS(stringA, stringB) {\n // obtain the lengths of both strings\n const m = stringA.length;\n const n = stringB.length;\n\n /* create a 2D array for dynamic programming approach, this will be the LCS\n table, which will yield the lengths of the LCS's for the (sub)strings, and\n backtracking along it yields the actual LCS. */\n lcsTable = []\n for (let i = 0; i < m + 1; i++) {\n lcsTable[i] = [];\n }\n\n // make the first row of the lcs table all 0's\n for (let i = 0; i < n + 1; i++) {\n lcsTable[0][i] = 0;\n }\n\n // make the first column of the lcs table all 0's\n for (let i = 0; i < m + 1; i++) {\n lcsTable[i][0] = 0;\n }\n\n // fill the rest of the lcs table\n for (let i = 1; i < m + 1; i++) {\n for (let j = 1; j < n + 1; j++) {\n if (stringA.charAt(i - 1) == stringB.charAt(j - 1)) {\n lcsTable[i][j] = lcsTable[i - 1][j - 1] + 1;\n } else {\n lcsTable[i][j] = Math.max(lcsTable[i][j - 1],\n lcsTable[i - 1][j]);\n }\n }\n }\n\n // obtain the length of the lcs\n const lcsLength = lcsTable[m][n];\n\n // backtrack along the lcs table to build the lcs string\n let lcsString = \"\";\n let cornerRow = m, cornerCol = n;\n for (let i = lcsLength; i >= 1; i--) {\n // find the next corner\n while (lcsTable[cornerRow][cornerCol - 1] == i) {\n cornerCol--;\n }\n while (lcsTable[cornerRow - 1][cornerCol] == i) {\n cornerRow--;\n }\n\n // prepend the character of that corner to the lcs string\n lcsString = stringA.charAt(cornerRow - 1) + lcsString;\n\n // decrement cornerRow and cornerCol\n cornerRow--;\n cornerCol--;\n }\n\n // return a small array containing the lcs string and its length\n return [\"\\\"\" + lcsString + \"\\\"\", lcsLength];\n}", "allStringPositions(hay, ndl) {\n let off = 0 // offset\n let all = []\n let pos\n\n while ((pos = hay.indexOf(ndl, off)) !== -1) {\n off = pos + 1\n all.push(pos)\n }\n\n return all\n }", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}", "function longest_match(s, cur_match) {\n var chain_length = s.max_chain_length; /* max hash chain length */\n var scan = s.strstart; /* current string */\n var match; /* matched string */\n var len; /* length of current match */\n var best_len = s.prev_length; /* best match length so far */\n var nice_match = s.nice_match; /* stop if match long enough */\n var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n var _win = s.window; // shortcut\n\n var wmask = s.w_mask;\n var prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n var strend = s.strstart + MAX_MATCH;\n var scan_end1 = _win[scan + best_len - 1];\n var scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH - (strend - scan);\n scan = strend - MAX_MATCH;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n}" ]
[ "0.64182967", "0.62951267", "0.62951267", "0.6201219", "0.59356546", "0.5885474", "0.58198744", "0.57690024", "0.57289577", "0.5691932", "0.56858134", "0.56737226", "0.5673231", "0.5602287", "0.5567311", "0.5566176", "0.5563941", "0.5563941", "0.5497012", "0.5438994", "0.5428671", "0.54074967", "0.5389228", "0.536537", "0.53589225", "0.5352305", "0.5323789", "0.5316404", "0.53121203", "0.53121203", "0.53121203", "0.5300801", "0.5294888", "0.52749807", "0.52564514", "0.52466315", "0.5238672", "0.5233974", "0.52189124", "0.5177868", "0.5167208", "0.51628834", "0.5157782", "0.51498055", "0.5144232", "0.5129946", "0.5115671", "0.5112242", "0.5105759", "0.51033026", "0.5074957", "0.50539386", "0.505178", "0.5044204", "0.5032753", "0.5027393", "0.5009171", "0.5006377", "0.50034034", "0.49980167", "0.49915418", "0.49791637", "0.49767536", "0.49727038", "0.49656266", "0.49648637", "0.49618596", "0.49613485", "0.49428374", "0.4938448", "0.49377483", "0.49339676", "0.49266762", "0.49266386", "0.4926599", "0.49217388", "0.49208158", "0.49188063", "0.49183318", "0.49183318", "0.49183318", "0.49183318", "0.49183318", "0.49183318", "0.49183318", "0.4918329", "0.4916024", "0.49138427", "0.4911662", "0.49106067", "0.4909372", "0.4907649", "0.49076167", "0.49031815", "0.48834237", "0.48781306", "0.48781306", "0.48781306", "0.48781306" ]
0.669368
1
get image corresponding to given string of cipher letters
function getImg(s) { var result = ""; for (var i=0; i<s.length; i++) { result += "<img src=\"alphabet/" + getName(s.substring(i,i+1)) + ".jpg\">"; } return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function GetImage(letter) {\n if (letter == \"A\") {\n return IMAGES.A;\n } else if (letter == \"B\") {\n return IMAGES.B;\n } else if (letter == \"C\") {\n return IMAGES.C;\n } else if (letter == \"D\") {\n return IMAGES.D;\n } else if (letter == \"E\") {\n return IMAGES.E;\n } else if (letter == \"F\") {\n return IMAGES.F;\n } else if (letter == \"G\") {\n return IMAGES.G;\n } else if (letter == \"H\") {\n return IMAGES.H;\n } else if (letter == \"I\") {\n return IMAGES.I;\n } else if (letter == \"J\") {\n return IMAGES.J;\n } else if (letter == \"K\") {\n return IMAGES.K;\n } else if (letter == \"L\") {\n return IMAGES.L;\n } else if (letter == \"M\") {\n return IMAGES.M;\n } else if (letter == \"N\") {\n return IMAGES.N;\n } else if (letter == \"O\") {\n return IMAGES.O;\n } else if (letter == \"P\") {\n return IMAGES.P;\n } else if (letter == \"Q\") {\n return IMAGES.Q;\n } else if (letter == \"R\") {\n return IMAGES.R;\n } else if (letter == \"S\") {\n return IMAGES.S;\n } else if (letter == \"T\") {\n return IMAGES.T;\n } else if (letter == \"U\") {\n return IMAGES.U;\n } else if (letter == \"V\") {\n return IMAGES.V;\n } else if (letter == \"W\") {\n return IMAGES.W;\n } else if (letter == \"X\") {\n return IMAGES.X;\n } else if (letter == \"Y\") {\n return IMAGES.Y;\n } else if (letter == \"Z\") {\n return IMAGES.Z;\n } else if (letter == \"_\") {\n return IMAGES._;\n }\n}", "function getImg(s, row) {\n\t\tvar result = \"\";\n\t\tfor (var i=0; i<s.length; i++) {\n\t\t\tvar g = \"\";\n\t\t\t//if (row % 2 == 0) g = \"green/lighter/\"\n\t\t\tresult += \"<img src=\\\"alphabet2/\" + g + getName(s.substring(i,i+1)) + \".jpg\\\">\";\n\t\t}\n\t\treturn result;\n\t}", "function getWordImg (cadena, marca)\r\n{\r\n var imatge;\r\n var word;\r\n var ParaulaImatge;\r\n var posMarca = cadena.indexOf (marca);\r\n word = cadena.substring (0, posMarca);\r\n imatge = cadena.substring (posMarca + 1, cadena.length);\r\n ParaulaImatge = new WordImg (word.toUpperCase(), imatge, \"so/\" + generate(word) + \".wav\");\r\n return ParaulaImatge;\r\n}", "makeImage(char, expanded, options) {\n const key = {\n char: char,\n expanded: expanded,\n options: options,\n };\n const stringKey = JSON.stringify(key);\n // Cache the glyph since we create a set of these for each created canvas.\n let glyph = this.glyphCache.get(stringKey);\n if (glyph === undefined) {\n glyph = this.makeImageInternal(char, expanded, options);\n this.glyphCache.set(stringKey, glyph);\n }\n return glyph;\n }", "function getCharacterImg(id){\n if (id < 10){\n id = \"0\" + id.toString()\n } \n return `../../asset/Yang_Walk_LR/Yang_Walk_LR_000${id}.png`\n }", "function letterDisplay() {\r\n\t\tlet pic = document.createElement(\"IMG\");\r\n\t\tpic.setAttribute(\"src\", \"AtoZ ASL/\"+letter+\".png\");\r\n\t\tlet node = document.createTextNode(letter);\r\n\t\tpic.appendChild(node);\t\t\r\n\t\tlet element = document.getElementById(\"output\");\r\n\t\telement.appendChild(pic);\r\n}", "function getgLetterImage(number) {\n let source;\n switch (number) {\n case \"0\":\n source = '<img src=\"assets/images/card_A.jpg\">';\n break;\n case \"1\":\n source = '<img src=\"assets/images/card_B.jpg\">';\n break;\n case \"2\":\n source = '<img src=\"assets/images/card_C.jpg\">';\n break;\n case \"3\":\n source = '<img src=\"assets/images/card_D.jpg\">';\n break;\n case \"4\":\n source = '<img src=\"assets/images/card_E.jpg\">';\n break;\n case \"5\":\n source = '<img src=\"assets/images/card_F.jpg\">';\n break;\n case \"6\":\n source = '<img src=\"assets/images/card_G.jpg\">';\n break;\n case \"7\":\n source = '<img src=\"assets/images/card_H.jpg\">';\n break;\n case \"8\":\n source = '<img src=\"assets/images/card_I.jpg\">';\n break;\n case \"9\":\n source = '<img src=\"assets/images/card_J.jpg\">';\n break;\n case \"10\":\n source = '<img src=\"assets/images/card_K.jpg\">';\n break;\n case \"11\":\n source = '<img src=\"assets/images/card_L.jpg\">';\n break;\n case \"12\":\n source = '<img src=\"assets/images/card_M.jpg\">';\n break;\n case \"13\":\n source = '<img src=\"assets/images/card_N.jpg\">';\n break;\n case \"14\":\n source = '<img src=\"assets/images/card_O.jpg\">';\n break;\n case \"15\":\n source = '<img src=\"assets/images/card_P.jpg\">';\n break;\n case \"16\":\n source = '<img src=\"assets/images/card_Q.jpg\">';\n break;\n case \"17\":\n source = '<img src=\"assets/images/card_R.jpg\">';\n break;\n case \"18\":\n source = '<img src=\"assets/images/card_S.jpg\">';\n break;\n case \"19\":\n source = '<img src=\"assets/images/card_T.jpg\">';\n break;\n case \"20\":\n source = '<img src=\"assets/images/card_U.jpg\">';\n break;\n case \"21\":\n source = '<img src=\"assets/images/card_V.jpg\">';\n break;\n case \"22\":\n source = '<img src=\"assets/images/card_W.jpg\">';\n break;\n case \"23\":\n source = '<img src=\"assets/images/card_X.jpg\">';\n break;\n case \"24\":\n source = '<img src=\"assets/images/card_Y.jpg\">';\n break;\n case \"25\":\n source = '<img src=\"assets/images/card_Z.jpg\">';\n break;\n default:\n source = '<img src=\"assets/images/card_back.jpg\">';\n }\n return source;\n}", "function convertToImg(str, p1, p2, s) {\n path = p2.split('/')\n p2 = 'images/'+path[path.length-1]\n console.log('p2',p2)\n\t\t\t\treturn '<img src=\"'+p2+'\" alt=\"'+p1+'\"/>'\n\t\t\t\t}", "function getImgDarker(s) {\n\t\tvar result = \"\";\n\t\tfor (var i=0; i<s.length; i++) {\n\t\t\tresult += \"<img src=\\\"alphabet/darker/\" + getName(s.substring(i,i+1)) + \".jpg\\\">\";\n\t\t}\n\t\treturn result;\n\t}", "function getgPunctuationImage(number) {\n let source;\n switch (number) {\n case \"0\":\n source = '<img src=\"assets/images/card_Ampresand.jpg\">';\n break;\n case \"1\":\n source = '<img src=\"assets/images/card_Apostrope.jpg\">';\n break;\n case \"2\":\n source = '<img src=\"assets/images/card_At.jpg\">';\n break;\n case \"3\":\n source = '<img src=\"assets/images/card_Colon.jpg\">';\n break;\n case \"4\":\n source = '<img src=\"assets/images/card_Comma.jpg\">';\n break;\n case \"5\":\n source = '<img src=\"assets/images/card_Dollar.jpg\">';\n break;\n case \"6\":\n source = '<img src=\"assets/images/card_Equals.jpg\">';\n break;\n case \"7\":\n source = '<img src=\"assets/images/card_Exclamation.jpg\">';\n break;\n case \"8\":\n source = '<img src=\"assets/images/card_Hyphen.jpg\">';\n break;\n case \"9\":\n source = '<img src=\"assets/images/card_ParanthesisClose.jpg\">';\n break;\n case \"10\":\n source = '<img src=\"assets/images/card_ParanthesisOpen.jpg\">';\n break;\n case \"11\":\n source = '<img src=\"assets/images/card_Period.jpg\">';\n break;\n case \"12\":\n source = '<img src=\"assets/images/card_Plus.jpg\">';\n break;\n case \"13\":\n source = '<img src=\"assets/images/card_Question.jpg\">';\n break;\n case \"14\":\n source = '<img src=\"assets/images/card_Quotation.jpg\">';\n break;\n case \"15\":\n source = '<img src=\"assets/images/card_Slash.jpg\">';\n break;\n case \"16\":\n source = '<img src=\"assets/images/card_Underscore.jpg\">';\n break;\n default:\n source = '<img src=\"assets/images/card_back.jpg\">';\n }\n return source;\n}", "function txtToImg(selString) {\n //Creates canvas element\n var canv = document.createElement('canvas');\n canv.setAttribute(\"type\", \"hidden\");\n canv.id = 'canvas';\n canv.width = 500;\n canv.height = 500;\n canv.style.position = \"absolute\";\n document.body.appendChild(canv);\n var ctx = canv.getContext('2d');\n ctx.fillStyle = \"white\";\n ctx.fillRect(0, 0, canv.width, canv.height);\n\n //Puts text on canvas element\n ctx.font = \"25px Segoe UI Semibold\";\n var mwidth = canv.width - 50;\n var y = 35;\n var x = (canv.width - mwidth) / 2;\n var height = 25;\n var color = \"black\"\n wrapText(ctx, selString, x, y, mwidth, height, color);\n var url = canv.toDataURL(\"image/png\");\n\n return url;\n }", "makeImageInternal(char, expanded, options) {\n const canvas = document.createElement(\"canvas\");\n let expandedMultiplier = expanded ? 2 : 1;\n canvas.width = this.width * expandedMultiplier;\n canvas.height = this.height * 2;\n const ctx = canvas.getContext(\"2d\");\n if (ctx === null) {\n throw new Error(\"2d context not supported\");\n }\n const imageData = ctx.createImageData(canvas.width, canvas.height);\n // Light pixel at (x,y) in imageData if bit \"bit\" of \"byte\" is on.\n const lightPixel = (x, y, byte, bit) => {\n const pixel = (byte & (1 << bit)) !== 0;\n if (pixel) {\n const pixelOffset = (y * canvas.width + x) * 4;\n const alpha = options.scanLines ? (y % 2 == 0 ? 0xFF : 0xAA) : 0xFF;\n imageData.data[pixelOffset + 0] = options.color[0];\n imageData.data[pixelOffset + 1] = options.color[1];\n imageData.data[pixelOffset + 2] = options.color[2];\n imageData.data[pixelOffset + 3] = alpha;\n }\n };\n const bankOffset = this.banks[Math.floor(char / 64)];\n if (bankOffset === -1) {\n // Graphical character.\n const byte = char % 64;\n for (let y = 0; y < canvas.height; y++) {\n const py = Math.floor(y / (canvas.height / 3));\n for (let x = 0; x < canvas.width; x++) {\n const px = Math.floor(x / (canvas.width / 2));\n const bit = py * 2 + px;\n lightPixel(x, y, byte, bit);\n }\n }\n }\n else {\n // Bitmap character.\n const charOffset = bankOffset + char % 64;\n const byteOffset = charOffset * 12;\n for (let y = 0; y < canvas.height; y++) {\n const byte = this.bits[byteOffset + Math.floor(y / 2)];\n for (let x = 0; x < canvas.width; x++) {\n lightPixel(x, y, byte, Math.floor(x / expandedMultiplier));\n }\n }\n }\n ctx.putImageData(imageData, 0, 0);\n return canvas;\n }", "function displayImg(word) {\n \n if (word === \"pancake\"){\n document.getElementById(\"coolimage\").src = \"assets/images/pancake.jpg\";\n }\n\n if (word === \"ducky\"){\n document.getElementById(\"coolimage\").src = \"assets/images/ducky.jpg\";\n }\n\n if (word === \"panda\"){\n document.getElementById(\"coolimage\").src = \"assets/images/panda.jpg\";\n }\n\n if (word === \"monkey\"){\n document.getElementById(\"coolimage\").src = \"assets/images/monkey.jpg\";\n }\n\n}", "function dumpLetters(data) {\n const png = PNG.sync.read(data);\n let count = 0;\n\n for (var i = 0; i < png.data.length; i++) {\n if (png.data[i] !== 0 && png.data[i] !== 255) {\n png.data[i] = 255;\n }\n }\n\n let letters = [];\n let currentLetter = {};\n let foundLetter = false;\n for (var x = 0, j = png.width; x < j; ++x) {\n // for every column\n var foundLetterInColumn = false;\n\n for (var y = 0, k = png.height; y < k; ++y) {\n // for every pixel\n var pixIndex = (y * png.width + x) * 4;\n if (png.data[pixIndex] === 0) {\n // if we're dealing with a letter pixel\n foundLetterInColumn = foundLetter = true;\n // set data for this letter\n currentLetter.minX = Math.min(x, currentLetter.minX || Infinity);\n currentLetter.maxX = Math.max(x, currentLetter.maxX || -1);\n currentLetter.minY = Math.min(y, currentLetter.minY || Infinity);\n currentLetter.maxY = Math.max(y, currentLetter.maxY || -1);\n }\n }\n\n // if we've reached the end of this letter, push it to letters array\n if (!foundLetterInColumn && foundLetter) {\n // get letter pixels\n letters.push({\n minX: currentLetter.minX,\n minY: currentLetter.minY,\n maxX: currentLetter.maxX - currentLetter.minX,\n maxY: currentLetter.maxY - currentLetter.minY\n });\n const height = currentLetter.maxY - currentLetter.minY + 1;\n const width = currentLetter.maxX - currentLetter.minX + 1;\n var dst = new PNG({ width, height });\n PNG.bitblt(\n png,\n dst,\n currentLetter.minX,\n currentLetter.minY,\n width,\n height,\n 0,\n 0\n );\n const buffer = PNG.sync.write(dst, {});\n\n const md5Hash = crypto\n .createHash('md5')\n .update(dst.data)\n .digest('hex');\n const newFilename = './letters/' + md5Hash + '.png';\n if(!fs.existsSync(newFilename)) {\n fs.writeFileSync(newFilename, buffer);\n count++;\n }\n \n\n // reset\n foundLetter = foundLetterInColumn = false;\n currentLetter = {};\n }\n }\n return count;\n}", "function decipher(string){\n\n}", "rc4(key, str) {\n var s = [], j = 0, x, res = '';\n for (var i = 0; i < 256; i++) {\n s[i] = i;\n }\n for (i = 0; i < 256; i++) {\n j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;\n x = s[i];\n s[i] = s[j];\n s[j] = x;\n }\n i = 0;\n j = 0;\n for (var y = 0; y < str.length; y++) {\n i = (i + 1) % 256;\n j = (j + s[i]) % 256;\n x = s[i];\n s[i] = s[j];\n s[j] = x;\n res += String.fromCharCode(str.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);\n }\n return res;\n }", "function getCharacterImg(dir, id){\n if (id < 10){\n id = \"0\" + id.toString()\n } \n if (dir === \"UP\"){\n return `../../asset/Yang_Walk_UP/Yang_Walk_UP_000${id}.png`\n } else if (dir === \"DOWN\"){\n return `../../asset/Yang_Walk_DN/Yang_Walk_DN_000${id}.png`\n } else if (dir === \"LEFT\" || dir === \"RIGHT\"){\n return `../../asset/Yang_Walk_LR/Yang_Walk_LR_000${id}.png`\n } \n}", "function convertFromImg(str, p1, p2, s) {\n var imgContainer = document.createElement( 'img' )\n imgContainer.innerHTML = str+'>'\n var src = imgContainer.firstChild.src\n var width = imgContainer.firstChild.width\n var alt = imgContainer.firstChild.alt\n var path = src.split('/')\n var filename = path[path.length-1]\n \n var out = `<img src=\"images/${ path[path.length-1] }\" width=\"${ width }\" alt=\"${ alt }\"`\n\t\t\t\treturn out\n\t\t\t\t}", "function pickIcon(match) {\n let firstLetter = match[0];\n let iconPath;\n for (let key in strife.icon) {\n if (firstLetter === key) {\n iconPath = strife.icon[key];\n }\n }\n return iconPath;\n}", "function caesarCipherEncryptor(string, key) {\n // Write your code here.\n // Create a var representing the alphabet\n // for loop: for each letter of the string,\n // find that letter's index in the alphabet. add 2 to that.\n // return alphabet with the new index\n // if it goes past 26, subtract 26\n\n const alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n let newStr = \"\";\n\n for (let i = 0; i < string.length; i++) {\n let idx = alphabet.indexOf(string[i]) + key;\n if (idx > 25) {\n idx = idx % 26;\n }\n newStr += alphabet[idx];\n }\n return newStr;\n}", "function getImage (charname) {\n $.get('/api/characters', function (data){\n for (var i =0;i<data.length;i++){\n if (data[i].name.indexOf(charname)>-1){\n if (charname==='obi-wan'){\n Materialize.toast('Hello there!', 3500)\n }\n $('#img-div').empty();\n var newImg = $('<img>');\n newImg.addClass('char-img')\n newImg.attr('src',data[i].url);\n $('#img-div').append(newImg);\n }\n }\n })\n}", "function emojiImage(el) {\n const image = document.createElement('img')\n image.className = 'emoji'\n image.alt = el.getAttribute('alias') || ''\n image.height = 20\n image.width = 20\n return image\n}", "function imageSearch(expression,string) {\n\treturn expression.test(string);\n}", "async function textToImage (text) {\n try {\n const ctx = document.createElement('CANVAS').getContext('2d');\n ctx.canvas.width = ctx.measureText(text).width;\n ctx.fillText(text, 0, 10);\n return await urlToFile(ctx.canvas.toDataURL(), 'image', 'jpg');\n } catch (err) {\n throw err;\n }\n}", "function getTextImage(imageId) {\n\n var width = 256;\n var height = 256;\n\n var tokens = imageId.substring(12).split(':');\n var l = tokens[0];\n var bg = tokens[1];\n var pixelData = createTextPixelData(l, bg);\n function getPixelData(){\n return pixelData;\n }\n\n var image = {\n imageId: imageId,\n minPixelValue : 0,\n maxPixelValue : 257,\n slope: 1.0,\n intercept: 0,\n windowCenter : 127,\n windowWidth : 256,\n render: cs.renderGrayscaleImage,\n getPixelData: getPixelData,\n rows: height,\n columns: width,\n height: height,\n width: width,\n color: false,\n columnPixelSpacing: 1.0,\n rowPixelSpacing: 1.0,\n invert: false,\n sizeInBytes: width * height\n };\n\n return {\n promise: new Promise((resolve) => {\n resolve(image);\n }),\n cancelFn: undefined\n };\n }", "function cipher(string, offset) {\n let code = '';\n for (let i = 0; i < string.length; i++) {\n let letter = string[i];\n let charCode = string.charCodeAt(i);\n if (charCode >= 65 && charCode <= 122) {\n letter = String.fromCharCode(((charCode - 65 + offset) % 26) + 65);\n } else if (charCode >= 97 && charCode <= 122) {\n letter = String.fromCharCode(((charCode - 97 + offset) % 26) + 97);\n }\n code += letter;\n }\n return code;\n}", "function caesarCipherEncryptor(string, key) {\n // Write your code here.\n if (key === 0) return string;\n let result = \"\";\n let alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n for (let i = 0; i < string.length; i++) {\n console.log(\"char\", string[i]);\n //grab the current char from input and find at what idx is it in alphabet\n let curIdx = alphabet.indexOf(string[i]); //23\n console.log(\"currentIdx\", curIdx);\n //find the needed idx of the letter that should replace it (from alphabet)\n let newIdx = curIdx + key; //25\n console.log(\"newIdx\", newIdx);\n while (newIdx >= 26) {\n newIdx = newIdx - 26;\n console.log(\"newIdx in loop\", newIdx);\n }\n //find that new letter and add it to the result string\n result += alphabet.charAt(newIdx);\n console.log(\"results string\", result);\n }\n return result;\n}", "render() {\n const {letters, onClick, className} = this.props\n return <div className={\"keyboard \" + (className || '')}>\n {letters.map((letter, index) =>\n <div\n key={index}\n className={\"contain-touch touch\" + letter + ' ' + this.displayLetter(letter)}\n onClick={() => onClick(letter)}>\n\n {\n // J'ai fait le choix d'utiliser une image en background mais je ne le referais pas ^^\n // Mauvais choix car pas simple et pas optimisé pour l'interactivite\n /*{letter}*/\n }\n </div>\n )}\n </div>\n }", "function add_char(ch,values) { \n var value = base64_values.indexOf(ch); \n var x = Math.floor(value / 8); \n var y = value % 8; \n values.push(x); \n values.push(y); \n }", "function drawLetters(hand)\r\n{\r\n\tvar str=\"\";\r\n\tvar parent=$('#letters');\r\n\tfor(i=0;i<hand.length;i++) {\r\n\t\tstr=str+' <img src=\"tiles/Scrabble_Tile_'+hand[i]+'.jpg\" class=\"pieces\" alt=\"'+hand[i]+'\" id=\"letter'+counterLetters+'\">';\r\n\t\tcounterLetters++;\r\n\t}\r\n\tparent.html(str+parent.html());\r\n}", "function updateHangmanImage(randomWord) {\n document.getElementById(\"image\").src = \"assets/images/\" + randomWord + \".jpg\";\n}", "function _newIv(text){\n var newIv = _encode(text.substr(0, 16));\n return newIv[0];\n}", "function getImage(){\n\t//check to see if they chose a character\n\tvar sel = this.options[this.selectedIndex];\n\t//get div\n\tvar div = this.parentNode.childNodes[5];\n\t\n\tif(sel.value == \"X\"){\n\t\t//alert error\n\t\tdiv.innerHTML = '<span class=\"error\">Please choose a character</span>';\n\t}else{\n\t\t//get image\n\t\tvar img = (sel.text);\n\t\timg = img.toLowerCase();\n\t\timg = img + \".gif\";\n\t\t\n\t\t//make innerHTML\n\t\tdiv.innerHTML = '<img src=\"images/' + img + '\" class=\"imgFloat\" />' + '<span class=\"correct\">Your character choice says something about you.</span>';\n\t}\n}", "function IDtoImage(id){\n\tvar scale = '1.0'\n\treturn 'https://static-cdn.jtvnw.net/emoticons/v1/' + id + '/' + scale;\n}", "getCharacters(){\n const characters = [\n 'images/char-boy.png',\n 'images/char-horn-girl.png',\n 'images/char-pink-girl.png',\n 'images/char-princess-girl.png',\n 'images/char-cat-girl.png'\n ];\n\n return characters;\n }", "function findLetter(letter) {\n\n\n // x postion of the first letter in a word\n var px = 100;\n // y postion of the first letter in a word\n var py = 200;\n var pSpace = 2;\n var nextPix = 0;\n // The array that will eventually hold of the letter\n var pixels = [];\n\n if (/^\\s+$/.test(letter)) {\n var l = 'space';\n } else {\n //Create a string to match the name of the funtion\n //that returns a letter in the alphabit\n var l = 'letter' + letter;\n }\n //Get the pattern for setting up the letter\n var pattern = window[l]().pattern;\n //Get the with of the letter\n var pWidth = window[l]().width;\n //The height of a letter is always 6 rects\n var pHeight = 6;\n\n //Below the letters of in given word are drawn\n // for every block in height ->\n for (var j = 0; j < pHeight; j++) {\n // is a row of blocks\n for (var i = 0; i < pWidth; i++) {\n\n // create new rect element\n var rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');\n rect.setAttribute('x', px.toString());\n rect.setAttribute('y', py.toString());\n rect.setAttribute('width', pixelSize.value.toString());\n rect.setAttribute('height', pixelSize.value.toString());\n rect.setAttribute('rx', rx.value.toString());\n rect.setAttribute('ry', '5');\n // Reads the pattern of the letters\n if (pattern[nextPix] == 0) {\n rect.setAttribute('fill', 'white');\n rect.setAttribute('fill-opacity', '0.0');\n } else {\n rect.setAttribute('fill', 'black');\n }\n // the next x coordinate is set with a little space in between rects\n px = px + endPixelSize + rx.value;\n console.log(px);\n pixels.push(rect);\n nextPix++;\n }\n // the y coordinate is set for every row of rects\n py = py + endPixelSize + rx.value;\n py.toString();\n // the x coordinate is reset for every row\n px = 100;\n }\n return pixels;\n}", "function caeserCipher(str, shift) {\n const alphabetArr = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n let res = \"\";\n for(let i =0; i < str.length; i++){\n const char = str[i];\n const idx = alphabetArr.indexOf(char);\n //console.log(idx)\n if(idx === -1 ){\n res += char;\n continue;\n }\n const encodedIdx = (idx + shift) %26;\n console.log(encodedIdx)\n res += alphabetArr[encodedIdx]\n }\n return res;\n}", "function encryption(string) {\n var res=\"\";\n var row = Math.floor(Math.sqrt(string.length));\n var column = Math.ceil(Math.sqrt(string.length));\n if(row * column < string.length) row = column;\n for(var i = 0; i < column; i++){\n for(var j = i; j < string.length; j = j + column ){\n res+=string.charAt(j);\n }\n res+=\" \";\n }\n return res;\n}", "function caesarCipherEncryptor(string, key) {\n // Write your code here.\n // we have to mutate this array we created, to work w edge case, where the ends move to the front. \n // the search ? // charAt(), IndexAt() or we can use a hash table \n const shiftedAlphabet = shiftAlphabet(key);\n let alphabet = 'abcdefghijklnmopqrstuvwxyz'.split('');\n let returnString = []; //space\n // O(n) \n for (let i = 0; i < string.length; i++) {\n // indexof O(N) if it is, we have to use a hash table in Javascript O(n) of constant 26\n let letterIndex = alphabet.indexOf(string[i]); \n returnString.push(shiftedAlphabet[letterIndex]) \n }\n return returnString.join('')\n }", "function getMatrix(charX, charY, img) {\n\n var canvas = document.createElement('canvas');\n var ctx = canvas.getContext('2d');\n var width = canvas.width = img.naturalWidth;\n var height = canvas.height = img.naturalHeight;\n ctx.drawImage(img, 0, 0);\n\n /* calculate the height and width of the ASCII art */\n var cols = Math.floor(width/charX);\n var rows = Math.floor(height/charY);\n\n /* create an empyty matrix to store averge pixel values */\n var matrix = new Array(rows);\n for (var i = 0; i < rows; i++) {\n matrix[i] = new Array(cols);\n }\n\n /* this gets a 1-dimensional array of pixel values for the whole image */\n var imageData = ctx.getImageData(0, 0 , img.naturalWidth, img.naturalHeight);\n\n /* for every slot in the matrix, put the average pixel value from the\n * relevent section of the original image. */\n for (var col = 0; col < cols; col++) {\n for (var row = 0; row < rows; row++) {\n var rgba = getAverageColor(col * charX, row * charY, charX, charY, imageData);\n matrix[row][col] = rgba;\n }\n }\n\n return matrix;\n}", "function getImage(city) {\n\n let lowerCity = city.replace(/\\s/g, '').toLowerCase();\n return \"images/\" + lowerCity + \".jpg\";\n\n}", "function getCharImageData (char, options) {\n\tif (!options) options = {}\n\tvar family = options.family || 'sans-serif'\n\tvar w = canvas.width, h = canvas.height\n\n\tvar size = options.width || options.height || options.size\n\tif (size && size != w) {\n\t\tw = h = canvas.width = canvas.height = size\n\t}\n\n\tvar fs = options.fontSize || w/2\n\n\tctx.fillStyle = '#000'\n\tctx.fillRect(0, 0, w, h)\n\n\tctx.font = fs + 'px ' + family\n\tctx.textBaseline = 'middle'\n\tctx.textAlign = 'center'\n\tctx.fillStyle = 'white'\n\tctx.fillText(char, w/2, h/2)\n\n\treturn ctx.getImageData(0, 0, w, h)\n}", "function caeserCipherEncryptor(str, key) {\n // intitalize an array to contain solution\n const newLetters = []\n // if the key is a big number (ie 54), we want the remainder\n // otherwise we want the number is smaller, it will be the remainder so all is well\n const newKey = key % 26\n // loop thru our str\n for (const letter of str) {\n // add the ciphered letter to result array\n newLetters.push(getNewLetter(letter, newKey))\n }\n //return the ciphered letters\n return newLetters.join('')\n}", "function nextImg(){\n\tif(actualString !== ''){\n\t\t//Getting the number of the image in the sequence and going to the next one if possible\n\t\tvar temp = Number(actualString.charAt(actualString.length - 1) ) + 1;\n\t\tvar ending;\n\t\tvar word = actualString.substr(0, actualString.length - 1);\n\n\t\t//Howd, hoed, hide, hayed have 4 images, the rest have 3\n\t\tif(word === 'howd' || word === 'hoed' || word == 'hide' || word == 'hayed')\n\t\t\tending = 4;\n\t\telse ending = 3;\n\n\t\tif(temp <= ending){\n\t\t\tvar next = word + temp;\n\t\t\timgChange(next);\n\t\t}\n\t}\n}", "function getDogImage(str) {\n \n fetch(`https://dog.ceo/api/breed/${str}/images`)\n .then(response => {\n if (response.ok) {\n return response.json();\n }\n throw new Error(response.statusText);\n })\n .then(responseJson => {\n\n console.log('Valid breed');\n\n let randomIndex = Math.floor(Math.random() * (responseJson.message.length-1));\n makeImageString(responseJson.message[randomIndex]);\n \n\n // console.log(htmlStr.newStr);\n // $('.images').html(htmlStr.newStr);\n\n });\n // console.log(htmlStr.newStr);\n // render(htmlStr.newStr);\n}", "function decipher(cifrado){\n\n alert (\"SORPRENDENTE: \" + cifrado);\n\n\n var descifrado =\"\";\n\n\n for(var j=0; j<cifrado.length; j++) { //el for recorrera las letras del texto a descifrar//\n\n var ubicacionDescifrado = (cifrado.charCodeAt(j) + 65 - 33) % 26 + 65;\n var palabraDescifrada= String.fromCharCode(ubicacionDescifrado);\n\n descifrado+=palabraDescifrada; //acumular las letras descifradas//\n}\n\nreturn descifrado;\n\n\n}", "function Populate_letter_container(){\r\n //remove old letters\r\n $('.individual_letter_container').remove();\r\n $('.answer_letter').remove();\r\n\r\n //create new letters\r\n for(var i=0; i<9; i++){\r\n var letter = String.fromCharCode(i + 97);\r\n $('#letters_row1').append('<div class=\"individual_letter_container\" id=\"'+ letter + '\"></div>');\r\n $('#' + letter).css(\"background\", \"url('pictures/\" + letter + \".png')\");\r\n $('#' + letter).css(\"left\", i * 60);\r\n }\r\n for(var i=9; i<20; i++){\r\n var letter = String.fromCharCode(i + 97);\r\n $('#letters_row2').append('<div class=\"individual_letter_container\" id=\"'+ letter + '\"></div>');\r\n $('#' + letter).css(\"background\", \"url('pictures/\" + letter + \".png')\");\r\n $('#' + letter).css(\"left\", (i - 9) * 60);\r\n }\r\n for(var i=20; i<29; i++){\r\n var letter;\r\n if (i == 26)\r\n letter = '1';\r\n else if (i == 27)\r\n letter = '2';\r\n else if (i == 28)\r\n letter = '3';\r\n else\r\n letter = String.fromCharCode(i + 97);\r\n $('#letters_row3').append('<div class=\"individual_letter_container\" id=\"'+ letter + '\"></div>');\r\n $('#' + letter).css(\"background\", \"url('pictures/\" + letter + \".png')\");\r\n $('#' + letter).css(\"left\", (i - 20) * 60);\r\n }\r\n\r\n $(\".individual_letter_container\").width(IMAGE_WIDTH);\r\n $(\".individual_letter_container\").height(IMAGE_HEIGHT);\r\n}", "function login_cipher(enctext,N)\r\n{\r\n\t//\r\n\tvar hidden = ((g_old_random_N & 0x00FFFFFF) + (g_random_N & 0x00FFFFFF)) & 0x00FFFFFF;\t// variable line\r\n\t//\t\r\n\tvar i = 0;\t\r\n\tvar dest = \"\";\r\n\t\r\n\tvar R = hidden;\r\n\t\r\n\twhile ( i < N ) {\r\n\t\tvar c = enctext.charAt(i);\r\n\t\tvar cc = enctext.charCodeAt(i);\r\n\t\tvar mc = (R & 0xFF);\r\n\t\r\n\t\tR = (R >> 8) & 0x00FFFFFF;\r\n\t\tif ( R == 0 ) {\r\n\t\t\thidden *= g_localprime;\r\n\t\t\thidden = ( hidden & 0x00FFFFFF );\r\n\t\t\tR = hidden;\r\n\t\t}\r\n\t\t//\r\n\t\t//\r\n\t\tcc = mc ^ cc;\r\n\t\t\r\n\t\tdest += cc.toString() + '_';\r\n\t\t//\r\n\t\ti++;\r\n\t\t//\r\n\t}\r\n\t\r\n\treturn(dest);\r\n}", "function emojify(name) {\n return `<img src=\"emojis/` + name + `.png\">`;\n}", "function catGenerator(){\n var img = document.createElement('img');\n var div = document.getElementById('flex-img');\n img.src=\"emoji.png\";\n \n img.setAttribute('id' , 'image')\n div.appendChild(img);\n}", "function CaesarCipher(str,num) { \n var littleAlpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];\n var bigAlpha = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];\n var result = '';\n var parts = str.split('');\n var ourIndex = 0;\n for (var i = 0; i < parts.length; i++){\n if (parts[i] >= 'a' && parts[i] <= 'z'){\n ourIndex = littleAlpha.indexOf(parts[i]);\n result += littleAlpha[ourIndex + num];\n } else if (parts[i] >= 'A' && parts[i] <= 'Z'){\n ourIndex = bigAlpha.indexOf(parts[i]);\n result += bigAlpha[ourIndex + num];\n } else {\n result += parts[i];\n }\n }\n return result;\n}", "function encrypt(){\n var str = \"AEGIOSZHOLAMUNDOaegiosz\";\nconsole.log(str);\nvar encrypted = {\n A:\"4\",\n E:\"3\",\n G:\"6\",\n I:\"1\",\n O:\"0\",\n S:\"5\",\n Z:\"2\",\n a:\"4\",\n e:\"3\",\n g:\"6\",\n i:\"1\",\n o:\"0\",\n s:\"5\",\n z:\"2\"\n \n};\nstr = str.replace(/A|4|E|3|G|6|I|1|O|0|S|5|Z|2|a|4|e|3|g|6|i|1|o|0|s|5|z|2/gi, function(matched){\n return encrypted[matched];\n});\nconsole.log(str);\n}", "function buildImage (species) {\n return species.toLowerCase() + '.png'\n}", "function decipher(string, offset) {\n let deCoded = '';\n for (let i = 0; i < string.length; i++) {\n let letter = string[i];\n let charCode = string.charCodeAt(i);\n if (charCode >= 65 && charCode <= 90) {\n letter = String.fromCharCode(((charCode - 65 + offset) % 26 + 65));\n } else if (charCode >= 97 && charCode <= 122) {\n letter = String.fromCharCode(((charCode - 97 + offset) % 26) + 97);\n }\n deCoded += letter;\n }\n return deCoded;\n}", "function rotationalCipher(str, key) {\n // Write your code here\n let cipher = '';\n\n //decipher each letter\n for (let i = 0; i < str.length; i++) {\n\n if (isNumeric(str[i])) {\n cipher += String.fromCharCode(((str.charCodeAt(i) + key - 48) % 10 + 48));\n } else if (isSpecialCharacter(str[i])) {\n cipher += str[i]\n }\n //if letter is uppercase then add uppercase letters\n else if (isUpperCase(str[i])) {\n cipher += String.fromCharCode((str.charCodeAt(i) + key - 65) % 26 + 65);\n } else {\n //else add lowercase letters\n cipher += String.fromCharCode((str.charCodeAt(i) + key - 97) % 26 + 97);\n }\n }\n\n return cipher;\n\n //check if letter is uppercase\n function isUpperCase(str) {\n return str === str.toUpperCase();\n }\n\n function isSpecialCharacter(str) {\n return str.match(/\\W|_/g);\n }\n\n function isNumeric(str) {\n return str.match(/^\\d+$/)\n }\n}", "function getImage(map, id) {\n var alias = \"alias:\";\n var image = map[id];\n while(image != null) {\n if(!image.startsWith(alias)) {\n var img = document.createElement(\"img\");\n img.src = image;\n img.alt = id;\n img.title = id;\n img.width = 25;\n return img.outerHTML;\n }\n id = image.replace(alias, \"\")\n image = map[id];\n }\n\n return null;\n}", "function getImage(imgName, index) {\n\t\t\n\t\t// uncapitalize first letter of each string in the array\n\t\tvar noSpace = imgName,\n\t\t firstLetter = noSpace.charAt(0);\n\t\t noSpace = firstLetter.toLowerCase() + noSpace.substring(1,noSpace.length);\n\t\t\n\t\t// Get image file names by returning the substring from index 0 to the first space\n\t\timgName = noSpace;\n\t\t\n\t\tvar endMark = imgName.indexOf(\" \");\n\t\t\n\t\tif (endMark === -1) {\n\t\t\timgName = imgName.substring(0,imgName.length);\n\t\t}\n\t\telse {\n\t\t\timgName = imgName.substring(0, endMark);\n\t\t};\n\t\n\t\t// creates the img elements\n\t\t$(\"<img src='images/\" + imgName + \".png' class='dataImage' alt='routine icon'/>\").prependTo(\"#heading\" + index);\n\t\t\n\t}", "function encipherPair(str) {\n if (str.length != 2) return false;\n var pos1 = getCharPosition(str.charAt(0));\n var pos2 = getCharPosition(str.charAt(1));\n var char1 = \"\";\n\n // Same Column - Increment 1 row, wrap around to top\n if (pos1.col == pos2.col) {\n pos1.row++;\n pos2.row++;\n if (pos1.row > cipher.maxRow - 1) pos1.row = 0;\n if (pos2.row > cipher.maxRow - 1) pos2.row = 0;\n char1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n } else if (pos1.row == pos2.row) {\n // Same Row - Increment 1 column, wrap around to left\n pos1.col++;\n pos2.col++;\n if (pos1.col > cipher.maxCol - 1) pos1.col = 0;\n if (pos2.col > cipher.maxCol - 1) pos2.col = 0;\n char1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n } else {\n // Box rule, use the opposing corners\n var col1 = pos1.col;\n var col2 = pos2.col;\n pos1.col = col2;\n pos2.col = col1;\n char1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n }\n return char1;\n}", "function toCaesar(str, rotation){\n while(rotation >= 26) rotation -= 26;\n \n var newString = \"\";\n \n for(var i = 0; i < str.length; i++){\n var code = str.charCodeAt(i);\n \n if(code >= 65 && code <= 90){\n code += rotation;\n if(code > 90) code -= 26;\n }else if(code >= 97 && code <= 122){\n code += rotation;\n if(code > 122) code -= 26;\n }else{\n //number or something\n }\n \n newString += String.fromCharCode(code);\n }\n return newString;\n}", "function createImgElement(text) {\n const imgElement = document.createElement('img');\n imgElement.src = text;\n return imgElement;\n}", "function decode(str) {\n //object representing the cipher\n const codeObj = {\n 'a': 1,\n 'b': 2,\n 'c': 3,\n 'd': 4\n };\n //create a vairable that is the first letter \n let decodedIndex = codeObj[str.charAt(0)];\n return str.charAt(decodedIndex);\n}", "function Font(image, glyph_width, glyph_height) {\n\tthis.table = \"0123456789/()&!?ABCDEFGHIJKLMNOPQRSTUVWXYZ.,;:'\\\"abcdefghijklmnopqrstuvwxyz~—<> \";\n\tthis.table_columns = 16;\n\tthis.image = image;\n\tthis.glyph_width = glyph_width;\n\tthis.glyph_height = glyph_height;\n\tthis.spacing = 0;\n\t\n\tthis.lookup_character_index = function(character) {\n\t\tfor (var i = 0, n = this.table.length; i < n; ++i) {\n\t\t\tif (character == this.table.charAt(i)) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n}", "function addTextToImg(src,text){\n\t\tvar canvas = document.getElementById('matText');\n\t\tvar ctx = canvas.getContext('2d');\n\t\tvar imageObj = new Image();\n\t\timageObj.onload = function() {\n\t\t\tvar marginImg = (canvas.width- imageObj.width)/2\n\t\t\tctx.drawImage(imageObj, marginImg,0);\n\t\t\tctx.strokeStyle = 'rgb(188,188,188)';\n\t\t\tctx.rect(0, 0, canvas.width, canvas.height);\n\t\t\tctx.stroke();\t\t\n\t\t};\n\t\timageObj.src = src;\t \t\n\t\tctx.font = '12px \"PT Serif\"';\t\t\n\t\tvar marginText = (ctx.measureText(text).width<canvas.width)?(canvas.width-ctx.measureText(text).width)/2:0;\n\t\tctx.fillText(text,marginText, 100,canvas.width);\t\t\n\t\tvar url = ctx.canvas.toDataURL();\n\t\tctx.clearRect(0,0,canvas.width,canvas.height);\n\t\treturn url;\n\t}", "function caesarCipher(string, offset, length) {\n let result = ''\n for (const character of string) {\n const code = character.codePointAt(0)\n if (code > 64 && code < 91 || code > 96 && code < 123) {\n let newCode = code + offset\n while (newCode < 65 && code < 91 || newCode < 97 && code > 96) {\n newCode += 26\n }\n while (newCode > 90 && code < 91 || newCode > 122 && code > 96) {\n newCode -= 26\n }\n result += String.fromCharCode(newCode)\n } else {\n result += character\n }\n }\n return result\n}", "function getImage(tipo,rarita) {\n\n return \"img/\"+tipo.toString()+rarita.toString()+\".jpg\";\n}", "function findLetter(note){\n\n letter = '';\n\n if(note.substring(0,2) == 'C5'){\n letter = 'h';\n } else if(note.substring(0,1) == 'C'){\n letter = 'a';\n } else if(note.substring(0,1) == 'D'){\n letter = 'b';\n } else if(note.substring(0,1) == 'E'){\n letter = 'c';\n } else if(note.substring(0,1) == 'F'){\n letter = 'd';\n } else if(note.substring(0,1) == 'G'){\n letter = 'e';\n } else if(note.substring(0,1) == 'A'){\n letter = 'f';\n } else if(note.substring(0,1) == 'B'){\n letter = 'g';\n }\n\n return letter;\n\n}", "function VigenereCipher(key, abc) {\n let _key = [...key].map(char =>\n abc.indexOf(char))\n\n let _nextKey = index =>\n _key[index % _key.length]\n\n let checkAlphabet = (x, f) => \n abc.indexOf(x) >= 0 ? f(x) : x\n\n this.encode = str =>\n str.replace(/./g, (x, i) =>\n checkAlphabet(x, x => abc[(abc.indexOf(x) + _nextKey(i)) % abc.length]))\n\n this.decode = str =>\n str.replace(/./g, (x, i) =>\n checkAlphabet(x, x => abc[(abc.indexOf(x) - _nextKey(i) + abc.length) % abc.length]))\n}", "function text2base64(text) {\n var j = 0;\n var i = 0;\n var base64 = new Array();\n var base64string = \"\";\n var base64key = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n var text0, text1, text2;\n\n////////////////////////////////////////////////////////////////////////////////////////////////////\n// Step thru the input text string 3 characters per loop, creating 4 output characters per loop //\n////////////////////////////////////////////////////////////////////////////////////////////////////\n\n for (i=0; i < text.length; )\n {\n text0 = text.charCodeAt(i);\n text1 = text.charCodeAt(i+1);\n text2 = text.charCodeAt(i+2);\n\n base64[j] = base64key.charCodeAt((text0 & 252) >> 2);\n if ((i+1)<text.length) // i+1 is still part of string\n {\n base64[j+1] = base64key.charCodeAt(((text0 & 3) << 4)|((text1 & 240) >> 4));\n if ((i+2)<text.length) // i+2 is still part of string\n {\n base64[j+2] = base64key.charCodeAt(((text1 & 15) << 2) | ((text2 & 192) >> 6));\n base64[j+3] = base64key.charCodeAt((text2 & 63));\n }\n else\n {\n base64[j+2] = base64key.charCodeAt(((text1 & 15) << 2));\n base64[j+3] = 61;\n }\n }\n else\n {\n base64[j+1] = base64key.charCodeAt(((text0 & 3) << 4));\n base64[j+2] = 61;\n base64[j+3] = 61;\n }\n i=i+3;\n j=j+4;\n }\n \n ////////////////////////////////////////////\n // Create output string from byte array //\n ////////////////////////////////////////////\n\n for (i=0; i<base64.length; i++)\n {\n base64string += String.fromCharCode(base64[i]);\n }\n\n return base64string;\n}", "function returnImgString (person) {\n return 'img/'+returnEmotion(person.scores)+'.png';\n }", "function caesarCipher(s, k) {\n // 한바퀴를 더 돌 경우( a+25=>z ) 모듈러 연산으로 무시\n k = k % 26;\n return s.split(\"\").map((char) => {\n let ascii = char.charCodeAt(0);\n if (ascii >= 65 && ascii <= 90) {\n let offset = 90 - k + 1;\n if (ascii / offset >= 1) {\n return String.fromCharCode(ascii % offset + 65);\n } else {\n return String.fromCharCode(ascii + k);\n }\n } else if (ascii >= 97 && ascii <= 122) {\n let offset = 122 - k + 1;\n if (ascii / offset >= 1) {\n return String.fromCharCode(ascii % offset + 97);\n } else {\n return String.fromCharCode(ascii + k);\n }\n } else {\n return char;\n }\n }).join(\"\");\n}", "function replaceImages(text){\n var emoticons = {\n 'smile' : ':)',\n 'neutral' : ':|',\n 'blush' : ':-)',\n 'confused' : ':-$',\n 'angry' : ':-@',\n 'like' : '(y)',\n };\n \n return text.replace(/[smile neutral blush confused angry like]+/g, function (match) {\n return emoticons[match] != 'undefined' ? emoticons[match] : match;\n });\n }", "function Img(name, src, answer) {\r\n this.name = name;\r\n this.src = src;\r\n this.answer = answer;\r\n\r\n // All characters push themselves into the array\r\n hiraArray.push(this);\r\n}", "function encipherPair(str) {\n\t\tif (str.length != 2) return false;\n\t\tvar pos1 = getCharPosition(str.charAt(0));\n\t\tvar pos2 = getCharPosition(str.charAt(1));\n\t\tvar char1 = \"\";\n\t\t\n\t\t// Same Column - Increment 1 row, wrap around to top\n\t\tif (pos1.col == pos2.col) {\n\t\t\tpos1.row++;\n\t\t\tpos2.row++;\n\t\t\tif (pos1.row > 4) pos1.row = 0;\n\t\t\tif (pos2.row > 4) pos2.row = 0;\n\t\t\tchar1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n\t\t\t} else if (pos1.row == pos2.row) { // Same Row - Increment 1 column, wrap around to left\n\t\t\tpos1.col++;\n\t\t\tpos2.col++;\n\t\t\tif (pos1.col > 4) pos1.col = 0;\n\t\t\tif (pos2.col > 4) pos2.col = 0;\n\t\t\tchar1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n\t\t\t} else { // Box rule, use the opposing corners\n\t\t\tvar col1 = pos1.col;\n\t\t\tvar col2 = pos2.col;\n\t\t\tpos1.col = col2;\n\t\t\tpos2.col = col1;\n\t\t\tchar1 = getCharFromPosition(pos1) + getCharFromPosition(pos2);\n\t\t}\n\t\t\n\t\treturn char1;\n\t}", "function ccipher(d) {\n var encMsg = '';\n var shift = 3; //shift alpha 3 letters over\n for (var i = 0; i < d.length; i++) {\n var code = d.charCodeAt(i);\n if ((code >= 65) && (code <= 90)) {\n //uppercase\n encMsg += String.fromCharCode((mod((code - 65 + shift), 26) + 65));\n } else if ((code >= 97) && (code <= 122)) {\n encMsg += String.fromCharCode((mod((code - 97 + shift), 26) + 97));\n } else {\n encMsg += String.fromCharCode(code);\n }\n }\n return encMsg;\n}", "function asciifyImage( canvasRenderer, oAscii ) {\n\n\t\toCtx.clearRect( 0, 0, iWidth, iHeight );\n\t\toCtx.drawImage( oCanvasImg, 0, 0, iWidth, iHeight );\n\t\tvar oImgData = oCtx.getImageData( 0, 0, iWidth, iHeight ).data;\n\n\t\t// Coloring loop starts now\n\t\tvar strChars = \"\";\n\n\t\t// console.time('rendering');\n\n\t\tfor ( var y = 0; y < iHeight; y += 2 ) {\n\n\t\t\tfor ( var x = 0; x < iWidth; x ++ ) {\n\n\t\t\t\tvar iOffset = ( y * iWidth + x ) * 4;\n\n\t\t\t\tvar iRed = oImgData[ iOffset ];\n\t\t\t\tvar iGreen = oImgData[ iOffset + 1 ];\n\t\t\t\tvar iBlue = oImgData[ iOffset + 2 ];\n\t\t\t\tvar iAlpha = oImgData[ iOffset + 3 ];\n\t\t\t\tvar iCharIdx;\n\n\t\t\t\tvar fBrightness;\n\n\t\t\t\tfBrightness = ( 0.3 * iRed + 0.59 * iGreen + 0.11 * iBlue ) / 255;\n\t\t\t\t// fBrightness = (0.3*iRed + 0.5*iGreen + 0.3*iBlue) / 255;\n\n\t\t\t\tif ( iAlpha == 0 ) {\n\n\t\t\t\t\t// should calculate alpha instead, but quick hack :)\n\t\t\t\t\t//fBrightness *= (iAlpha / 255);\n\t\t\t\t\tfBrightness = 1;\n\n\t\t\t\t}\n\n\t\t\t\tiCharIdx = Math.floor( ( 1 - fBrightness ) * ( aCharList.length - 1 ) );\n\n\t\t\t\tif ( bInvert ) {\n\n\t\t\t\t\tiCharIdx = aCharList.length - iCharIdx - 1;\n\n\t\t\t\t}\n\n\t\t\t\t// good for debugging\n\t\t\t\t//fBrightness = Math.floor(fBrightness * 10);\n\t\t\t\t//strThisChar = fBrightness;\n\n\t\t\t\tvar strThisChar = aCharList[ iCharIdx ];\n\n\t\t\t\tif ( strThisChar === undefined || strThisChar == \" \" )\n\t\t\t\t\t{ strThisChar = \"&nbsp;\"; }\n\n\t\t\t\tif ( bColor ) {\n\n\t\t\t\t\tstrChars += \"<span style='\"\n\t\t\t\t\t\t+ \"color:rgb(\" + iRed + \",\" + iGreen + \",\" + iBlue + \");\"\n\t\t\t\t\t\t+ ( bBlock ? \"background-color:rgb(\" + iRed + \",\" + iGreen + \",\" + iBlue + \");\" : \"\" )\n\t\t\t\t\t\t+ ( bAlpha ? \"opacity:\" + ( iAlpha / 255 ) + \";\" : \"\" )\n\t\t\t\t\t\t+ \"'>\" + strThisChar + \"</span>\";\n\n\t\t\t\t} else {\n\n\t\t\t\t\tstrChars += strThisChar;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tstrChars += \"<br/>\";\n\n\t\t}\n\n\t\toAscii.innerHTML = \"<tr><td>\" + strChars + \"</td></tr>\";\n\n\t\t// console.timeEnd('rendering');\n\n\t\t// return oAscii;\n\n\t}", "function encrypt(string) {\n /*asosiy kirill ga o'girish algoritmi */\n for (var i = 0; i < string.length; i++) {\n for (var j = 0; j < alphaLatin.length; j++) {\n\n\n if (string[i] == alphaLatin[j]) {\n CyrillicTranslated += alphaRus[j]; break;\n }\n /*simvollarni va shuningdek o'zi kirill alifbosidagi harflarni ham o'zgartirmaydi: */\n else if ((string.charCodeAt(i) >= 9 && string.charCodeAt(i) <= 11) || (string.charCodeAt(i) > 32 && string.charCodeAt(i) < 39) || (string.charCodeAt(i) > 39 && string.charCodeAt(i) <= 64) || (string.charCodeAt(i) >= 91 && string.charCodeAt(i) < 96) || (string.charCodeAt(i) >= 123 && string.charCodeAt(i) <= 1300)) {\n CyrillicTranslated += string[i]; break;\n // alert(\"son simvol topdi\"); \n }\n\n else if (string.charCodeAt(i) === 32) { /* probelni necha bo'lsa shuncha qo'shadi :)*/\n CyrillicTranslated += \" \"; break;\n }\n }\n }\n // console.log(CyrillicTranslated)\n }", "function getgImage(number) {\n switch (number) {\n case \"0\":\n return '<img src=\"assets/images/card_Ampresand.jpg\">';\n case \"1\":\n return '<img src=\"assets/images/card_Apostrope.jpg\">';\n case \"2\":\n return '<img src=\"assets/images/card_At.jpg\">';\n case \"3\":\n return '<img src=\"assets/images/card_Colon.jpg\">';\n case \"4\":\n return '<img src=\"assets/images/card_Comma.jpg\">';\n case \"5\":\n return '<img src=\"assets/images/card_Dollar.jpg\">';\n case \"6\":\n return '<img src=\"assets/images/card_Equals.jpg\">';\n case \"7\":\n return '<img src=\"assets/images/card_Exclamation.jpg\">';\n case \"8\":\n return '<img src=\"assets/images/card_Hyphen.jpg\">';\n case \"9\":\n return '<img src=\"assets/images/card_ParanthesisClose.jpg\">';\n case \"10\":\n return '<img src=\"assets/images/card_ParanthesisOpen.jpg\">';\n case \"11\":\n return '<img src=\"assets/images/card_Period.jpg\">';\n case \"12\":\n return '<img src=\"assets/images/card_Plus.jpg\">';\n case \"13\":\n return '<img src=\"assets/images/card_Question.jpg\">';\n case \"14\":\n return '<img src=\"assets/images/card_Quotation.jpg\">';\n case \"15\":\n return '<img src=\"assets/images/card_Slash.jpg\">';\n case \"16\":\n return '<img src=\"assets/images/card_Underscore.jpg\">';\n default:\n return '<img src=\"assets/images/card_back.jpg\">';\n }\n}", "function injectEmojiImages(inputText, validEmojis, emojisUsed) {\n var resultStr = \"\";\n var matches = inputText.matchAll(emojiMatch);\n var currentIndexInInput = 0;\n\n var match;\n while (!(match = matches.next()).done) {\n var reInjectText = match.value[0];\n if (validEmojis.indexOf(match.value[1]) != -1) {\n const emojiName = match.value[1];\n reInjectText = createImgTag(emojiName);\n emojisUsed[emojiName] = (emojisUsed[emojiName] === undefined ? 0 : emojisUsed[emojiName]) + 1;\n }\n\n resultStr += inputText.substring(currentIndexInInput, match.value.index);\n resultStr += reInjectText;\n currentIndexInInput = match.value.index + match.value[0].length;\n }\n resultStr += inputText.substring(currentIndexInInput, inputText.length);\n if (!resultStr.endsWith('&nbsp;')) {\n //a characer of some sort is requred to get emoji at the end of a message to display correctly\n // don't ask me why\n // also don't ask me why it's not needed anymore\n // resultStr += '&nbsp;';\n }\n return resultStr;\n }", "function caesarCipher(myString) {\nvar\n}", "function caeserCipherEncryptor(str, key) {\n\t// intitalize an array to contain solution\n\tconst newLetters = []\n\t// mod ur current key by 26, cause theres ony 26 letters\n const newKey = key % 26\n //make the alphaet\n const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')\n\t// loop thru our str\n\tfor (const letter of str) {\n\t\t// add the ciphered letter to result array\n\t\tnewLetters.push(getNewLetterB(letter, newKey, alphabet))\n\t}\n\n\t//return the ciphered letters\n\treturn newLetters.join('')\n}", "function caesarCipher(str, key) {\n if (key > 26)\n key = key % 26;\n return str.toLocaleLowerCase().split('').map(function (val) {\n return String.fromCharCode((val.charCodeAt(0) + key) > 122 ? val.charCodeAt(0) + key - 26 :\n val.charCodeAt(0) + key); // 122 is 'z' so if charCode more than 122 we need to circle it by subtracting 26\n }).join('');\n}", "function atbashCipher(text) {\n let output = \"\";\n let alphabet = \"abcdefghijklmnopqrstuvwxyz\"\n for (let i = 0; i < text.length; i++) {\n output += alphabet[26 - alphabet.indexOf(text[i]) - 1];\n }\n return output;\n}", "function c_case(v,h) {\r\n\tvar imag=document.createElement(\"img\");\r\n\timag.src=img_src(\"case\");\r\n\timag.className = \"case\";\r\n\timag.style.top = v+\"px\"; imag.style.left = h+\"px\";\r\n\timag.alt=\"\";\r\n\treturn imag;\r\n}", "function get_preview(source) {\r\n var position = (source.length - 5) // appends the _HD suffix at the -4th index : before the .png\r\n return source.substring(0, position) + \"_HD\" + source.substring(position);\r\n}", "getImage(){\n return '';//This might change later, we will see what I want this to be\n }", "function displayImage(){\n\t\tvar images = { 3:\"assets/images/gym.png\", 5:\"assets/images/kanto.jpg\", 6:\"assets/images/badge.png\", 7:\"assets/images/pikachu.png\", 8:\"assets/images/squirtle.png\"};\n\t\t$(\"#imagePlace\").html(\"<img src=\"+images[randomWord.length]+\" style=\\\"height:225px;\\\">\");\n\t}", "showMatchedLetter(letter){\r\n $(letter).addClass('show');\r\n // display the char of the corresponding letters check if game is won\r\n }", "function cipher(phrase){ // Con esta funcion cifraremos la frase ingresada por el usuario\n var str= \"\";// Aqui se guardara la frase cifrada\n for (var i = 0; i < phrase.length; i++) { //Iterar el string para poder obtener el numero de la letra dentro del codigo ascii para posteriormente poder recorrernos 33 espacios.\n var codeNumber = phrase.charCodeAt(i); // charCodeAt nos devuelve un número indicando el valor Unicode del carácter en el índice proporcionado el cual estaremos iterando (i).\n var letterMay = (codeNumber - 65 + 33) % 26 + 65;\n var letterMin = (codeNumber - 97 + 33) % 26 + 97;\n\n if (codeNumber >= 65 && codeNumber <= 90) { //Condicionamos y seccionamos, si codeNumber es mayor o igual a la posicion 65 o menor o igual que 90 en el codigo ASCII seran letras Mayusculas.\n str += String.fromCharCode(letterMay);\n\n } else {\n (codeNumber >= 97 && codeNumber <= 122) //Condicionamos y seccionamos, si codeNumber es mayor o igual a la posicion 97 o menor o igual que 122 en el codigo ASCII seran letras Minisculas.\n str += String.fromCharCode(letterMin);\n }\n }\n\n console.log(str); // str Nos muestra la frase cifrada\n document.write(\"Tu frase cifrada es \" + str); //Imprimimos en la pantalla la frase cifrada para el usuario que guardamos en la variable str.\n}", "function getIndexes(key) {\n var index = randomLowerCase.indexOf(key);\n while (index != -1) {\n wordDashes[index] = randomWord[index];\n index = randomLowerCase.indexOf(key, index + 1);\n \n }\n \n// Function to show gif when user wins or loses \n}", "function WithNameAloneAsString(){\n return lib.getKeywordsForImage('iphone.jpeg').then(function(data){\n console.log('Passed with name alone as string : ' + data);\n }).fail(function(){\n return 'with name alone as string : failed';\n });\n}", "function ConvertSSLImages(c)\n{\n\treplaceImage = 'src=\\\"http://' + URL;\n\tc = c.replace(re4,replaceImage);\n\treturn c;\n}", "function ceasarCipher3(alphabet) {\n for (var i = 0; i < alphabet.length; i++){\n console.log(alphabet[i].charCodeAt());\n }\n}", "function AtbashCipher(txt){\n \n inputText = document.getElementById(\"input1\").value;\n outputText = \"\";\n \n //Checking if inputText is empty\n if(inputText.length==0)\n document.getElementById(\"input2\").value = \"\";\n \n for( i=0;i<inputText.length;i++)\n {\n // Checking if the character is in [a-z] or [A-Z] \n if( AtbashWheel[inputText[i]] !== undefined ) {\n res += AtbashWheel[inputText[i]]; \n }\n //Checking if character non alphabetic\n else {\n //No change, use the same character\n res += inputText[i];\n }\n document.getElementById(\"input2\").value = res;\n }\n}", "function chooseChars(string) {\n $(string).html(\"<h2>Pick your Character:</h2>\")\n for (var i = 0; i < characters.length; i++) {\n if(chosen === characters[i]){\n characters.splice(i,1);\n if(i > characters.length - 1)\n continue;\n }\n var newDiv = $(\"<button class='pictures buttonId'><img src=\"\n + characters[i].image + \" height='100'><div>\" +\n characters[i].health + \"</div></img></button>\");\n newDiv.data(\"data-object\", characters[i]);\n $(string).append(newDiv);\n }\n }", "static fromAscii(value) {\n let trytes = \"\";\n for (let i = 0; i < value.length; i++) {\n const asciiValue = value.charCodeAt(i);\n const firstValue = asciiValue % 27;\n const secondValue = (asciiValue - firstValue) / 27;\n trytes += TrytesHelper.ALPHABET[firstValue] + TrytesHelper.ALPHABET[secondValue];\n }\n return trytes;\n }", "function caesarCipherDecript(str) {\r\n \r\n const alphabetArr = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\r\n let resultrot13EncriptCaesarCypher = \"\";\r\n\r\n for (let i = 0; i < str.length; i++) {\r\n const char = str[i];\r\n const idx = alphabetArr.indexOf(char);\r\n\r\n // if it is not a letter, don`t shift it\r\n if (idx === -1) {\r\n resultrot13EncriptCaesarCypher += char;\r\n continue;\r\n }\r\n\r\n // only 26 letters in alphabet, if > 26 it wraps around\r\n var shift = 6;\r\n const encodedIdx = (idx + shift) % 26;\r\n resultrot13EncriptCaesarCypher += alphabetArr[encodedIdx];\r\n }\r\n //return res;\r\n document.getElementById(\"showresult\").value = resultrot13EncriptCaesarCypher;\r\n //console.log(res);\r\n}", "function getImageMeta(string, key){\n\t\t\n\t\tstring = string.split(separateData)[0];\n\t\t\n\t\tvar dimensions = string.substr(7).split(separateSize);\n\t\tvar color = string.substr(1, 6);\n\t\tvar monochrome = string[0] === monoPrefix;\n\t\t\n\t\tvar object = {\n\t\t\twidth: parseFloat(dimensions[0]),\n\t\t\theight: parseFloat(dimensions[1]),\n\t\t\tcolor: hexPrefix + color,\n\t\t\tblack: hexPrefix + hexToMonochrome(color),\n\t\t\tmonochrome: monochrome\n\t\t};\n\t\t\n\t\treturn typeof key === \"string\" ? object[key] : object;\n\t\t\n\t}", "function getImage(name) {\n const image = images[name];\n\n if (image.includes('https')) return image;\n\n return imageMap[image];\n }", "Decrypt(string){\n var str=string;\n var newstr=\"\";\n for(var i=0;i<string.length;i++){\n var n=str.charCodeAt(i);\n if((n>=65 && n<=90)){\n var res=String.fromCharCode(155-n);\n newstr=newstr.concat(res);\n }\n else if((n>=97 && n<=122)){\n var res=String.fromCharCode(219-n);\n newstr=newstr.concat(res);\n }\n else{\n newstr=newstr.concat(str[i]);\n }\n }\n return newstr;\n }", "function prevImg(){\n\tif(actualString !== ''){\n\t\t//Getting the number of the image in the sequence and going to the previous one if possible\n\t\tvar temp = Number(actualString.charAt(actualString.length - 1) ) - 1;\n\t\tvar word = actualString.substr(0, actualString.length - 1);\n\t\tif(temp > 0){\n\t\t\tvar prev = word + temp;\n\t\t\timgChange(prev);\n\t\t}\n\t}\n}" ]
[ "0.70061934", "0.6534171", "0.59344065", "0.5890802", "0.5837095", "0.5800241", "0.577855", "0.5760525", "0.57462704", "0.5721525", "0.56979626", "0.56428576", "0.55858254", "0.5577009", "0.5566507", "0.5536229", "0.5528588", "0.54420495", "0.5419105", "0.5412684", "0.5379764", "0.5369519", "0.5364916", "0.53465515", "0.53436923", "0.53414756", "0.5320571", "0.5314204", "0.5313088", "0.5308103", "0.53064746", "0.5298732", "0.52858436", "0.5276207", "0.5269366", "0.5261676", "0.52601445", "0.52582943", "0.5251595", "0.5245564", "0.52419895", "0.5227194", "0.52151716", "0.5212933", "0.52100027", "0.5202976", "0.5192118", "0.5190746", "0.51859003", "0.51540154", "0.5151699", "0.51494086", "0.5146255", "0.5139128", "0.51374894", "0.51371264", "0.5131423", "0.51098806", "0.5109302", "0.51081306", "0.51062334", "0.51008", "0.5099112", "0.50793076", "0.50743735", "0.5073195", "0.5072871", "0.50675714", "0.506593", "0.5063258", "0.5062916", "0.5061944", "0.5050886", "0.5044519", "0.5036996", "0.50319433", "0.5031753", "0.50275177", "0.5026303", "0.5021957", "0.50217175", "0.50188017", "0.5017103", "0.5007407", "0.50017697", "0.50007194", "0.5000101", "0.49961802", "0.49854994", "0.49748135", "0.49741682", "0.4958014", "0.49500015", "0.49485883", "0.49419105", "0.49415472", "0.4934503", "0.4912722", "0.4912443", "0.49090162" ]
0.7113889
0
get cipher character at position (r, c). translate out of bounds values to within bounds values.
function get(r, c) { r=getR(r); c=getC(c); return cipher[which][r].substring(c,c+1); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getCharFromPosition(pos) {\n var index = pos.row * 5;\n index = index + pos.col;\n return cipher.key.charAt(index);\n}", "function getCharPosition(c) {\n var index = cipher.key.indexOf(c);\n var row = Math.floor(index / 5);\n var col = index % 5;\n return {\n row: row,\n col: col,\n };\n}", "function getCharFromPosition(pos) {\n\t\tvar index = pos.row * 5;\n\t\tindex = index + pos.col;\n\t\treturn keyPhrase.charAt(index);\n\t}", "function indexOf(r, c) {\n return Base26.toBase26(c) + r.toString();\n }", "function getChar(c){\n return String.fromCodePoint(c);\n}", "function getChar(c){\n return String.fromCharCode(c)\n}", "function c(n){\r\n\treturn String.fromCharCode(n);\r\n}", "char () {\n\t\treturn this.code[ this.pos ];\n\t}", "function charToIndex (c) {\n return parseInt(c.toLowerCase().charCodeAt(0) - 97);\n }", "charAt(index) {return this.code[index];}", "function positionToChar(position) {\n var counter = 0;\n\n loop:\n for (var i = 1; i <= keyboardDimension[0]; i++) {\n for (var j = 1; j <= keyboardDimension[1]; j++) {\n if (!(i in invalidPositions) || !invalidPositions[i].some(xPosition => xPosition == j)) {\n counter++;\n }\n\n if (position[0] == i && position[1] == j) {\n //We are at the position that is given as the parameter, stop the N(2) loop\n // with the label\n break loop;\n }\n }\n }\n\n if (counter >= 10) {\n return String.fromCharCode(65 + (counter - 10));\n }\n\n return counter;\n}", "function getChar() {\n index++;\n c = expr.charAt(index);\n }", "function ctl(ch){return String.fromCharCode(ch.charCodeAt(0)-64);}", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position)\n }", "function at(position) {\n return value.charAt(position);\n }", "function ccipher(d) {\n var encMsg = '';\n var shift = 3; //shift alpha 3 letters over\n for (var i = 0; i < d.length; i++) {\n var code = d.charCodeAt(i);\n if ((code >= 65) && (code <= 90)) {\n //uppercase\n encMsg += String.fromCharCode((mod((code - 65 + shift), 26) + 65));\n } else if ((code >= 97) && (code <= 122)) {\n encMsg += String.fromCharCode((mod((code - 97 + shift), 26) + 97));\n } else {\n encMsg += String.fromCharCode(code);\n }\n }\n return encMsg;\n}", "function cipher(string, offset) {\n let code = '';\n for (let i = 0; i < string.length; i++) {\n let letter = string[i];\n let charCode = string.charCodeAt(i);\n if (charCode >= 65 && charCode <= 122) {\n letter = String.fromCharCode(((charCode - 65 + offset) % 26) + 65);\n } else if (charCode >= 97 && charCode <= 122) {\n letter = String.fromCharCode(((charCode - 97 + offset) % 26) + 97);\n }\n code += letter;\n }\n return code;\n}", "charValue(character){\n if(BadBoggle.isAVowel(character)) return 3;\n if(character === 'y') return -10;\n return -2;\n }", "function getChar(c) {\n let char = String.fromCharCode(c);\n // console.log(char);\n return char\n}", "function characPosit(character){\n\t\t//your code is here\n\t\tvar code = character.toLowerCase().charCodeAt(0)\n\t\treturn \"Position of alphabet: \" + (code - 96);\n\t}", "function getPuzzleValue(r, c) {\n\treturn puzzle[r][c];\n}", "function getLetter(index) {\n return String.fromCharCode(64 + index);\n}", "function indexToChar (i) {\n // 97 = a\n return String.fromCharCode(97 + i); \n }", "function getPosLetter(inpt,position)\r\n{\r\n\tvar len=inpt.length;\r\n\tif(position<=len)\r\n\t{\r\n\t\tfinalOutput=inpt.charAt(position-1);\r\n\t\treturn finalOutput;\r\n\t\t \r\n\t}\r\n\telse\r\n\t{\r\n\t\tdocument.write(\"Invalid Position!\");\r\n\t\treturn; \r\n\t}\r\n\t\r\n}", "function WGetItem(r, c)\n{\n if ((c >= this.cols) || (c < 0)) return \"\";\n if (this.rows == 0) return \"\";\n if ((r >= this.rows) || (r < 0)) return \"\";\n return this.arrdata[r * this.cols + c];\n}", "function byChar(cm, pos, dir) {\n return cm.findPosH(pos, dir, \"char\", true);\n }", "function getChar(keyNum) {\r\n return String.fromCharCode(keyNum);\r\n}", "function shift (c, n) {\n // 97: ASCII 'a'. offsets the caeaer cipher arithmetic.\n return String.fromCharCode(((ord(c) - 97 + n) % 26) + 97)\n}", "static completeWithChar(value, c, n, right = false) {\n var s = value.length;\n for (var i = 0; i < n - s; ++i) {\n if (right)\n value = value + c;\n else\n value = c + value;\n }\n return value;\n }", "function getchar(position){\n return $(position).text();\n}", "function charToHex(c) {\r\n var ZERO = 48;\r\n var NINE = ZERO + 9;\r\n var littleA = 97;\r\n var littleZ = littleA + 25;\r\n var bigA = 65;\r\n var bigZ = 65 + 25;\r\n var result;\r\n\r\n if (c >= ZERO && c <= NINE) {\r\n result = c - ZERO;\r\n } else if (c >= bigA && c <= bigZ) {\r\n result = 10 + c - bigA;\r\n } else if (c >= littleA && c <= littleZ) {\r\n result = 10 + c - littleA;\r\n } else {\r\n result = 0;\r\n }\r\n return result;\r\n}", "function getLetterFromAlphabet(position) {\n if (position == 0) {\n return \"\";\n }\n return String.fromCharCode(64 + position);\n}", "function indexToChar(i) {\n return String.fromCharCode(i+97).toUpperCase(); //97 in ASCII is 'a', so i=0 returns 'a', i=1 returns 'b', etc\n}", "function characPosit(character){\n\t\tvar alphabet=\"abcdefghijklmnopqrstuvwxyz\"\n\t\tvar position =eval(alphabet.indexOf(character))+1;\n\t\treturn \"Position of alphabet: \" + position;\n\t}", "function char_2_int(c)\n{\n switch (c) {\n case 'R': return 0;\n case 'G': return 1;\n case 'B': return 2;\n\n // shouldn't happen\n default:\n return 3;\n }\n}", "function getRandomChar(c) {\n var r = Math.random() * 16;//random number between 0 and 16\n if(d > 0){\n r = (d + r)%16 | 0;\n d = Math.floor(d/16);\n } else { r = (d2 + r)%16 | 0;\n d2 = Math.floor(d2/16);\n }\n return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);\n }", "function charToColor(c) {\n if (c === '.') return null;\n if (c === 'b') return 'black';\n if (c === 'w') return 'white';\n throw new Error(\"Failed to map char to piece.\");\n}", "function trC(coord){\n\treturn -95 + coord*10;\n}", "function isChar( i, r, c ) {\n return board[r][c] === word[i];\n }", "function _char(c) {\n if (!_CHARS[c]) {\n _CHARS[c] = '\\\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4);\n }\n return _CHARS[c];\n}", "function _char(c) {\n if (!_CHARS[c]) {\n _CHARS[c] = '\\\\u'+('0000'+(+(c.charCodeAt(0))).toString(16)).slice(-4);\n }\n return _CHARS[c];\n}", "function char_to_int(r){\n switch (r){\n case 'I': return 1;\n case 'V': return 5;\n case 'X': return 10;\n case 'L': return 50;\n case 'C': return 100;\n case 'D': return 500;\n case 'M': return 1000;\n default: return -1;\n }\n}", "function caesarCipher(string, offset, length) {\n let result = ''\n for (const character of string) {\n const code = character.codePointAt(0)\n if (code > 64 && code < 91 || code > 96 && code < 123) {\n let newCode = code + offset\n while (newCode < 65 && code < 91 || newCode < 97 && code > 96) {\n newCode += 26\n }\n while (newCode > 90 && code < 91 || newCode > 122 && code > 96) {\n newCode -= 26\n }\n result += String.fromCharCode(newCode)\n } else {\n result += character\n }\n }\n return result\n}", "function getFirstCh(c) {\n execScript(\"tmp=asc(\\\"\" + c + \"\\\")\", \"vbscript\");\n tmp = 65536 + tmp;\n if (tmp >= 45217 && tmp <= 45252) return \"A\";\n if (tmp >= 45253 && tmp <= 45760) return \"B\";\n if (tmp >= 45761 && tmp <= 46317) return \"C\";\n if (tmp >= 46318 && tmp <= 46825) return \"D\";\n if (tmp >= 46826 && tmp <= 47009) return \"E\";\n if (tmp >= 47010 && tmp <= 47296) return \"F\";\n if ((tmp >= 47297 && tmp <= 47613) || (tmp == 63193)) return \"G\";\n if (tmp >= 47614 && tmp <= 48118) return \"H\";\n if (tmp >= 48119 && tmp <= 49061) return \"J\";\n if (tmp >= 49062 && tmp <= 49323) return \"K\";\n if (tmp >= 49324 && tmp <= 49895) return \"L\";\n if (tmp >= 49896 && tmp <= 50370) return \"M\";\n if (tmp >= 50371 && tmp <= 50613) return \"N\";\n if (tmp >= 50614 && tmp <= 50621) return \"O\";\n if (tmp >= 50622 && tmp <= 50905) return \"P\";\n if (tmp >= 50906 && tmp <= 51386) return \"Q\";\n if (tmp >= 51387 && tmp <= 51445) return \"R\";\n if (tmp >= 51446 && tmp <= 52217) return \"S\";\n if (tmp >= 52218 && tmp <= 52697) return \"T\";\n if (tmp >= 52698 && tmp <= 52979) return \"W\";\n if (tmp >= 52980 && tmp <= 53688) return \"X\";\n if (tmp >= 53689 && tmp <= 54480) return \"Y\";\n if (tmp >= 54481 && tmp <= 62289) return \"Z\";\n return c.charAt(0);\n }", "function charFromX(line, x) {\n if (x <= 0) return 0;\n var lineObj = getLine(line), text = lineObj.text;\n function getX(len) {\n return measureLine(lineObj, len).left;\n }\n var from = 0, fromX = 0, to = text.length, toX;\n // Guess a suitable upper bound for our search.\n var estimated = Math.min(to, Math.ceil(x / charWidth()));\n for (;;) {\n var estX = getX(estimated);\n if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));\n else {toX = estX; to = estimated; break;}\n }\n if (x > toX) return to;\n // Try to guess a suitable lower bound as well.\n estimated = Math.floor(to * 0.8); estX = getX(estimated);\n if (estX < x) {from = estimated; fromX = estX;}\n // Do a binary search between these bounds.\n for (;;) {\n if (to - from <= 1) return (toX - x > x - fromX) ? from : to;\n var middle = Math.ceil((from + to) / 2), middleX = getX(middle);\n if (middleX > x) {to = middle; toX = middleX;}\n else {from = middle; fromX = middleX;}\n }\n }", "function charFromX(line, x) {\n if (x <= 0) return 0;\n var lineObj = getLine(line), text = lineObj.text;\n function getX(len) {\n return measureLine(lineObj, len).left;\n }\n var from = 0, fromX = 0, to = text.length, toX;\n // Guess a suitable upper bound for our search.\n var estimated = Math.min(to, Math.ceil(x / charWidth()));\n for (;;) {\n var estX = getX(estimated);\n if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));\n else {toX = estX; to = estimated; break;}\n }\n if (x > toX) return to;\n // Try to guess a suitable lower bound as well.\n estimated = Math.floor(to * 0.8); estX = getX(estimated);\n if (estX < x) {from = estimated; fromX = estX;}\n // Do a binary search between these bounds.\n for (;;) {\n if (to - from <= 1) return (toX - x > x - fromX) ? from : to;\n var middle = Math.ceil((from + to) / 2), middleX = getX(middle);\n if (middleX > x) {to = middle; toX = middleX;}\n else {from = middle; fromX = middleX;}\n }\n }", "function charFromX(line, x) {\n if (x <= 0) return 0;\n var lineObj = getLine(line), text = lineObj.text;\n function getX(len) {\n return measureLine(lineObj, len).left;\n }\n var from = 0, fromX = 0, to = text.length, toX;\n // Guess a suitable upper bound for our search.\n var estimated = Math.min(to, Math.ceil(x / charWidth()));\n for (;;) {\n var estX = getX(estimated);\n if (estX <= x && estimated < to) estimated = Math.min(to, Math.ceil(estimated * 1.2));\n else {toX = estX; to = estimated; break;}\n }\n if (x > toX) return to;\n // Try to guess a suitable lower bound as well.\n estimated = Math.floor(to * 0.8); estX = getX(estimated);\n if (estX < x) {from = estimated; fromX = estX;}\n // Do a binary search between these bounds.\n for (;;) {\n if (to - from <= 1) return (toX - x > x - fromX) ? from : to;\n var middle = Math.ceil((from + to) / 2), middleX = getX(middle);\n if (middleX > x) {to = middle; toX = middleX;}\n else {from = middle; fromX = middleX;}\n }\n }", "c() {\n if (this._c === undefined) {\n this._c = (this.eof ? \"\" : this._chars[this._pointer]);\n }\n return this._c;\n }", "function MapUnicodeCharacter(C)\r\n{\r\n\tif(KeyBoardLayout == BIJOY)\r\n\t\treturn bijoy_keyboard_map[C];\r\n\telse if(KeyBoardLayout == UNIJOY)\r\n\t\treturn unijoy_keyboard_map[C];\r\n\telse if(KeyBoardLayout == PROBHAT)\r\n\t\treturn probhat_keyboard_map[C];\r\n\telse if(KeyBoardLayout == SWIPHONETIC)\r\n\t\treturn somewherein_phonetic_keyboard_map [C];\r\n\telse if(KeyBoardLayout == AVROPHONETIC) {\r\n\t\tAvro_Forced = IsAvorForced(C);\r\n\t\treturn avro_phonetic_keyboard_map [C];\r\n\t}\r\n\telse if(KeyBoardLayout == BORNOSOFTACCENT) {\r\n\t\treturn bornosoft_keyboard_map [C];\r\n\t}\r\n\r\n\treturn C;\r\n}", "function charToCol(c) {\n c = c.toUpperCase();\n var r = 192 + ((c.charCodeAt(0) - 65) * 2.52) % 64;\n r = Math.floor(r);\n return r;\n}", "getChar(x,y){\n if(this.map[y] != undefined && this.map[y][x] != undefined){\n return(this.map[y][x]);\n }\n else{\n return({color: this.backgcolor, solid: 1});\n }\n }", "function rchr(x) {\n \t\treturn table.charAt(0x3F & x);\n \t}", "function getCharAtPosInDiv(editableDiv, pos) {\r\n\treturn editableDiv.innerHTML.charAt(pos);\r\n}", "function fN2C(n) {\n if (n < 10) {return n.toString();}\n else if (n < 36) {return String.fromCharCode(0x41 + n - 10);}\n else if (n < 60) {return String.fromCharCode(0x61 + n - 36);}\n else if (n < 100) {return \"z\"+ fN2C(n - 60);}\n\n return \"_\";\n}", "get(index) { return this.input.charAt(index) }", "function coordsChar(cm, x, y) {\n\t\t var doc = cm.doc;\n\t\t y += cm.display.viewOffset;\n\t\t if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n\t\t var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n\t\t if (lineN > last)\n\t\t { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n\t\t if (x < 0) { x = 0; }\n\n\t\t var lineObj = getLine(doc, lineN);\n\t\t for (;;) {\n\t\t var found = coordsCharInner(cm, lineObj, lineN, x, y);\n\t\t var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n\t\t if (!collapsed) { return found }\n\t\t var rangeEnd = collapsed.find(1);\n\t\t if (rangeEnd.line == lineN) { return rangeEnd }\n\t\t lineObj = getLine(doc, lineN = rangeEnd.line);\n\t\t }\n\t\t }", "selectChar(){\n this.pFse = (this.pFse + 1) % this.frase.length;\n return this.frase[this.pFse];\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function getC()\n\t{\n\t var number = Math.floor(Math.random() * 10);\n\t var c = ['☪', 'C','c', '☪','☪', 'C','☪', 'C','☪', 'C'];\n\t if ( number % 2 == 0 ) return \"c\";\n\t return c[number];\n\t}", "function wrapCoords(c, bound) {\n if(c < 0) { \n c += bound; \n } else if(c >= bound) {\n c -= bound;\n }\n return c;\n}", "function toColumn(c) {\n let sc = \"\";\n c++;\n do {\n sc = String.fromCharCode(64 + (c % 26 || 26)) + sc;\n } while ((c = Math.floor((c - 1) / 26)));\n return sc;\n}", "function characPosit(character){\n\t\tvar str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\n\t\treturn str.search(character)+1;\n\n}", "function coordsChar(cm, x, y) {\n var doc = cm.view.doc;\n y += cm.display.viewOffset;\n if (y < 0) return {line: 0, ch: 0, outside: true};\n var lineNo = lineAtHeight(doc, y);\n if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};\n if (x < 0) x = 0;\n\n for (;;) {\n var lineObj = getLine(doc, lineNo);\n var found = coordsCharInner(cm, lineObj, lineNo, x, y);\n var merged = collapsedSpanAtEnd(lineObj);\n var mergedPos = merged && merged.find();\n if (merged && found.ch >= mergedPos.from.ch)\n lineNo = mergedPos.to.line;\n else\n return found;\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.view.doc;\n y += cm.display.viewOffset;\n if (y < 0) return {line: 0, ch: 0, outside: true};\n var lineNo = lineAtHeight(doc, y);\n if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};\n if (x < 0) x = 0;\n\n for (;;) {\n var lineObj = getLine(doc, lineNo);\n var found = coordsCharInner(cm, lineObj, lineNo, x, y);\n var merged = collapsedSpanAtEnd(lineObj);\n var mergedPos = merged && merged.find();\n if (merged && found.ch >= mergedPos.from.ch)\n lineNo = mergedPos.to.line;\n else\n return found;\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.view.doc;\n y += cm.display.viewOffset;\n if (y < 0) return {line: 0, ch: 0, outside: true};\n var lineNo = lineAtHeight(doc, y);\n if (lineNo >= doc.size) return {line: doc.size - 1, ch: getLine(doc, doc.size - 1).text.length};\n if (x < 0) x = 0;\n\n for (;;) {\n var lineObj = getLine(doc, lineNo);\n var found = coordsCharInner(cm, lineObj, lineNo, x, y);\n var merged = collapsedSpanAtEnd(lineObj);\n var mergedPos = merged && merged.find();\n if (merged && found.ch >= mergedPos.from.ch)\n lineNo = mergedPos.to.line;\n else\n return found;\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n }", "function get_character(workspace, char) {\n const x = (char * font_width) % (font_width * spritesheet_columns);\n const y = font_height * Math.floor(char / spritesheet_columns);\n return workspace.spritesheet_ctx.getImageData(x, y, font_width, font_height);\n }", "function caeserCipher(str, shift) {\n const alphabetArr = \"abcdefghijklmnopqrstuvwxyz\".split(\"\");\n let res = \"\";\n for(let i =0; i < str.length; i++){\n const char = str[i];\n const idx = alphabetArr.indexOf(char);\n //console.log(idx)\n if(idx === -1 ){\n res += char;\n continue;\n }\n const encodedIdx = (idx + shift) %26;\n console.log(encodedIdx)\n res += alphabetArr[encodedIdx]\n }\n return res;\n}", "_convertViewportColToCharacterIndex(bufferLine, coords) {\n let charIndex = coords[0];\n for (let i = 0; coords[0] >= i; i++) {\n const length = bufferLine.loadCell(i, this._workCell).getChars().length;\n if (this._workCell.getWidth() === 0) {\n // Wide characters aren't included in the line string so decrement the\n // index so the index is back on the wide character.\n charIndex--;\n }\n else if (length > 1 && coords[0] !== i) {\n // Emojis take up multiple characters, so adjust accordingly. For these\n // we don't want ot include the character at the column as we're\n // returning the start index in the string, not the end index.\n charIndex += length - 1;\n }\n }\n return charIndex;\n }", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n}", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n}", "function coordsChar(cm, x, y) {\n var doc = cm.doc;\n y += cm.display.viewOffset;\n if (y < 0) { return PosWithInfo(doc.first, 0, null, true, -1) }\n var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1;\n if (lineN > last)\n { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, true, 1) }\n if (x < 0) { x = 0; }\n\n var lineObj = getLine(doc, lineN);\n for (;;) {\n var found = coordsCharInner(cm, lineObj, lineN, x, y);\n var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 ? 1 : 0));\n if (!collapsed) { return found }\n var rangeEnd = collapsed.find(1);\n if (rangeEnd.line == lineN) { return rangeEnd }\n lineObj = getLine(doc, lineN = rangeEnd.line);\n }\n}", "function key2Char(key) {\n var s = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n if (key >= 97 && key <= 122) return s.charAt(key - 97);\n if (key >= 65 && key <= 90) return s.charAt(key - 65);\n if (key >= 48 && key <= 57) return \"\" + (key - 48);\n return null;\n }", "function int_2_char(i)\n{\n switch (i) {\n case 0: return 'R';\n case 1: return 'G';\n case 2: return 'B';\n\n // shouldn't happen\n default:\n return '\\0';\n }\n}", "function chrToString(chr){\n if(chr == 23){\n chr = \"X\"\n }else if(chr == 24){\n chr = \"Y\"\n }\n return chr.toString()\n }", "function change(posm, posk){\n\n let y = (posm + posk)%27;\n return y;\n}", "function transformCharToROT13(char) {\n let alphabet = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"];\n let charIndex = alphabet.indexOf(char);\n let newCharIndex;\n if(charIndex + 13 > 25) {\n newCharIndex = charIndex + 13 - 26;}\n else {\n newCharIndex = charIndex + 13;}\n //console.log(alphabet[newCharIndex])\n return alphabet[newCharIndex];\n }", "function chr(i) {\n\t\treturn String.fromCharCode(i);\n\t}", "function cigar2pos(cigar, pos)\n{\n\tvar x = 0, y = 0;\n\tfor (var i = 0; i < cigar.length; ++i) {\n\t\tvar op = cigar[i][0], len = cigar[i][1];\n\t\tif (op == 'M') {\n\t\t\tif (y <= pos && pos < y + len)\n\t\t\t\treturn x + (pos - y);\n\t\t\tx += len, y += len;\n\t\t} else if (op == 'D') {\n\t\t\tx += len;\n\t\t} else if (op == 'I') {\n\t\t\tif (y <= pos && pos < y + len)\n\t\t\t\treturn x;\n\t\t\ty += len;\n\t\t} else if (op == 'S' || op == 'H') {\n\t\t\tif (y <= pos && pos < y + len)\n\t\t\t\treturn -1;\n\t\t\ty += len;\n\t\t}\n\t}\n\treturn -1;\n}", "function add_char(ch,values) { \n var value = base64_values.indexOf(ch); \n var x = Math.floor(value / 8); \n var y = value % 8; \n values.push(x); \n values.push(y); \n }", "static getCharCode(char) {\n if (char.length === 0) {\n return 0;\n }\n const charCode = char.charCodeAt(0);\n switch (charCode) {\n case 768 /* U_Combining_Grave_Accent */: return 96 /* U_GRAVE_ACCENT */;\n case 769 /* U_Combining_Acute_Accent */: return 180 /* U_ACUTE_ACCENT */;\n case 770 /* U_Combining_Circumflex_Accent */: return 94 /* U_CIRCUMFLEX */;\n case 771 /* U_Combining_Tilde */: return 732 /* U_SMALL_TILDE */;\n case 772 /* U_Combining_Macron */: return 175 /* U_MACRON */;\n case 773 /* U_Combining_Overline */: return 8254 /* U_OVERLINE */;\n case 774 /* U_Combining_Breve */: return 728 /* U_BREVE */;\n case 775 /* U_Combining_Dot_Above */: return 729 /* U_DOT_ABOVE */;\n case 776 /* U_Combining_Diaeresis */: return 168 /* U_DIAERESIS */;\n case 778 /* U_Combining_Ring_Above */: return 730 /* U_RING_ABOVE */;\n case 779 /* U_Combining_Double_Acute_Accent */: return 733 /* U_DOUBLE_ACUTE_ACCENT */;\n }\n return charCode;\n }" ]
[ "0.7024991", "0.7024688", "0.6790267", "0.6457656", "0.62811", "0.61889803", "0.61611974", "0.61095667", "0.6102148", "0.60968727", "0.5966746", "0.5907109", "0.59026957", "0.5901869", "0.5901869", "0.5901869", "0.5901869", "0.5895901", "0.5885721", "0.58631426", "0.5852097", "0.58384764", "0.5832766", "0.58277684", "0.5809814", "0.5805933", "0.578339", "0.57770693", "0.5763424", "0.5754377", "0.5745056", "0.5702671", "0.57003874", "0.5693862", "0.56871164", "0.5641538", "0.5636495", "0.5618696", "0.55985737", "0.5597684", "0.5597068", "0.5591955", "0.55713767", "0.55713767", "0.5558977", "0.5555234", "0.5548734", "0.5529124", "0.5529124", "0.5529124", "0.5528066", "0.55257213", "0.55202806", "0.5519303", "0.5513058", "0.55092305", "0.5490667", "0.548608", "0.54688895", "0.54676723", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.54587096", "0.5456023", "0.5455795", "0.5455638", "0.5451693", "0.5450901", "0.5450901", "0.5450901", "0.54507387", "0.54507387", "0.54507387", "0.54507387", "0.54507387", "0.54467446", "0.54456973", "0.54435927", "0.54422", "0.54422", "0.54422", "0.54383767", "0.543552", "0.5430726", "0.5429085", "0.5427094", "0.5415889", "0.540111", "0.53992534", "0.5385691" ]
0.740268
1
highlight/unhighlight the given matches
function hmatch(matches, highlight) { for (var j=1; j<3; j++) { for (var i=0; i<matches[j].length; i++) { var id = getR(matches[j][i][0])+"_"+getC(matches[j][i][1]); // alert(id); if (highlight) h2(id); else u(id); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "set highlightMatches(v) {\n this._highlights = v;\n }", "highlightMatches(text, query) {\n const regex = this.toRegex(query);\n if (regex instanceof RegExp) {\n return text.replace(regex, match => `<b>${match}</b>`);\n }\n return text;\n }", "function highlightMatches (text, query) {\n // Sort terms length, so that the longest are highlighted first.\n const terms = tokenize(query).sort((term1, term2) => term2.length - term1.length)\n return highlightTerms(text, terms)\n}", "function highlightMatch() {\n //if no matches, just clear the document\n if (!obj.hasMatch) { \n try {clearAll(chromeWindow, header); fireMouseEvent(\"click\", chromeWindow.content.wrappedJSObject.document.body); return;}\n catch(err) {return;} \n }\n //if XUL searching, don't do anything because red highlighting throws an error\n if (instanceOf(obj.document, XULDocument)) {return;}\n //then highlight all or just one, depending on whether they clicked on an expanded match object or not\n var win = obj.document.defaultView;\n if (!obj._toExpand) {\n clearAll(chromeWindow, obj);\n try {selectAll(win, obj);} catch (err) {debug(err)}\n header.style.color = 'red';\n header.title = 'black';\n }\n else {\n clearAll(chromeWindow, obj);\n var matchToSelect = oneMatch(obj);\n try {selectAll(obj.document.defaultView, matchToSelect);} catch (err) {debug(err)}\n header.childNodes[2].style.color = 'red';\n header.title = 'green';\n }\n }", "function FMCClearSearch( win )\n{\n var highlights\t= FMCGetElementsByClassRoot( win.document.body, \"highlight\" );\n \n for ( var i = 0; i < highlights.length; i++ )\n {\n\t\tvar highlight\t= highlights[i];\n\t\tvar innerSpan\t= FMCGetChildNodeByTagName( highlight, \"SPAN\", 0 );\n var text\t\t= win.document.createTextNode( innerSpan.innerHTML );\n \n highlight.parentNode.replaceChild( text, highlight );\n }\n \n gColorIndex = 0;\n gFirstHighlight = null;\n \n // At this point, highlight nodes got replaced by text nodes. This causes nodes that were once single text nodes to\n // become divided into multiple text nodes. Future attempts to highlight multi-character strings may not work\n // because they may have been divided into multiple text nodes. To solve this, we merge adjacent text nodes.\n \n FMCMergeTextNodes( win.document.body );\n}", "function highlight(text) {\n var src_str = $(\"#demo\").html();\n var term = text;\n term = term.replace(/(\\s+)/, \"(<[^>]+>)*$1(<[^>]+>)*\");\n var pattern = new RegExp(\"(\" + term + \")\", \"gi\");\n\n src_str = src_str.replace(pattern, \"<mark>$1</mark>\");\n src_str = src_str.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\\/mark>)/, \"$1</mark>$2<mark>$4\");\n\n $(\"#demo\").html(src_str);\n}", "function highlightMatchesInAllRelevantCells (cm) {\n\t\tvar newOverlay = null;\n\n\t\tvar re = params.show_token === true ? /[\\w$]/ : params.show_token;\n\t\tvar from = cm.getCursor('from');\n\t\tif (!cm.somethingSelected() && params.show_token) {\n\t\t\tvar line = cm.getLine(from.line), start = from.ch, end = start;\n\t\t\twhile (start && re.test(line.charAt(start - 1))) {\n\t\t\t\t--start;\n\t\t\t}\n\t\t\twhile (end < line.length && re.test(line.charAt(end))) {\n\t\t\t\t++end;\n\t\t\t}\n\t\t\tif (start < end) {\n\t\t\t\tnewOverlay = makeOverlay(line.slice(start, end), re, params.highlight_style);\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tvar to = cm.getCursor(\"to\");\n\t\t\tif (from.line == to.line) {\n\t\t\t\tif (!params.words_only || isWord(cm, from, to)) {\n\t\t\t\t\tvar selection = cm.getRange(from, to);\n\t\t\t\t\tif (params.trim) {\n\t\t\t\t\t\tselection = selection.replace(/^\\s+|\\s+$/g, \"\");\n\t\t\t\t\t}\n\t\t\t\t\tif (selection.length >= params.min_chars) {\n\t\t\t\t\t\tvar hasBoundary = params.highlight_only_whole_words ? (re instanceof RegExp ? re : /[\\w$]/) : false;\n\t\t\t\t\t\tnewOverlay = makeOverlay(selection, hasBoundary, params.highlight_style);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tvar cells = params.highlight_across_all_cells ? get_relevant_cells() : [\n\t\t\t$(cm.getWrapperElement()).closest('.cell').data('cell')\n\t\t];\n\t\tvar oldOverlay = globalState.overlay; // cached for later function\n\t\tglobalState.overlay = newOverlay;\n\t\tcells.forEach(function (cell, idx, array) {\n\t\t\t// cm.operation to delay updating DOM until all work is done\n\t\t\tcell.code_mirror.operation(function () {\n\t\t\t\tcell.code_mirror.removeOverlay(oldOverlay);\n\t\t\t\tif (newOverlay) {\n\t\t\t\t\tcell.code_mirror.addOverlay(newOverlay);\n\t\t\t\t}\n\t\t\t});\n\t\t});\n\t}", "function resultHighlight(text, term) {\n var terms = term.split(\" \");\n\n $.each(terms, function (key, term) {\n if (term.length >= 3) {\n term = term.replace(/(\\s+)/, \"(<[^>]+>)*$1(<[^>]+>)*\");\n var pattern = new RegExp(\"(\" + term + \")\", \"gi\");\n\n text = text.replace(pattern, \"<mark>$1</mark>\");\n }\n });\n\n return text;\n //remove the mark tag if needed\n //srcstr = srcstr.replace(/(<mark>[^<>]*)((<[^>]+>)+)([^<>]*<\\/mark>)/, \"$1</mark>$2<mark>$4\");\n }", "highlight(on) { }", "get highlightMatches() {\n return this._highlights;\n }", "addHighlightMatch(pat) {\n this._highlights.push(pat);\n }", "function highlight(id) {\n\n // Find and remove all higlighted chars\n var elems = el.getElementsByTagName('span');\n removeClasses(elems, 'highlight');\n\n // Mark the matching chars as highlited\n var a = annotationById(id);\n if (a) addClasses(elements(a.pos), 'highlight');\n }", "function localSearchHighlight(searchStr, singleWordSearch, doc) \n{\n var MAX_WORDS = 50; //limit for words to search, if unlimited, browser may crash\n doc = typeof(doc) != 'undefined' ? doc : document;\n \n if (!doc.createElement) \n {\n return;\n }\n \n // Trim leading and trailing spaces after unescaping\n searchstr = unescape(searchStr).replace(/^\\s+|\\s+$/g, \"\");\n \n if( searchStr == '' ) \n {\n return;\n }\n \n //majgis: Single search option\n if(singleWordSearch)\n {\n phrases = searchStr.replace(/\\+/g,' ').split(/\\\"/);\n }\n else\n {\n phrases = [\"\",searchStr];\n }\n \n var hinodes = [];\n colorgen = colorGenerator(singleWordSearch || !clearBetweenSelections);\n \n for(p=0; p < phrases.length; p++) \n {\n phrases[p] = unescape(phrases[p]).replace(/^\\s+|\\s+$/g, \"\");\n \n if( phrases[p] == '' ) \n {\n continue;\n }\n \n if( p % 2 == 0 ) \n {\n words = phrases[p].replace(/([+,()]|%(29|28)|\\W+(AND|OR)\\W+)/g,' ').split(/\\s+/);\n }\n else \n { \n words=Array(1); \n words[0] = phrases[p]; \n }\n \n //limit length to prevent crashing browser\n if (words.length > MAX_WORDS)\n {\n words.splice(MAX_WORDS - 1, phrases.length - MAX_WORDS);\n }\n \n for (w=0; w < words.length; w++) \n {\n if( words[w] == '' ) \n {\n continue;\n }\n \n hinodes = highlightWord(doc.getElementsByTagName(\"body\")[0], words[w], doc);\n }\n }\n \n selection.removeAllRanges();\n var oldSelection = document.getElementById(\"mySelectedSpan\");\n var reselectRange = document.createRange();\n reselectRange.selectNode(oldSelection);\n selection.addRange(reselectRange);\n}", "function highlightRewritten(selection, container, anchorNode, focusNode, anchorOffset, focusOffset, highlightColor, uniqueId){\n // NOTE: Look at highlightTry6 for the current highlight function\n}", "function unhighlightAnnotate(ids) {\n var idx = 0;\n var end = ids.length;\n highlight_index++;\n var selectNow = '';\n\n //strip spaces\n if ($('#' + ids[0]).hasClass(\"space\")) {\n idx = 1;\n }\n if ($('#' + ids[end - 1]).hasClass(\"space\")) {\n end = ids.length - 1;\n }\n\n //highlight\n for (i = idx; i < end; i++) {\n if ($(\"#\" + ids[i]).hasClass(\"highlight\")) {\n $(\"#\" + ids[i]).removeClass(\"highlight\")\n }\n selectNow = selectNow + $(\"#\" + ids[i]).text() + \" \";\n }\n return selectNow;\n}", "function highlight_words() {\n\n // YOUR CODE GOES HERE\n}", "highlightCorrectWord(result) {\n const highlightTint = this.getHighlightColour()\n\n // result contains the sprites of the letters, the word, etc.\n const word = this.wordList[result.word]\n\n word.text.fill = '#' + highlightTint.toString(16)\n word.text.stroke = '#000000'\n\n this.selectFeatureWord(word.text)\n\n result.letters.forEach((letter) => {\n letter.tint = highlightTint\n })\n }", "function highlightAnnotate(ids) {\n var idx = 0;\n var end = ids.length;\n highlight_index++;\n var selectNow = '';\n\n //strip spaces\n if ($('#' + ids[0]).hasClass(\"space\")) {\n idx = 1;\n }\n if ($('#' + ids[end - 1]).hasClass(\"space\")) {\n end = ids.length - 1;\n }\n\n //highlight\n for (i = idx; i < end; i++) {\n $(\"#\" + ids[i]).addClass(\"highlight\");\n selectNow = selectNow + $(\"#\" + ids[i]).text() + \" \";\n }\n\n return selectNow;\n}", "function highlight() {\n if (window.getSelection) {\n var selection = window.getSelection();\n if (selection.rangeCount) {\n var range = selection.getRangeAt(0).cloneRange();\n var highlightNode = document.createElement(\"span\");\n highlightNode.setAttribute(\"id\", \"highlighted\");\n highlightNode.setAttribute(\"style\", \"background-color:#FFFF00\");\n range.surroundContents(highlightNode);\n selection.removeAllRanges();\n }\n }\n}", "function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) \r\n{\r\n // the highlightStartTag and highlightEndTag parameters are optional\r\n if ((!highlightStartTag) || (!highlightEndTag)) {\r\n highlightStartTag = \"<font style='color:blue; background-color:yellow;'>\";\r\n highlightEndTag = \"</font>\";\r\n }\r\n \r\n // find all occurences of the search term in the given text,\r\n // and add some \"highlight\" tags to them (we're not using a\r\n // regular expression search, because we want to filter out\r\n // matches that occur within HTML tags and script blocks, so\r\n // we have to do a little extra validation)\r\n var newText = \"\";\r\n var i = -1;\r\n var lcSearchTerm = searchTerm.toLowerCase();\r\n var lcBodyText = bodyText.toLowerCase();\r\n \r\n while (bodyText.length > 0) {\r\n i = lcBodyText.indexOf(lcSearchTerm, i+1);\r\n if (i < 0) {\r\n newText += bodyText;\r\n bodyText = \"\";\r\n } else {\r\n // skip anything inside an HTML tag\r\n if (bodyText.lastIndexOf(\">\", i) >= bodyText.lastIndexOf(\"<\", i)) {\r\n // skip anything inside a <script> block\r\n if (lcBodyText.lastIndexOf(\"/script>\", i) >= lcBodyText.lastIndexOf(\"<script\", i)) {\r\n subName= returnSubName(searchTerm);\r\n \r\n newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + subName + highlightEndTag;\r\n bodyText = bodyText.substr(i + searchTerm.length);\r\n lcBodyText = bodyText.toLowerCase();\r\n i = -1;\r\n }\r\n }\r\n }\r\n }\r\n \r\n return newText;\r\n}", "_msgHighlightTransform(event, message, map, $msg, $effects) {\n let result = message;\n for (let pat of this._highlights) {\n let pattern = pat;\n let locations = [];\n let arr = null;\n /* Ensure pattern has \"g\" flag */\n if (pat.flags.indexOf(\"g\") === -1) {\n pattern = new RegExp(pat, pat.flags + \"g\");\n }\n while ((arr = pattern.exec(event.message)) !== null) {\n if (!$msg.hasClass(\"highlight\")) {\n $msg.addClass(\"highlight\");\n }\n let whole = arr[0];\n let part = arr.length > 1 ? arr[1] : arr[0];\n let start = arr.index + whole.indexOf(part);\n let end = start + part.length;\n locations.push({part: part, start: start, end: end});\n }\n /* Ensure the locations array is indeed sorted */\n locations.sort((a, b) => a.start - b.start);\n while (locations.length > 0) {\n let location = locations.pop();\n let node = $(`<em class=\"highlight\"></em>`).text(location.part);\n let msg_start = result.substr(0, map[location.start]);\n let msg_part = node[0].outerHTML;\n let msg_end = result.substr(map[location.end]);\n $msg.addClass(\"highlight\");\n result = msg_start + msg_part + msg_end;\n this._remap(map, location.start, location.end, msg_part.length);\n }\n }\n return result;\n }", "function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) \r\n{\r\n // the highlightStartTag and highlightEndTag parameters are optional\r\n if ((!highlightStartTag) || (!highlightEndTag)) {\r\n highlightStartTag = \"<font style='color:blue; background-color:#00B2EE;'>\";\r\n highlightEndTag = \"</font>\";\r\n }\r\n \r\n // find all occurences of the search term in the given text,\r\n // and add some \"highlight\" tags to them (we're not using a\r\n // regular expression search, because we want to filter out\r\n // matches that occur within HTML tags and script blocks, so\r\n // we have to do a little extra validation)\r\n var newText = \"\";\r\n var i = -1;\r\n var lcSearchTerm = searchTerm.toLowerCase();\r\n var lcBodyText = bodyText.toLowerCase();\r\n \r\n while (bodyText.length > 0) {\r\n i = lcBodyText.indexOf(lcSearchTerm, i+1);\r\n if (i < 0) {\r\n newText += bodyText;\r\n bodyText = \"\";\r\n } else {\r\n // skip anything inside an HTML tag\r\n if (bodyText.lastIndexOf(\">\", i) >= bodyText.lastIndexOf(\"<\", i)) {\r\n // skip anything inside a <script> block\r\n if (lcBodyText.lastIndexOf(\"/script>\", i) >= lcBodyText.lastIndexOf(\"<script\", i)) {\r\n newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;\r\n bodyText = bodyText.substr(i + searchTerm.length);\r\n lcBodyText = bodyText.toLowerCase();\r\n i = -1;\r\n }\r\n }\r\n }\r\n }\r\n \r\n return newText;\r\n}", "function highlightTextSearch(text) {\r\n\t\r\n\t// Barra testo cercato\r\n\t$(\"#txtSearched\").empty();\r\n\t$(\"#txtSearched\").append(\"<p>Risultati per \\\"<span class='highlight'>\"+text+\"</span>\\\" :</p>\");\r\n\t\r\n\t// Highlight testo cercato\t\r\n\t$('.searchTitleHere').each(function(){\r\n\t\t var search_value = text.toUpperCase();\r\n\t\t var search_regexp = new RegExp(search_value, \"i\");\r\n\t\t $(this).html($(this).html().replace(search_regexp,\"<span class='highlight'>\"+search_value+\"</span>\"));\r\n\t});\r\n}", "function searchNhighlight(searchvalue, search, color)\r\n{\r\n var sub = searchvalue.toLowerCase();\r\n var elements = document.getElementsByClassName(search);\r\n if(sub != '') //if the text box is not empty\r\n for(var i = 0; i < elements.length; i++)\r\n {\r\n var searchin = elements[i].innerText;\r\n var index = searchin.toLowerCase().indexOf(sub);\r\n if( index !=-1)\r\n elements[i].style.backgroundColor= color;\r\n else\r\n elements[i].style.backgroundColor='';\r\n }\r\n else //if the value of text box is empty\r\n for(var i = 0; i < elements.length; i++)\r\n {\r\n elements[i].style.backgroundColor='';\r\n }\r\n}", "function highlight(){\r\n\tfor(var i=0; i<wordItems.length; i++)\r\n\t\twordItems[i].style.color = \"red\";\r\n}", "function highlightText(text, $node){ \n var searchText = $.trim(text).toLowerCase(), currentNode = $node.get(0).firstChild, matchIndex, newTextNode, newSpanNode;\n while ((matchIndex = currentNode.data.toLowerCase().indexOf(searchText)) >= 0) {\n newTextNode = currentNode.splitText(matchIndex);\n currentNode = newTextNode.splitText(searchText.length);\n newSpanNode = document.createElement(\"span\");\n newSpanNode.className = \"highlight\";\n currentNode.parentNode.insertBefore(newSpanNode, currentNode);\n newSpanNode.appendChild(newTextNode);\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n function subMode(lexeme, mode) {\n var i, length;\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix, openSpan = '<span class=\"' + classPrefix, closeSpan = leaveOpen ? '' : spanEndTag;\n openSpan += classname + '\">';\n return openSpan + insideSpan + closeSpan;\n }\n function processKeywords() {\n var keyword_match, last_index, match, result;\n if (!top.keywords)\n return escape(mode_buffer);\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n }\n else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n function startNewMode(mode) {\n result += mode.className ? buildSpan(mode.className, '', true) : '';\n top = Object.create(mode, { parent: { value: top } });\n }\n function processLexeme(buffer, lexeme) {\n mode_buffer += buffer;\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n }\n else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n }\n else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts);\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for (current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for (current = top; current.parent; current = current.parent) {\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n }\n catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n }\n else {\n throw e;\n }\n }\n}", "highlightInText(term) {\n var content = $('#textviewer');\n var results;\n\n function jumpTo() {\n if (results.length) {\n var position;\n var current = results.eq(0);\n\n if (current.length) {\n content.scrollTop(0);\n content.scrollTop(current.offset().top - content.offset().top - 20);\n }\n }\n }\n\n content.unmark({\n done: function() {\n content.mark(term, {\n done: function() {\n results = content.find(\"mark\");\n jumpTo();\n }\n });\n }\n });\n }", "function highlight(regex, element, child) {\n // Create a regex based on the bot match string\n var regex = new RegExp(escRegExp(regex), 'gim');\n // Generate results based on regex matches within match_parent\n var results = [];\n // Check for element\n if($(element).length) {\n // Match regex on parent element\n var match = $(element).text().match(regex);\n if(match != null) {\n // Push our matches onto results\n $(element).find(child).each(function(index, value) {\n // Push child onto to results array if it contains our regex\n if($(this).text().match(regex)) results.push($(this));\n });\n }\n }\n return results;\n}", "clearHighlight() {\n\n //TODO - your code goes here -\n }", "function matchSuspects( name ){\n rgName = name.substring(0,3);\n lcName = name.toLowerCase().substring(0,3);\n var rgQ = \"#matching .merge-list span:contains('{str}')\".supplant({\"str\": rgName});\n var lcQ = \"#matching .merge-list span:contains('{str}')\".supplant({\"str\": lcName});\n $(rgQ).addClass(\"selected\");\n }", "function highlightLinkMatches(searchString) {\r\n var linksMatched = [];\r\n for (var i = 0; i < hintMarkers.length; i++) {\r\n var linkMarker = hintMarkers[i];\r\n if (linkMarker.getAttribute(\"hintString\").indexOf(searchString) == 0) {\r\n if (linkMarker.style.display == \"none\")\r\n linkMarker.style.display = \"\";\r\n var childNodes = linkMarker.childNodes;\r\n for (var j = 0, childNodesCount = childNodes.length; j < childNodesCount; j++)\r\n childNodes[j].className = (j >= searchString.length) ? \"\" : \"matchingCharacter\";\r\n linksMatched.push(linkMarker.clickableItem);\r\n } else {\r\n linkMarker.style.display = \"none\";\r\n }\r\n }\r\n return linksMatched;\r\n }", "function getHighlightHtml(originalText, matchList) {\n var startSpan = \"<span class=\\\"mention\\\" title=\\\"\";\n var closeSpan = \"</span>\";\n\n var arr = [];\n var offset = 0;\n for (var i = 0; i < matchList.length; i++) {\n var match = matchList[i];\n\n var prev = originalText.substr(offset, match.offset - offset);\n arr.push(prev);\n\n var curr = startSpan + match.id + \"\\\">\" + originalText.substr(match.offset, match.textLength) + closeSpan;\n arr.push(curr);\n offset = match.offset + match.textLength;\n }\n\n // Add last\n var last = originalText.substr(offset, originalText.length - offset);\n arr.push(last);\n\n return arr.join('');\n}", "function highlightify(source,output,highlightRegExp)\n{\n\tif(source && source != \"\")\n\t\t{\n\t\tvar wikifier = new Wikifier(source,formatter,highlightRegExp,null);\n\t\twikifier.outputText(output,0,source.length);\n\t\t}\n}", "_highlight(items) {\n return _.flatten(items.map((item) => {\n return MentionHighlighter.highlight(item, this.state.highlightWords, { highlightClassName: 'highlight', key: Math.random() });\n }));\n }", "function highlightMatches(pattern, appLinks) {\n\tvar appLinks = document.getElementsByClassName('appLinkHyperLink');\n\tpattern = pattern.split(' ');\n\t\n\tfirstMatch = -1;\n\tvar index = 1;\n\n\t// Iterate through all AppLink objects on current page\n\tfor (var i = 0; i < appLinks.length; i++) {\n\t\tif (rootSearchTree.contains(i, pattern)) {\n\t\t\tif (firstMatch == -1) firstMatch = i;\n\n\t\t\tappLinks[i].className = 'appLinkHyperLink searched';\n\t\t\tappLinks[i].tabIndex = index++;\n\t\t}\n\t\telse {\n\t\t\tappLinks[i].className = 'appLinkHyperLink notSearched';\n\t\t\tappLinks[i].tabIndex = -1;\n\t\t}\n\t}\n}", "function highlightSearchSorterMatchFunction($sce) {\n\t var highlightOpen = '<strong>';\n\t var highlightClose = '</strong>';\n\n\t return function highlightSearchSorterMatch(input, search) {\n\t if (!input || !search) {\n\t return input;\n\t }\n\t var cleanInput = (0, _lodashEscape2['default'])(input);\n\t var lowerCleanInput = cleanInput.toLowerCase();\n\t search = search.toLowerCase();\n\t if (contains(lowerCleanInput, search)) {\n\t cleanInput = cleanInput.replace(new RegExp('(' + search + ')', 'ig'), highlightOpen + '$1' + highlightClose);\n\t } else {\n\t cleanInput = highlightIndexes(cleanInput, search);\n\t }\n\t return $sce.trustAsHtml(cleanInput);\n\t };\n\n\t function highlightIndexes(cleanInput, search) {\n\t var lowerCleanInput = cleanInput.toLowerCase();\n\t var indexes = _azSearchSorter2['default'].getAcronymIndexes(lowerCleanInput, search);\n\t if (isEmptyArray(indexes)) {\n\t indexes = _azSearchSorter2['default'].getMatchingStringIndexes(lowerCleanInput, search);\n\t }\n\t if (!isEmptyArray(indexes)) {\n\t (function () {\n\t var highlightedInput = '';\n\t var currentIndex = 0;\n\t indexes.forEach(function (anIndex) {\n\t var needsOpen = !contains(indexes, anIndex - 1);\n\t var needsClose = !contains(indexes, anIndex + 1);\n\t var open = needsOpen ? highlightOpen : '';\n\t var close = needsClose ? highlightClose : '';\n\t highlightedInput += [cleanInput.substr(currentIndex, anIndex - currentIndex), open, cleanInput.substr(anIndex, 1), close].join('');\n\t currentIndex = anIndex + 1;\n\t });\n\t cleanInput = highlightedInput + cleanInput.substr(currentIndex);\n\t })();\n\t }\n\t return cleanInput;\n\t }\n\t}", "function highlightText(list) {\n var previouslndex = null;\n list.click(function(){\n currentIndex = list.index(this);\n if (currentIndex != previouslndex){\n list.removeClass('highlight');\n $(this).addClass('highlight');\n previouslndex = currentIndex;\n }else{\n $(this).toggleClass('highlight');\n }\n \n });\n}", "highlight(query) {\n const tokens = this.tokenizer.tokenize(query);\n let token;\n let ret = '';\n let position = 0;\n // eslint-disable-next-line no-cond-assign\n while (token = tokens[position++]) {\n ret += this.highlightToken(token.type, token.value);\n }\n return ret;\n }", "function highlight_search(name) {\n var new_search = indexMap[\"search\"];\n var new_split = name.split(new_search);\n var new_name = \"\";\n var html_name = \"\";\n\n for (var l = 0; l < new_split.length; l++) {\n new_name += new_split[l];\n html_name += new_split[l];\n if (name.indexOf(new_name + new_search) != -1) {\n new_name += new_search;\n html_name += \"<font class='bg-success'>\"+new_search+\"</font>\";\n }\n }\n\n return html_name;\n}", "unhighlightAll() {\n if (!this.tf.highlightKeywords) {\n return;\n }\n\n this.unhighlight(null, this.highlightCssClass);\n }", "function processSearchQuery(query){\n var transcript = document.getElementById(\"text\");\n for(var i=0; i<transcript.childNodes.length; i++){\n var strings = transcript.childNodes[i].innerHTML.split(\" \");\n transcript.childNodes[i].style.backgroundColor=\"#d1d1d1\";\n for(var j=0; j<strings.length; j++){\n if(strings[j] == query){\n transcript.childNodes[i].style.backgroundColor=\"#ffffff\";\n }\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function repmatch(matched, before, word, after) {\r\n\tchanges++;\r\n\treturn before + '<span class=\"' + classes[curpat] + '\">' + word + '</span>' + after;\r\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function unHighlight() {\r\n var sel = window.getSelection && window.getSelection();\r\n if (sel && sel.rangeCount == 0 && savedRange != null) {\r\n sel.addRange(savedRange);\r\n }\r\n if (sel && sel.rangeCount > 0) {\r\n // Get location and text info\r\n let range = sel.getRangeAt(0);\r\n console.log(range)\r\n let node = document.createElement('p')\r\n node.setAttribute('class', 'unhighlight')\r\n let selText = range.cloneContents();\r\n node.appendChild(selText);\r\n let markedList = node.getElementsByTagName('mark');\r\n for (let i = 0; i < markedList.length; i++) {\r\n markedList[i].outerHTML = markedList[i].innerHTML;\r\n }\r\n\r\n range.deleteContents();\r\n range.insertNode(node);\r\n // Remove the tags from inserted node\r\n var unHiteLiteList = document.getElementsByClassName('unhighlight');\r\n\r\n for (let i = 0 ; i < unHiteLiteList.length; i ++) {\r\n var parent = unHiteLiteList[i].parentNode;\r\n while (unHiteLiteList[i].firstChild) {\r\n parent.insertBefore(unHiteLiteList[i].firstChild, unHiteLiteList[i]);\r\n }\r\n parent.removeChild(unHiteLiteList[i]);\r\n }\r\n // range.selectNodeContents(selText); \r\n saveCurrentState();\r\n }\r\n }", "function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)\r\n{\r\n // if the treatAsPhrase parameter is true, then we should search for \r\n // the entire phrase that was entered; otherwise, we will split the\r\n // search string so that each word is searched for and highlighted\r\n // individually\r\n if (treatAsPhrase) {\r\n searchArray = [searchText];\r\n } else {\r\n searchArray = searchText.split(\" \");\r\n }\r\n \r\n if (!document.body || typeof(document.body.innerHTML) == \"undefined\") {\r\n if (warnOnFailure) {\r\n alert(\"Por alguna razon el texto de esta pagina no se encuentra disponible, por lo que la busqueda no servira.\");\r\n }\r\n return false;\r\n }\r\n \r\n var bodyText = document.body.innerHTML;\r\n for (var i = 0; i < searchArray.length; i++) {\r\n bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);\r\n }\r\n \r\n document.body.innerHTML = bodyText;\r\n return true;\r\n}", "function WR_Highlight_key() {\n\t \t$( '.search-results .search-item .entry-content p, .search-results .search-item .entry-title a' ).each( function( i, el ) {\n\t \t\tvar keyword = $( '.search-results .result-list' ).attr( 'data-key' );\n\t \t\tvar text = $( el ).text();\n\t \t\tvar keywords = keyword.split( ' ' );\n\n\t \t\t$.each( keywords, function( i, key ) {\n\t \t\t\tvar regex = new RegExp( '(' + key + ')', 'gi' );\n\t \t\t\ttext = text.replace( regex, '<span class=\"highlight\">$1</span>' );\n\t \t\t\t$( el ).html( text )\n\t \t\t} )\n\t \t} )\n\t }", "function highlight() {\n\n\t// Get tweet text div\n\tvar tweetTextDiv = d3.select(\"#tweetTextDiv\");\n\n\t// Get tweet text (works although text is inside a <span>)\n\tvar tweetText = tweetTextDiv.text();\n\t// Get tweet text in lower case (used to highlight without case sensitivity)\n\tvar tweetTextLowerCase = tweetText.toLowerCase();\n\n\t// Highlight if string to highlight is currently displayed\n\tif (tweetTextLowerCase.includes(searchedStr)) {\n\n\t\t// Get string before the string to highlight\n\t\tvar strBefore = tweetText.substr(0, (tweetTextLowerCase.indexOf(searchedStr)));\n\t\t// Get string after the string to highlight\n\t\tvar strAfter = tweetText.substr((tweetTextLowerCase.indexOf(searchedStr) +\n\t\t\t\t\t\t\t\t\tsearchedStr.length),\n\t\t\t\t\t\t\t\t\t(tweetText.length - 1));\n\n\t\t// Remove non highlighted tweet text (the old tweet text with 1 <span>)\n\t\ttweetTextDiv.selectAll(\"span\").remove();\n\n\t\t// Append string before highlight\n\t\ttweetTextDiv.append(\"span\")\n\t\t\t.text(strBefore);\n\t\t// Append highlighted string\n\t\ttweetTextDiv.append(\"span\")\n\t\t\t.attr(\"class\", \"highlight\")\n\t\t\t.text(searchedStr);\n\t\t// Append string after highlight\n\t\ttweetTextDiv.append(\"span\")\n\t\t\t.text(strAfter);\n\t}\n}", "function highlight(name, value, ignore_illegals, continuation) {\n\n function escapeRe(value) {\n return new RegExp(value.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), 'm');\n }\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n if (mode.contains[i].endSameAsBegin) {\n mode.contains[i].endRe = escapeRe( mode.contains[i].beginRe.exec(lexeme)[0] );\n }\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip && !top.subLanguage) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n if (end_mode.endSameAsBegin) {\n end_mode.starts.endRe = end_mode.endRe;\n }\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function escapeRe(value) {\n return new RegExp(value.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), 'm');\n }\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n if (mode.contains[i].endSameAsBegin) {\n mode.contains[i].endRe = escapeRe( mode.contains[i].beginRe.exec(lexeme)[0] );\n }\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag;\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip && !top.subLanguage) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n if (end_mode.endSameAsBegin) {\n end_mode.starts.endRe = end_mode.endRe;\n }\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function escapeRe(value) {\n return new RegExp(value.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), 'm');\n }\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n if (mode.contains[i].endSameAsBegin) {\n mode.contains[i].endRe = escapeRe( mode.contains[i].beginRe.exec(lexeme)[0] );\n }\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag;\n\n openSpan += classname + '\">';\n\n if (!classname) return insideSpan;\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substring(last_index, match.index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className? buildSpan(mode.className, '', true): '';\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip && !top.subLanguage) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n if (end_mode.endSameAsBegin) {\n end_mode.starts.endRe = end_mode.endRe;\n }\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for(current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substring(index, match.index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlightSelectionMatches(options) {\n let ext = [defaultTheme, matchHighlighter];\n if (options)\n ext.push(highlightConfig.of(options));\n return ext;\n}", "function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {\n // the highlightStartTag and highlightEndTag parameters are optional\n if ((!highlightStartTag) || (!highlightEndTag)) {\n highlightStartTag = \"<font style='color:blue; background-color:yellow;'>\";\n highlightEndTag = \"</font>\";\n }\n \n // find all occurences of the search term in the given text,\n // and add some \"highlight\" tags to them (we're not using a\n // regular expression search, because we want to filter out\n // matches that occur within HTML tags and script blocks, so\n // we have to do a little extra validation)\n var newText = \"\";\n var i = -1;\n var lcSearchTerm = searchTerm.toLowerCase();\n var lcBodyText = bodyText.toLowerCase();\n \n while (bodyText.length > 0) {\n i = lcBodyText.indexOf(lcSearchTerm, i+1);\n if (i < 0) {\n newText += bodyText;\n bodyText = \"\";\n } else {\n // skip anything inside an HTML tag\n if (bodyText.lastIndexOf(\">\", i) >= bodyText.lastIndexOf(\"<\", i)) {\n // skip anything inside a <script> block\n if (lcBodyText.lastIndexOf(\"/script>\", i) >= lcBodyText.lastIndexOf(\"<script\", i)) {\n newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;\n bodyText = bodyText.substr(i + searchTerm.length);\n lcBodyText = bodyText.toLowerCase();\n i = -1;\n }\n }\n }\n }\n \n return newText;\n}", "function highlight(name, value, ignore_illegals, continuation) {\n\n\t function subMode(lexeme, mode) {\n\t for (var i = 0; i < mode.contains.length; i++) {\n\t if (testRe(mode.contains[i].beginRe, lexeme)) {\n\t return mode.contains[i];\n\t }\n\t }\n\t }\n\n\t function endOfMode(mode, lexeme) {\n\t if (testRe(mode.endRe, lexeme)) {\n\t while (mode.endsParent && mode.parent) {\n\t mode = mode.parent;\n\t }\n\t return mode;\n\t }\n\t if (mode.endsWithParent) {\n\t return endOfMode(mode.parent, lexeme);\n\t }\n\t }\n\n\t function isIllegal(lexeme, mode) {\n\t return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n\t }\n\n\t function keywordMatch(mode, match) {\n\t var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n\t return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n\t }\n\n\t function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n\t var classPrefix = noPrefix ? '' : options.classPrefix,\n\t openSpan = '<span class=\"' + classPrefix,\n\t closeSpan = leaveOpen ? '' : '</span>';\n\n\t openSpan += classname + '\">';\n\n\t return openSpan + insideSpan + closeSpan;\n\t }\n\n\t function processKeywords() {\n\t if (!top.keywords)\n\t return escape(mode_buffer);\n\t var result = '';\n\t var last_index = 0;\n\t top.lexemesRe.lastIndex = 0;\n\t var match = top.lexemesRe.exec(mode_buffer);\n\t while (match) {\n\t result += escape(mode_buffer.substr(last_index, match.index - last_index));\n\t var keyword_match = keywordMatch(top, match);\n\t if (keyword_match) {\n\t relevance += keyword_match[1];\n\t result += buildSpan(keyword_match[0], escape(match[0]));\n\t } else {\n\t result += escape(match[0]);\n\t }\n\t last_index = top.lexemesRe.lastIndex;\n\t match = top.lexemesRe.exec(mode_buffer);\n\t }\n\t return result + escape(mode_buffer.substr(last_index));\n\t }\n\n\t function processSubLanguage() {\n\t var explicit = typeof top.subLanguage == 'string';\n\t if (explicit && !languages[top.subLanguage]) {\n\t return escape(mode_buffer);\n\t }\n\n\t var result = explicit ?\n\t highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n\t highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n\t // Counting embedded language score towards the host language may be disabled\n\t // with zeroing the containing mode relevance. Usecase in point is Markdown that\n\t // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n\t // score.\n\t if (top.relevance > 0) {\n\t relevance += result.relevance;\n\t }\n\t if (explicit) {\n\t continuations[top.subLanguage] = result.top;\n\t }\n\t return buildSpan(result.language, result.value, false, true);\n\t }\n\n\t function processBuffer() {\n\t return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n\t }\n\n\t function startNewMode(mode, lexeme) {\n\t var markup = mode.className? buildSpan(mode.className, '', true): '';\n\t if (mode.returnBegin) {\n\t result += markup;\n\t mode_buffer = '';\n\t } else if (mode.excludeBegin) {\n\t result += escape(lexeme) + markup;\n\t mode_buffer = '';\n\t } else {\n\t result += markup;\n\t mode_buffer = lexeme;\n\t }\n\t top = Object.create(mode, {parent: {value: top}});\n\t }\n\n\t function processLexeme(buffer, lexeme) {\n\n\t mode_buffer += buffer;\n\t if (lexeme === undefined) {\n\t result += processBuffer();\n\t return 0;\n\t }\n\n\t var new_mode = subMode(lexeme, top);\n\t if (new_mode) {\n\t result += processBuffer();\n\t startNewMode(new_mode, lexeme);\n\t return new_mode.returnBegin ? 0 : lexeme.length;\n\t }\n\n\t var end_mode = endOfMode(top, lexeme);\n\t if (end_mode) {\n\t var origin = top;\n\t if (!(origin.returnEnd || origin.excludeEnd)) {\n\t mode_buffer += lexeme;\n\t }\n\t result += processBuffer();\n\t do {\n\t if (top.className) {\n\t result += '</span>';\n\t }\n\t relevance += top.relevance;\n\t top = top.parent;\n\t } while (top != end_mode.parent);\n\t if (origin.excludeEnd) {\n\t result += escape(lexeme);\n\t }\n\t mode_buffer = '';\n\t if (end_mode.starts) {\n\t startNewMode(end_mode.starts, '');\n\t }\n\t return origin.returnEnd ? 0 : lexeme.length;\n\t }\n\n\t if (isIllegal(lexeme, top))\n\t throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n\t /*\n\t Parser should not reach this point as all types of lexemes should be caught\n\t earlier, but if it does due to some bug make sure it advances at least one\n\t character forward to prevent infinite looping.\n\t */\n\t mode_buffer += lexeme;\n\t return lexeme.length || 1;\n\t }\n\n\t var language = getLanguage(name);\n\t if (!language) {\n\t throw new Error('Unknown language: \"' + name + '\"');\n\t }\n\n\t compileLanguage(language);\n\t var top = continuation || language;\n\t var continuations = {}; // keep continuations for sub-languages\n\t var result = '', current;\n\t for(current = top; current != language; current = current.parent) {\n\t if (current.className) {\n\t result = buildSpan(current.className, '', true) + result;\n\t }\n\t }\n\t var mode_buffer = '';\n\t var relevance = 0;\n\t try {\n\t var match, count, index = 0;\n\t while (true) {\n\t top.terminators.lastIndex = index;\n\t match = top.terminators.exec(value);\n\t if (!match)\n\t break;\n\t count = processLexeme(value.substr(index, match.index - index), match[0]);\n\t index = match.index + count;\n\t }\n\t processLexeme(value.substr(index));\n\t for(current = top; current.parent; current = current.parent) { // close dangling modes\n\t if (current.className) {\n\t result += '</span>';\n\t }\n\t }\n\t return {\n\t relevance: relevance,\n\t value: result,\n\t language: name,\n\t top: top\n\t };\n\t } catch (e) {\n\t if (e.message.indexOf('Illegal') != -1) {\n\t return {\n\t relevance: 0,\n\t value: escape(value)\n\t };\n\t } else {\n\t throw e;\n\t }\n\t }\n\t }", "function highlight(name, value, ignore_illegals, continuation) {\n\n\t function subMode(lexeme, mode) {\n\t for (var i = 0; i < mode.contains.length; i++) {\n\t if (testRe(mode.contains[i].beginRe, lexeme)) {\n\t return mode.contains[i];\n\t }\n\t }\n\t }\n\n\t function endOfMode(mode, lexeme) {\n\t if (testRe(mode.endRe, lexeme)) {\n\t while (mode.endsParent && mode.parent) {\n\t mode = mode.parent;\n\t }\n\t return mode;\n\t }\n\t if (mode.endsWithParent) {\n\t return endOfMode(mode.parent, lexeme);\n\t }\n\t }\n\n\t function isIllegal(lexeme, mode) {\n\t return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n\t }\n\n\t function keywordMatch(mode, match) {\n\t var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n\t return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n\t }\n\n\t function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n\t var classPrefix = noPrefix ? '' : options.classPrefix,\n\t openSpan = '<span class=\"' + classPrefix,\n\t closeSpan = leaveOpen ? '' : '</span>';\n\n\t openSpan += classname + '\">';\n\n\t return openSpan + insideSpan + closeSpan;\n\t }\n\n\t function processKeywords() {\n\t if (!top.keywords)\n\t return escape(mode_buffer);\n\t var result = '';\n\t var last_index = 0;\n\t top.lexemesRe.lastIndex = 0;\n\t var match = top.lexemesRe.exec(mode_buffer);\n\t while (match) {\n\t result += escape(mode_buffer.substr(last_index, match.index - last_index));\n\t var keyword_match = keywordMatch(top, match);\n\t if (keyword_match) {\n\t relevance += keyword_match[1];\n\t result += buildSpan(keyword_match[0], escape(match[0]));\n\t } else {\n\t result += escape(match[0]);\n\t }\n\t last_index = top.lexemesRe.lastIndex;\n\t match = top.lexemesRe.exec(mode_buffer);\n\t }\n\t return result + escape(mode_buffer.substr(last_index));\n\t }\n\n\t function processSubLanguage() {\n\t var explicit = typeof top.subLanguage == 'string';\n\t if (explicit && !languages[top.subLanguage]) {\n\t return escape(mode_buffer);\n\t }\n\n\t var result = explicit ?\n\t highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n\t highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n\t // Counting embedded language score towards the host language may be disabled\n\t // with zeroing the containing mode relevance. Usecase in point is Markdown that\n\t // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n\t // score.\n\t if (top.relevance > 0) {\n\t relevance += result.relevance;\n\t }\n\t if (explicit) {\n\t continuations[top.subLanguage] = result.top;\n\t }\n\t return buildSpan(result.language, result.value, false, true);\n\t }\n\n\t function processBuffer() {\n\t return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n\t }\n\n\t function startNewMode(mode, lexeme) {\n\t var markup = mode.className? buildSpan(mode.className, '', true): '';\n\t if (mode.returnBegin) {\n\t result += markup;\n\t mode_buffer = '';\n\t } else if (mode.excludeBegin) {\n\t result += escape(lexeme) + markup;\n\t mode_buffer = '';\n\t } else {\n\t result += markup;\n\t mode_buffer = lexeme;\n\t }\n\t top = Object.create(mode, {parent: {value: top}});\n\t }\n\n\t function processLexeme(buffer, lexeme) {\n\n\t mode_buffer += buffer;\n\t if (lexeme === undefined) {\n\t result += processBuffer();\n\t return 0;\n\t }\n\n\t var new_mode = subMode(lexeme, top);\n\t if (new_mode) {\n\t result += processBuffer();\n\t startNewMode(new_mode, lexeme);\n\t return new_mode.returnBegin ? 0 : lexeme.length;\n\t }\n\n\t var end_mode = endOfMode(top, lexeme);\n\t if (end_mode) {\n\t var origin = top;\n\t if (!(origin.returnEnd || origin.excludeEnd)) {\n\t mode_buffer += lexeme;\n\t }\n\t result += processBuffer();\n\t do {\n\t if (top.className) {\n\t result += '</span>';\n\t }\n\t relevance += top.relevance;\n\t top = top.parent;\n\t } while (top != end_mode.parent);\n\t if (origin.excludeEnd) {\n\t result += escape(lexeme);\n\t }\n\t mode_buffer = '';\n\t if (end_mode.starts) {\n\t startNewMode(end_mode.starts, '');\n\t }\n\t return origin.returnEnd ? 0 : lexeme.length;\n\t }\n\n\t if (isIllegal(lexeme, top))\n\t throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n\t /*\n\t Parser should not reach this point as all types of lexemes should be caught\n\t earlier, but if it does due to some bug make sure it advances at least one\n\t character forward to prevent infinite looping.\n\t */\n\t mode_buffer += lexeme;\n\t return lexeme.length || 1;\n\t }\n\n\t var language = getLanguage(name);\n\t if (!language) {\n\t throw new Error('Unknown language: \"' + name + '\"');\n\t }\n\n\t compileLanguage(language);\n\t var top = continuation || language;\n\t var continuations = {}; // keep continuations for sub-languages\n\t var result = '', current;\n\t for(current = top; current != language; current = current.parent) {\n\t if (current.className) {\n\t result = buildSpan(current.className, '', true) + result;\n\t }\n\t }\n\t var mode_buffer = '';\n\t var relevance = 0;\n\t try {\n\t var match, count, index = 0;\n\t while (true) {\n\t top.terminators.lastIndex = index;\n\t match = top.terminators.exec(value);\n\t if (!match)\n\t break;\n\t count = processLexeme(value.substr(index, match.index - index), match[0]);\n\t index = match.index + count;\n\t }\n\t processLexeme(value.substr(index));\n\t for(current = top; current.parent; current = current.parent) { // close dangling modes\n\t if (current.className) {\n\t result += '</span>';\n\t }\n\t }\n\t return {\n\t relevance: relevance,\n\t value: result,\n\t language: name,\n\t top: top\n\t };\n\t } catch (e) {\n\t if (e.message.indexOf('Illegal') != -1) {\n\t return {\n\t relevance: 0,\n\t value: escape(value)\n\t };\n\t } else {\n\t throw e;\n\t }\n\t }\n\t }", "function highlight(name, value, ignore_illegals, continuation) {\n\n\t function subMode(lexeme, mode) {\n\t for (var i = 0; i < mode.contains.length; i++) {\n\t if (testRe(mode.contains[i].beginRe, lexeme)) {\n\t return mode.contains[i];\n\t }\n\t }\n\t }\n\n\t function endOfMode(mode, lexeme) {\n\t if (testRe(mode.endRe, lexeme)) {\n\t while (mode.endsParent && mode.parent) {\n\t mode = mode.parent;\n\t }\n\t return mode;\n\t }\n\t if (mode.endsWithParent) {\n\t return endOfMode(mode.parent, lexeme);\n\t }\n\t }\n\n\t function isIllegal(lexeme, mode) {\n\t return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n\t }\n\n\t function keywordMatch(mode, match) {\n\t var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n\t return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n\t }\n\n\t function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n\t var classPrefix = noPrefix ? '' : options.classPrefix,\n\t openSpan = '<span class=\"' + classPrefix,\n\t closeSpan = leaveOpen ? '' : '</span>';\n\n\t openSpan += classname + '\">';\n\n\t return openSpan + insideSpan + closeSpan;\n\t }\n\n\t function processKeywords() {\n\t if (!top.keywords)\n\t return escape(mode_buffer);\n\t var result = '';\n\t var last_index = 0;\n\t top.lexemesRe.lastIndex = 0;\n\t var match = top.lexemesRe.exec(mode_buffer);\n\t while (match) {\n\t result += escape(mode_buffer.substr(last_index, match.index - last_index));\n\t var keyword_match = keywordMatch(top, match);\n\t if (keyword_match) {\n\t relevance += keyword_match[1];\n\t result += buildSpan(keyword_match[0], escape(match[0]));\n\t } else {\n\t result += escape(match[0]);\n\t }\n\t last_index = top.lexemesRe.lastIndex;\n\t match = top.lexemesRe.exec(mode_buffer);\n\t }\n\t return result + escape(mode_buffer.substr(last_index));\n\t }\n\n\t function processSubLanguage() {\n\t var explicit = typeof top.subLanguage == 'string';\n\t if (explicit && !languages[top.subLanguage]) {\n\t return escape(mode_buffer);\n\t }\n\n\t var result = explicit ?\n\t highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n\t highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n\t // Counting embedded language score towards the host language may be disabled\n\t // with zeroing the containing mode relevance. Usecase in point is Markdown that\n\t // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n\t // score.\n\t if (top.relevance > 0) {\n\t relevance += result.relevance;\n\t }\n\t if (explicit) {\n\t continuations[top.subLanguage] = result.top;\n\t }\n\t return buildSpan(result.language, result.value, false, true);\n\t }\n\n\t function processBuffer() {\n\t return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n\t }\n\n\t function startNewMode(mode, lexeme) {\n\t var markup = mode.className? buildSpan(mode.className, '', true): '';\n\t if (mode.returnBegin) {\n\t result += markup;\n\t mode_buffer = '';\n\t } else if (mode.excludeBegin) {\n\t result += escape(lexeme) + markup;\n\t mode_buffer = '';\n\t } else {\n\t result += markup;\n\t mode_buffer = lexeme;\n\t }\n\t top = Object.create(mode, {parent: {value: top}});\n\t }\n\n\t function processLexeme(buffer, lexeme) {\n\n\t mode_buffer += buffer;\n\t if (lexeme === undefined) {\n\t result += processBuffer();\n\t return 0;\n\t }\n\n\t var new_mode = subMode(lexeme, top);\n\t if (new_mode) {\n\t result += processBuffer();\n\t startNewMode(new_mode, lexeme);\n\t return new_mode.returnBegin ? 0 : lexeme.length;\n\t }\n\n\t var end_mode = endOfMode(top, lexeme);\n\t if (end_mode) {\n\t var origin = top;\n\t if (!(origin.returnEnd || origin.excludeEnd)) {\n\t mode_buffer += lexeme;\n\t }\n\t result += processBuffer();\n\t do {\n\t if (top.className) {\n\t result += '</span>';\n\t }\n\t relevance += top.relevance;\n\t top = top.parent;\n\t } while (top != end_mode.parent);\n\t if (origin.excludeEnd) {\n\t result += escape(lexeme);\n\t }\n\t mode_buffer = '';\n\t if (end_mode.starts) {\n\t startNewMode(end_mode.starts, '');\n\t }\n\t return origin.returnEnd ? 0 : lexeme.length;\n\t }\n\n\t if (isIllegal(lexeme, top))\n\t throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n\t /*\n\t Parser should not reach this point as all types of lexemes should be caught\n\t earlier, but if it does due to some bug make sure it advances at least one\n\t character forward to prevent infinite looping.\n\t */\n\t mode_buffer += lexeme;\n\t return lexeme.length || 1;\n\t }\n\n\t var language = getLanguage(name);\n\t if (!language) {\n\t throw new Error('Unknown language: \"' + name + '\"');\n\t }\n\n\t compileLanguage(language);\n\t var top = continuation || language;\n\t var continuations = {}; // keep continuations for sub-languages\n\t var result = '', current;\n\t for(current = top; current != language; current = current.parent) {\n\t if (current.className) {\n\t result = buildSpan(current.className, '', true) + result;\n\t }\n\t }\n\t var mode_buffer = '';\n\t var relevance = 0;\n\t try {\n\t var match, count, index = 0;\n\t while (true) {\n\t top.terminators.lastIndex = index;\n\t match = top.terminators.exec(value);\n\t if (!match)\n\t break;\n\t count = processLexeme(value.substr(index, match.index - index), match[0]);\n\t index = match.index + count;\n\t }\n\t processLexeme(value.substr(index));\n\t for(current = top; current.parent; current = current.parent) { // close dangling modes\n\t if (current.className) {\n\t result += '</span>';\n\t }\n\t }\n\t return {\n\t relevance: relevance,\n\t value: result,\n\t language: name,\n\t top: top\n\t };\n\t } catch (e) {\n\t if (e.message.indexOf('Illegal') != -1) {\n\t return {\n\t relevance: 0,\n\t value: escape(value)\n\t };\n\t } else {\n\t throw e;\n\t }\n\t }\n\t }", "function highlight(name, value, ignore_illegals, continuation) {\n\n\t function subMode(lexeme, mode) {\n\t for (var i = 0; i < mode.contains.length; i++) {\n\t if (testRe(mode.contains[i].beginRe, lexeme)) {\n\t return mode.contains[i];\n\t }\n\t }\n\t }\n\n\t function endOfMode(mode, lexeme) {\n\t if (testRe(mode.endRe, lexeme)) {\n\t while (mode.endsParent && mode.parent) {\n\t mode = mode.parent;\n\t }\n\t return mode;\n\t }\n\t if (mode.endsWithParent) {\n\t return endOfMode(mode.parent, lexeme);\n\t }\n\t }\n\n\t function isIllegal(lexeme, mode) {\n\t return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n\t }\n\n\t function keywordMatch(mode, match) {\n\t var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n\t return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n\t }\n\n\t function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n\t var classPrefix = noPrefix ? '' : options.classPrefix,\n\t openSpan = '<span class=\"' + classPrefix,\n\t closeSpan = leaveOpen ? '' : '</span>';\n\n\t openSpan += classname + '\">';\n\n\t return openSpan + insideSpan + closeSpan;\n\t }\n\n\t function processKeywords() {\n\t if (!top.keywords)\n\t return escape(mode_buffer);\n\t var result = '';\n\t var last_index = 0;\n\t top.lexemesRe.lastIndex = 0;\n\t var match = top.lexemesRe.exec(mode_buffer);\n\t while (match) {\n\t result += escape(mode_buffer.substr(last_index, match.index - last_index));\n\t var keyword_match = keywordMatch(top, match);\n\t if (keyword_match) {\n\t relevance += keyword_match[1];\n\t result += buildSpan(keyword_match[0], escape(match[0]));\n\t } else {\n\t result += escape(match[0]);\n\t }\n\t last_index = top.lexemesRe.lastIndex;\n\t match = top.lexemesRe.exec(mode_buffer);\n\t }\n\t return result + escape(mode_buffer.substr(last_index));\n\t }\n\n\t function processSubLanguage() {\n\t var explicit = typeof top.subLanguage == 'string';\n\t if (explicit && !languages[top.subLanguage]) {\n\t return escape(mode_buffer);\n\t }\n\n\t var result = explicit ?\n\t highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n\t highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n\t // Counting embedded language score towards the host language may be disabled\n\t // with zeroing the containing mode relevance. Usecase in point is Markdown that\n\t // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n\t // score.\n\t if (top.relevance > 0) {\n\t relevance += result.relevance;\n\t }\n\t if (explicit) {\n\t continuations[top.subLanguage] = result.top;\n\t }\n\t return buildSpan(result.language, result.value, false, true);\n\t }\n\n\t function processBuffer() {\n\t return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n\t }\n\n\t function startNewMode(mode, lexeme) {\n\t var markup = mode.className? buildSpan(mode.className, '', true): '';\n\t if (mode.returnBegin) {\n\t result += markup;\n\t mode_buffer = '';\n\t } else if (mode.excludeBegin) {\n\t result += escape(lexeme) + markup;\n\t mode_buffer = '';\n\t } else {\n\t result += markup;\n\t mode_buffer = lexeme;\n\t }\n\t top = Object.create(mode, {parent: {value: top}});\n\t }\n\n\t function processLexeme(buffer, lexeme) {\n\n\t mode_buffer += buffer;\n\t if (lexeme === undefined) {\n\t result += processBuffer();\n\t return 0;\n\t }\n\n\t var new_mode = subMode(lexeme, top);\n\t if (new_mode) {\n\t result += processBuffer();\n\t startNewMode(new_mode, lexeme);\n\t return new_mode.returnBegin ? 0 : lexeme.length;\n\t }\n\n\t var end_mode = endOfMode(top, lexeme);\n\t if (end_mode) {\n\t var origin = top;\n\t if (!(origin.returnEnd || origin.excludeEnd)) {\n\t mode_buffer += lexeme;\n\t }\n\t result += processBuffer();\n\t do {\n\t if (top.className) {\n\t result += '</span>';\n\t }\n\t relevance += top.relevance;\n\t top = top.parent;\n\t } while (top != end_mode.parent);\n\t if (origin.excludeEnd) {\n\t result += escape(lexeme);\n\t }\n\t mode_buffer = '';\n\t if (end_mode.starts) {\n\t startNewMode(end_mode.starts, '');\n\t }\n\t return origin.returnEnd ? 0 : lexeme.length;\n\t }\n\n\t if (isIllegal(lexeme, top))\n\t throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n\t /*\n\t Parser should not reach this point as all types of lexemes should be caught\n\t earlier, but if it does due to some bug make sure it advances at least one\n\t character forward to prevent infinite looping.\n\t */\n\t mode_buffer += lexeme;\n\t return lexeme.length || 1;\n\t }\n\n\t var language = getLanguage(name);\n\t if (!language) {\n\t throw new Error('Unknown language: \"' + name + '\"');\n\t }\n\n\t compileLanguage(language);\n\t var top = continuation || language;\n\t var continuations = {}; // keep continuations for sub-languages\n\t var result = '', current;\n\t for(current = top; current != language; current = current.parent) {\n\t if (current.className) {\n\t result = buildSpan(current.className, '', true) + result;\n\t }\n\t }\n\t var mode_buffer = '';\n\t var relevance = 0;\n\t try {\n\t var match, count, index = 0;\n\t while (true) {\n\t top.terminators.lastIndex = index;\n\t match = top.terminators.exec(value);\n\t if (!match)\n\t break;\n\t count = processLexeme(value.substr(index, match.index - index), match[0]);\n\t index = match.index + count;\n\t }\n\t processLexeme(value.substr(index));\n\t for(current = top; current.parent; current = current.parent) { // close dangling modes\n\t if (current.className) {\n\t result += '</span>';\n\t }\n\t }\n\t return {\n\t relevance: relevance,\n\t value: result,\n\t language: name,\n\t top: top\n\t };\n\t } catch (e) {\n\t if (e.message.indexOf('Illegal') != -1) {\n\t return {\n\t relevance: 0,\n\t value: escape(value)\n\t };\n\t } else {\n\t throw e;\n\t }\n\t }\n\t }", "function _removeHighlights() {\n\t\t$(\".find-highlight\").contents().unwrap();\n\t}", "function highlightWord(){\n var keyword = document.getElementById(\"keyword\").value;\n var display = document.getElementById('fileContent');\n var newContent = \"\";\n \n //find all the occurences\n let spans = document.querySelectorAll(\"mark\");\n\n for (var i=0; i< spans.length; i++){\n spans[i].outerHTML = spans[i].innerHTML;\n }\n\n var re = new RegExp(keyword, \"gi\");\n var replaceText = \"<mark od ='markMe'>$&</mark>\";\n var currentBook = display.innerHTML;\n \n newContent = currentBook.replace(re, replaceText);\n\n display.innerHTML = newContent;\n var count = document.querySelectorAll(\"mark\");\n document.getElementById(\"searchstat\").innerHTML = \"found \" + count.length + \" occurences\";\n\n if (count > 0){\n var element = document.getElementById(\"markMe\");\n element.scrollIntoView;\n }\n}", "function highlight(name, value, ignore_illegals, continuation) {\n\n\t function subMode(lexeme, mode) {\n\t var i, length;\n\n\t for (i = 0, length = mode.contains.length; i < length; i++) {\n\t if (testRe(mode.contains[i].beginRe, lexeme)) {\n\t return mode.contains[i];\n\t }\n\t }\n\t }\n\n\t function endOfMode(mode, lexeme) {\n\t if (testRe(mode.endRe, lexeme)) {\n\t while (mode.endsParent && mode.parent) {\n\t mode = mode.parent;\n\t }\n\t return mode;\n\t }\n\t if (mode.endsWithParent) {\n\t return endOfMode(mode.parent, lexeme);\n\t }\n\t }\n\n\t function isIllegal(lexeme, mode) {\n\t return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n\t }\n\n\t function keywordMatch(mode, match) {\n\t var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n\t return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n\t }\n\n\t function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n\t var classPrefix = noPrefix ? '' : options.classPrefix,\n\t openSpan = '<span class=\"' + classPrefix,\n\t closeSpan = leaveOpen ? '' : spanEndTag\n\n\t openSpan += classname + '\">';\n\n\t return openSpan + insideSpan + closeSpan;\n\t }\n\n\t function processKeywords() {\n\t var keyword_match, last_index, match, result;\n\n\t if (!top.keywords)\n\t return escape(mode_buffer);\n\n\t result = '';\n\t last_index = 0;\n\t top.lexemesRe.lastIndex = 0;\n\t match = top.lexemesRe.exec(mode_buffer);\n\n\t while (match) {\n\t result += escape(mode_buffer.substr(last_index, match.index - last_index));\n\t keyword_match = keywordMatch(top, match);\n\t if (keyword_match) {\n\t relevance += keyword_match[1];\n\t result += buildSpan(keyword_match[0], escape(match[0]));\n\t } else {\n\t result += escape(match[0]);\n\t }\n\t last_index = top.lexemesRe.lastIndex;\n\t match = top.lexemesRe.exec(mode_buffer);\n\t }\n\t return result + escape(mode_buffer.substr(last_index));\n\t }\n\n\t function processSubLanguage() {\n\t var explicit = typeof top.subLanguage === 'string';\n\t if (explicit && !languages[top.subLanguage]) {\n\t return escape(mode_buffer);\n\t }\n\n\t var result = explicit ?\n\t highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n\t highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n\t // Counting embedded language score towards the host language may be disabled\n\t // with zeroing the containing mode relevance. Usecase in point is Markdown that\n\t // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n\t // score.\n\t if (top.relevance > 0) {\n\t relevance += result.relevance;\n\t }\n\t if (explicit) {\n\t continuations[top.subLanguage] = result.top;\n\t }\n\t return buildSpan(result.language, result.value, false, true);\n\t }\n\n\t function processBuffer() {\n\t result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n\t mode_buffer = '';\n\t }\n\n\t function startNewMode(mode) {\n\t result += mode.className? buildSpan(mode.className, '', true): '';\n\t top = Object.create(mode, {parent: {value: top}});\n\t }\n\n\t function processLexeme(buffer, lexeme) {\n\n\t mode_buffer += buffer;\n\n\t if (lexeme == null) {\n\t processBuffer();\n\t return 0;\n\t }\n\n\t var new_mode = subMode(lexeme, top);\n\t if (new_mode) {\n\t if (new_mode.skip) {\n\t mode_buffer += lexeme;\n\t } else {\n\t if (new_mode.excludeBegin) {\n\t mode_buffer += lexeme;\n\t }\n\t processBuffer();\n\t if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n\t mode_buffer = lexeme;\n\t }\n\t }\n\t startNewMode(new_mode, lexeme);\n\t return new_mode.returnBegin ? 0 : lexeme.length;\n\t }\n\n\t var end_mode = endOfMode(top, lexeme);\n\t if (end_mode) {\n\t var origin = top;\n\t if (origin.skip) {\n\t mode_buffer += lexeme;\n\t } else {\n\t if (!(origin.returnEnd || origin.excludeEnd)) {\n\t mode_buffer += lexeme;\n\t }\n\t processBuffer();\n\t if (origin.excludeEnd) {\n\t mode_buffer = lexeme;\n\t }\n\t }\n\t do {\n\t if (top.className) {\n\t result += spanEndTag;\n\t }\n\t if (!top.skip) {\n\t relevance += top.relevance;\n\t }\n\t top = top.parent;\n\t } while (top !== end_mode.parent);\n\t if (end_mode.starts) {\n\t startNewMode(end_mode.starts, '');\n\t }\n\t return origin.returnEnd ? 0 : lexeme.length;\n\t }\n\n\t if (isIllegal(lexeme, top))\n\t throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n\t /*\n\t Parser should not reach this point as all types of lexemes should be caught\n\t earlier, but if it does due to some bug make sure it advances at least one\n\t character forward to prevent infinite looping.\n\t */\n\t mode_buffer += lexeme;\n\t return lexeme.length || 1;\n\t }\n\n\t var language = getLanguage(name);\n\t if (!language) {\n\t throw new Error('Unknown language: \"' + name + '\"');\n\t }\n\n\t compileLanguage(language);\n\t var top = continuation || language;\n\t var continuations = {}; // keep continuations for sub-languages\n\t var result = '', current;\n\t for(current = top; current !== language; current = current.parent) {\n\t if (current.className) {\n\t result = buildSpan(current.className, '', true) + result;\n\t }\n\t }\n\t var mode_buffer = '';\n\t var relevance = 0;\n\t try {\n\t var match, count, index = 0;\n\t while (true) {\n\t top.terminators.lastIndex = index;\n\t match = top.terminators.exec(value);\n\t if (!match)\n\t break;\n\t count = processLexeme(value.substr(index, match.index - index), match[0]);\n\t index = match.index + count;\n\t }\n\t processLexeme(value.substr(index));\n\t for(current = top; current.parent; current = current.parent) { // close dangling modes\n\t if (current.className) {\n\t result += spanEndTag;\n\t }\n\t }\n\t return {\n\t relevance: relevance,\n\t value: result,\n\t language: name,\n\t top: top\n\t };\n\t } catch (e) {\n\t if (e.message && e.message.indexOf('Illegal') !== -1) {\n\t return {\n\t relevance: 0,\n\t value: escape(value)\n\t };\n\t } else {\n\t throw e;\n\t }\n\t }\n\t }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '';\n for(var current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(var current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n };\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, top.continuation.top) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n top.continuation.top = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var result = '';\n for(var current = top; current != language; current = current.parent) {\n if (current.className) {\n result += buildSpan(current.className, result, true);\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(var current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n };\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '';\n for(var current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(var current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n };\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, top.continuation.top) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n top.continuation.top = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className? buildSpan(mode.className, '', true): '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {parent: {value: top}});\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var result = '';\n for(var current = top; current != language; current = current.parent) {\n if (current.className) {\n result += buildSpan(current.className, result, true);\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for(var current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n };\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function unHighlight() {\n if (window.getSelection) {\n var selection = window.getSelection();\n if (selection.rangeCount) {\n\n var highlightNode = document.createElement(\"span\");\n highlightNode.setAttribute(\"id\", \"highlighted\");\n highlightNode.setAttribute(\"style\", \"background-color:#FFFF00\");\n\n var range = selection.getRangeAt(0).cloneRange();\n var node = $(range.commonAncestorContainer);\n\n var previousRange = document.createRange();\n previousRange.setStart(range.startContainer, 0);\n previousRange.setEnd(range.startContainer, range.startOffset);\n\n var nextRange = document.createRange();\n nextRange.setStart(range.endContainer, range.endOffset);\n nextRange.setEnd(range.endContainer, 0);\n\n node.unwrap();\n previousRange.surroundContents(highlightNode);\n nextRange.surroundContents(highlightNode);\n\n selection.removeAllRanges();\n selection.addRange(previousRange);\n selection.addRange(nextRange);\n }\n }\n}", "function highlightObjectOnWordTap(object) {\n highlight(object.offsetLeft, object.offsetTop, object.offsetWidth, object.offsetHeight, \"over\");\n}", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n var i, length;\n\n for (i = 0, length = mode.contains.length; i < length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n while (mode.endsParent && mode.parent) {\n mode = mode.parent;\n }\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : spanEndTag\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n var keyword_match, last_index, match, result;\n\n if (!top.keywords)\n return escape(mode_buffer);\n\n result = '';\n last_index = 0;\n top.lexemesRe.lastIndex = 0;\n match = top.lexemesRe.exec(mode_buffer);\n\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n var explicit = typeof top.subLanguage === 'string';\n if (explicit && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n\n var result = explicit ?\n highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) :\n highlightAuto(mode_buffer, top.subLanguage.length ? top.subLanguage : undefined);\n\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (explicit) {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n result += (top.subLanguage != null ? processSubLanguage() : processKeywords());\n mode_buffer = '';\n }\n\n function startNewMode(mode) {\n result += mode.className ? buildSpan(mode.className, '', true) : '';\n top = Object.create(mode, { parent: { value: top } });\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n\n if (lexeme == null) {\n processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n if (new_mode.skip) {\n mode_buffer += lexeme;\n } else {\n if (new_mode.excludeBegin) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (!new_mode.returnBegin && !new_mode.excludeBegin) {\n mode_buffer = lexeme;\n }\n }\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (origin.skip) {\n mode_buffer += lexeme;\n } else {\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n processBuffer();\n if (origin.excludeEnd) {\n mode_buffer = lexeme;\n }\n }\n do {\n if (top.className) {\n result += spanEndTag;\n }\n if (!top.skip) {\n relevance += top.relevance;\n }\n top = top.parent;\n } while (top !== end_mode.parent);\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '', current;\n for (current = top; current !== language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for (current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += spanEndTag;\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message && e.message.indexOf('Illegal') !== -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function makeHighlightHTML(baseText, docAstart, docAend, textA, textB) {\n\t\tvar highlightString = \"\";\n\t\t\n\t\tvar t = baseText.replace(/<DELETED>/g, \" \");\n\t\tt = t.replace(/<\\/DELETED>/g, \" \");\n\t\tt = t.replace(/[\\W|_]/g,\" \");\n\t\tt = t.toLowerCase();\n\t\t\n\t\tvar lastMismatched = false;\n\t\tvar mInd = 0;\n\t\tvar bInd = docAstart;\n\t\twhile (mInd < textA.length && bInd < docAend) {\n\t\t\t//skip gaps in the textA match\n\t\t\tif (textA[mInd] == '-') {\n\t\t\t\tmInd++;\n\t\t\t} else if (t[bInd] == '\\\\') {\n\t\t\t\tbInd++;\n\t\t\t//skip extra characters in the original text (likely stripped out punctuation)\n\t\t\t} else if (textA[mInd] != t[bInd]) {\n\t\t\t\thighlightString = highlightString + baseText[bInd];\n\t\t\t\tbInd++;\n\t\t\t//we got a mismatch\n\t\t\t} else if (textB[mInd] == '-' || textA[mInd] != textB[mInd]) {\n\t\t\t\tif (!lastMismatched) {\n\t\t\t\t\thighlightString = highlightString + \"<span style='background-color: \" + mismatchColor + \"'>\";\n\t\t\t\t}\n\t\t\t\thighlightString = highlightString + baseText[bInd];\n\t\t\t\tmInd++;\n\t\t\t\tbInd++;\n\t\t\t\tlastMismatched = true;\n\t\t\t//the characters matched\n\t\t\t} else {\n\t\t\t\tif (lastMismatched) {\n\t\t\t\t\thighlightString = highlightString + \"</span>\";\n\t\t\t\t}\n\t\t\t\thighlightString = highlightString + baseText[bInd];\n\t\t\t\tmInd++;\n\t\t\t\tbInd++;\n\t\t\t\tlastMismatched = false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn highlightString;\n\t}", "function highlight(source, indices, fn) {\r\n // Set up the result array.\r\n var result = [];\r\n // Set up the counter variables.\r\n var k = 0;\r\n var last = 0;\r\n var n = indices.length;\r\n // Iterator over each index.\r\n while (k < n) {\r\n // Set up the chunk indices.\r\n var i = indices[k];\r\n var j = indices[k];\r\n // Advance the right chunk index until it's non-contiguous.\r\n while (++k < n && indices[k] === j + 1) {\r\n j++;\r\n }\r\n // Extract the unmatched text.\r\n if (last < i) {\r\n result.push(source.slice(last, i));\r\n }\r\n // Extract and highlight the matched text.\r\n if (i < j + 1) {\r\n result.push(fn(source.slice(i, j + 1)));\r\n }\r\n // Update the last visited index.\r\n last = j + 1;\r\n }\r\n // Extract any remaining unmatched text.\r\n if (last < source.length) {\r\n result.push(source.slice(last));\r\n }\r\n // Return the highlighted result.\r\n return result;\r\n }", "function highlight2(code) {\n return code.replace(/(F+)/g,'<span style=\"color: pink\">$1</span>').\n replace(/(L+)/g,'<span style=\"color: red\">$1</span>').\n replace(/(R+)/g,'<span style=\"color: green\">$1</span>').\n replace(/(\\d+)/g,'<span style=\"color: orange\">$1</span>');\n}", "function highlightMultiple(start, end, passage, id) {\n // ignore margins between elements\n $(passage).find('#selection').contents().unwrap();\n if(start.is(end)) { // single element\n $(start).wrapAll(\"<span class='term event\" + id + \"term' id='selection'/>\");\n } else { // if range of elements\n if($(passage).find('span').index(start) > $(passage).find('span').index(end)) { // swap if end is before start\n var temp = end;\n end = start;\n start = temp;\n }\n \n \n if(!start.parent().not($('#selection')).is(end.parent().not($('#selection')))) {\n // common parent element\n var common = end.parents().not($('#selection')).has(start).first();\n \n if(start.parent('.term').not(common).length) { // if word has a parent term\n start = $(common).children().has(start);\n // $(start).parent('.term');\n }\n \n if(end.parent('.term').not(common).length) {\n end = $(common).children().has(end);\n //end = $(end).parent('.term');\n }\n }\n // highlight range\n $(start).nextUntil(end.next()).andSelf().wrapAll(\"<span class='term event\" + id + \"term' id='selection' />\");\n }\n }", "clearHighlights() {\n\t\tvar t = this;\n\t\tvar len = t.getLength();\n\t\tfor (var x = 0; x < len; x++) {\n\t\t\tt.getRow(x).classList.remove(\"highlight\");\n\t\t}\n\t}", "function highlightResult(item) {\n\n \n\n _highlightResult(item);\n\n \n\n }", "function highlight(part, i){\n document.getElementById(\"myAnimation\"+i).innerHTML = fiveWords[i-1];\n var inputText = document.getElementById(\"myAnimation\"+i);\n var innerHTML = inputText.innerHTML;\n var highlightedPart = innerHTML.substring(0, part.length);\n var restOfWord = innerHTML.substring(part.length, innerHTML.length);\n \n innerHTML = \"<span class='highlight'>\" + highlightedPart + \"</span>\" + restOfWord;\n inputText.innerHTML = innerHTML;\n \n// if(highlightedPart.localeCompare(fiveWords[i-1]) == 0){\n// document.getElementById(\"myAnimation\"+i).innerHTML = fiveWords[i-1]; \n// }\n}", "function hiliteElement(elm, wordsArray) {\n if (!wordsArray || elm.childNodes.length == 0)\n return;\n\n var qre_inse_parts = new Array(); // insensitive words\n var qre_sens_parts = new Array(); // sensitive words\n for (var i = 0; i < wordsArray.length; i ++) {\n word = wordsArray[i] //.toLowerCase();\n if (word.length > 2 && word[0] == \"\\\"\" && word[word.length - 1] == \"\\\"\")\n qre_sens_parts.push('\\\\b' + normalizeWords(word.slice(1, word.length - 1)) + '\\\\b');\n else if (exact)\n qre_inse_parts.push('\\\\b' + normalizeWords(word) + '\\\\b');\n else \n qre_inse_parts.push(normalizeWords(word));\n }\n\n qre_inse = new RegExp(qre_inse_parts.join(\"|\"), \"i\");\n qre_sens = new RegExp(qre_sens_parts.join(\"|\"));\n if(debug) {\n console.log(qre_inse);\n console.log(qre_sens);\n }\n\n curColor = 0\n\n var textproc = function(node) {\n function paintPearlFound(val, pos) { \n var node2 = node.splitText(pos);\n var node3 = node2.splitText(val.length);\n var span = node.ownerDocument.createElement('FONT');\n\n node.parentNode.replaceChild(span, node2);\n span.className = 'pearl-hilighted-word';\n if (!wordsColors[val]) {\n wordsColors[val] = colors[curColor];\n curColor = (curColor + 1) % colors.length;\n } \n span.style.color = wordsColors[val][0]; \n span.style.background = wordsColors[val][1];\n\n span.appendChild(node2);\n hilightedNodes[hilightedNodes.length] = span; \n total++;\n return span;\n }\n var inse_match = qre_inse.exec(node.data);\n var sens_match = qre_sens.exec(node.data);\n var inse_matched = (inse_match !== null && inse_match[0].length > 0);\n var sens_matched = (sens_match !== null && sens_match[0].length > 0);\n \n if (inse_matched && !sens_matched || \n (inse_matched && sens_matched &&\n inse_match.index <= sens_match.index)) { \n return paintPearlFound(inse_match[0].toLowerCase(), inse_match.index);\n } else if (sens_matched) {\n return paintPearlFound(sens_match[0].toLowerCase(), sens_match.index); \n }\n return node;\n };\n walkElements(elm.childNodes[0], 1, textproc); \n}", "function highlight(name, value, ignore_illegals, continuation) {\n\n function subMode(lexeme, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n if (testRe(mode.contains[i].beginRe, lexeme)) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode, lexeme) {\n if (testRe(mode.endRe, lexeme)) {\n return mode;\n }\n if (mode.endsWithParent) {\n return endOfMode(mode.parent, lexeme);\n }\n }\n\n function isIllegal(lexeme, mode) {\n return !ignore_illegals && testRe(mode.illegalRe, lexeme);\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n return mode.keywords.hasOwnProperty(match_str) && mode.keywords[match_str];\n }\n\n function buildSpan(classname, insideSpan, leaveOpen, noPrefix) {\n var classPrefix = noPrefix ? '' : options.classPrefix,\n openSpan = '<span class=\"' + classPrefix,\n closeSpan = leaveOpen ? '' : '</span>';\n\n openSpan += classname + '\">';\n\n return openSpan + insideSpan + closeSpan;\n }\n\n function processKeywords() {\n if (!top.keywords)\n return escape(mode_buffer);\n var result = '';\n var last_index = 0;\n top.lexemesRe.lastIndex = 0;\n var match = top.lexemesRe.exec(mode_buffer);\n while (match) {\n result += escape(mode_buffer.substr(last_index, match.index - last_index));\n var keyword_match = keywordMatch(top, match);\n if (keyword_match) {\n relevance += keyword_match[1];\n result += buildSpan(keyword_match[0], escape(match[0]));\n } else {\n result += escape(match[0]);\n }\n last_index = top.lexemesRe.lastIndex;\n match = top.lexemesRe.exec(mode_buffer);\n }\n return result + escape(mode_buffer.substr(last_index));\n }\n\n function processSubLanguage() {\n if (top.subLanguage && !languages[top.subLanguage]) {\n return escape(mode_buffer);\n }\n var result = top.subLanguage ? highlight(top.subLanguage, mode_buffer, true, continuations[top.subLanguage]) : highlightAuto(mode_buffer);\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (top.relevance > 0) {\n relevance += result.relevance;\n }\n if (top.subLanguageMode == 'continuous') {\n continuations[top.subLanguage] = result.top;\n }\n return buildSpan(result.language, result.value, false, true);\n }\n\n function processBuffer() {\n return top.subLanguage !== undefined ? processSubLanguage() : processKeywords();\n }\n\n function startNewMode(mode, lexeme) {\n var markup = mode.className ? buildSpan(mode.className, '', true) : '';\n if (mode.returnBegin) {\n result += markup;\n mode_buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexeme) + markup;\n mode_buffer = '';\n } else {\n result += markup;\n mode_buffer = lexeme;\n }\n top = Object.create(mode, {\n parent: {\n value: top\n }\n });\n }\n\n function processLexeme(buffer, lexeme) {\n\n mode_buffer += buffer;\n if (lexeme === undefined) {\n result += processBuffer();\n return 0;\n }\n\n var new_mode = subMode(lexeme, top);\n if (new_mode) {\n result += processBuffer();\n startNewMode(new_mode, lexeme);\n return new_mode.returnBegin ? 0 : lexeme.length;\n }\n\n var end_mode = endOfMode(top, lexeme);\n if (end_mode) {\n var origin = top;\n if (!(origin.returnEnd || origin.excludeEnd)) {\n mode_buffer += lexeme;\n }\n result += processBuffer();\n do {\n if (top.className) {\n result += '</span>';\n }\n relevance += top.relevance;\n top = top.parent;\n } while (top != end_mode.parent);\n if (origin.excludeEnd) {\n result += escape(lexeme);\n }\n mode_buffer = '';\n if (end_mode.starts) {\n startNewMode(end_mode.starts, '');\n }\n return origin.returnEnd ? 0 : lexeme.length;\n }\n\n if (isIllegal(lexeme, top))\n throw new Error('Illegal lexeme \"' + lexeme + '\" for mode \"' + (top.className || '<unnamed>') + '\"');\n\n /*\n Parser should not reach this point as all types of lexemes should be caught\n earlier, but if it does due to some bug make sure it advances at least one\n character forward to prevent infinite looping.\n */\n mode_buffer += lexeme;\n return lexeme.length || 1;\n }\n\n var language = getLanguage(name);\n if (!language) {\n throw new Error('Unknown language: \"' + name + '\"');\n }\n\n compileLanguage(language);\n var top = continuation || language;\n var continuations = {}; // keep continuations for sub-languages\n var result = '',\n current;\n for (current = top; current != language; current = current.parent) {\n if (current.className) {\n result = buildSpan(current.className, '', true) + result;\n }\n }\n var mode_buffer = '';\n var relevance = 0;\n try {\n var match, count, index = 0;\n while (true) {\n top.terminators.lastIndex = index;\n match = top.terminators.exec(value);\n if (!match)\n break;\n count = processLexeme(value.substr(index, match.index - index), match[0]);\n index = match.index + count;\n }\n processLexeme(value.substr(index));\n for (current = top; current.parent; current = current.parent) { // close dangling modes\n if (current.className) {\n result += '</span>';\n }\n }\n return {\n relevance: relevance,\n value: result,\n language: name,\n top: top\n };\n } catch (e) {\n if (e.message.indexOf('Illegal') != -1) {\n return {\n relevance: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function highlight(language_name, value) {\n\n function subMode(lexem, mode) {\n for (var i = 0; i < mode.contains.length; i++) {\n var match = mode.contains[i].beginRe.exec(lexem);\n if (match && match.index == 0) {\n return mode.contains[i];\n }\n }\n }\n\n function endOfMode(mode_index, lexem) {\n if (modes[mode_index].end && modes[mode_index].endRe.test(lexem))\n return 1;\n if (modes[mode_index].endsWithParent) {\n var level = endOfMode(mode_index - 1, lexem);\n return level ? level + 1 : 0;\n }\n return 0;\n }\n\n function isIllegal(lexem, mode) {\n return mode.illegal && mode.illegalRe.test(lexem);\n }\n\n function eatModeChunk(value, index) {\n var mode = modes[modes.length - 1];\n if (mode.terminators) {\n mode.terminators.lastIndex = index;\n return mode.terminators.exec(value);\n }\n }\n\n function keywordMatch(mode, match) {\n var match_str = language.case_insensitive ? match[0].toLowerCase() : match[0];\n var value = mode.keywords[match_str];\n if (value && value instanceof Array)\n return value;\n return false;\n }\n\n function processKeywords(buffer, mode) {\n buffer = escape(buffer);\n if (!mode.keywords)\n return buffer;\n var result = '';\n var last_index = 0;\n mode.lexemsRe.lastIndex = 0;\n var match = mode.lexemsRe.exec(buffer);\n while (match) {\n result += buffer.substr(last_index, match.index - last_index);\n var keyword_match = keywordMatch(mode, match);\n if (keyword_match) {\n keyword_count += keyword_match[1];\n result += '<span class=\"'+ keyword_match[0] +'\">' + match[0] + '</span>';\n } else {\n result += match[0];\n }\n last_index = mode.lexemsRe.lastIndex;\n match = mode.lexemsRe.exec(buffer);\n }\n return result + buffer.substr(last_index);\n }\n\n function processSubLanguage(buffer, mode) {\n var result;\n if (mode.subLanguage == '') {\n result = highlightAuto(buffer);\n } else {\n result = highlight(mode.subLanguage, buffer);\n }\n // Counting embedded language score towards the host language may be disabled\n // with zeroing the containing mode relevance. Usecase in point is Markdown that\n // allows XML everywhere and makes every XML snippet to have a much larger Markdown\n // score.\n if (mode.relevance > 0) {\n keyword_count += result.keyword_count;\n relevance += result.relevance;\n }\n return '<span class=\"' + result.language + '\">' + result.value + '</span>';\n }\n\n function processBuffer(buffer, mode) {\n if (mode.subLanguage && languages[mode.subLanguage] || mode.subLanguage == '') {\n return processSubLanguage(buffer, mode);\n } else {\n return processKeywords(buffer, mode);\n }\n }\n\n function startNewMode(mode, lexem) {\n var markup = mode.className? '<span class=\"' + mode.className + '\">': '';\n if (mode.returnBegin) {\n result += markup;\n mode.buffer = '';\n } else if (mode.excludeBegin) {\n result += escape(lexem) + markup;\n mode.buffer = '';\n } else {\n result += markup;\n mode.buffer = lexem;\n }\n modes.push(mode);\n relevance += mode.relevance;\n }\n\n function processModeInfo(buffer, lexem) {\n var current_mode = modes[modes.length - 1];\n if (lexem === undefined) {\n result += processBuffer(current_mode.buffer + buffer, current_mode);\n return;\n }\n\n var new_mode = subMode(lexem, current_mode);\n if (new_mode) {\n result += processBuffer(current_mode.buffer + buffer, current_mode);\n startNewMode(new_mode, lexem);\n return new_mode.returnBegin;\n }\n\n var end_level = endOfMode(modes.length - 1, lexem);\n if (end_level) {\n var markup = current_mode.className?'</span>':'';\n if (current_mode.returnEnd) {\n result += processBuffer(current_mode.buffer + buffer, current_mode) + markup;\n } else if (current_mode.excludeEnd) {\n result += processBuffer(current_mode.buffer + buffer, current_mode) + markup + escape(lexem);\n } else {\n result += processBuffer(current_mode.buffer + buffer + lexem, current_mode) + markup;\n }\n while (end_level > 1) {\n markup = modes[modes.length - 2].className?'</span>':'';\n result += markup;\n end_level--;\n modes.length--;\n }\n var last_ended_mode = modes[modes.length - 1];\n modes.length--;\n modes[modes.length - 1].buffer = '';\n if (last_ended_mode.starts) {\n startNewMode(last_ended_mode.starts, '');\n }\n return current_mode.returnEnd;\n }\n\n if (isIllegal(lexem, current_mode))\n throw 'Illegal';\n }\n\n var language = languages[language_name];\n compileLanguage(language);\n var modes = [language];\n language.buffer = '';\n var relevance = 0;\n var keyword_count = 0;\n var result = '';\n try {\n var match, index = 0;\n while (true) {\n match = eatModeChunk(value, index);\n if (!match)\n break;\n var return_lexem = processModeInfo(value.substr(index, match.index - index), match[0]);\n index = match.index + (return_lexem ? 0 : match[0].length);\n }\n processModeInfo(value.substr(index), undefined);\n return {\n relevance: relevance,\n keyword_count: keyword_count,\n value: result,\n language: language_name\n };\n } catch (e) {\n if (e == 'Illegal') {\n return {\n relevance: 0,\n keyword_count: 0,\n value: escape(value)\n };\n } else {\n throw e;\n }\n }\n }", "function getHighlights(url) {\n $.get(baseUrl + \"/tags/highlights\", {\n \"url\": url,\n }).done(function(res) {\n if (res.success) {\n for (var h in res.highlights) {\n var hl = decodeURIComponent(h);\n var hl_id = res.highlights[h].id;\n\n var max_tag = res.highlights[h].max_tag;\n var is_owner = res.highlights[h].is_owner;\n var entire_highlight_present = true;\n var html = $.parseHTML(hl);\n\n var all_eligible = $.merge($(\"p\"), $(\"div\"));\n var last = null;\n\n if ($(\"body\").html().indexOf(hl) === -1) {\n all_eligible.filter(function () {\n if (/&nbsp;/gi.test($(this).html())) {\n if ($(this).html().replace(/&nbsp;/gi,'').indexOf(hl) > -1) {\n if (last === null || $(this).children().length < last.children().length) {\n last = $(this);\n }\n }\n }\n });\n last.html(last.html().replace(hl, \"<div class='highlight-annote' highlight='\" + hl_id + \"'>\"+hl+\"</div>\")); \n } else {\n var base = $('p:contains(\"' + html[0].textContent + '\"):last');\n base.html(base.html().replace(hl, \"<div class='highlight-annote' highlight='\" + hl_id + \"'>\"+hl+\"</div>\"));\n }\n\n $(\".highlight-annote[highlight='\"+hl_id+\"']\").css({\n \"background-color\": muteColor(max_tag[1]),\n \"display\": \"inline\",\n });\n $(\".highlight-annote[highlight='\"+hl_id+\"']\").attr(\"color\", muteColor(max_tag[1]));\n\n highlight_colors[hl_id] = muteColor(max_tag[1]);\n\n $(\".highlight-annote\").attr(\"is_owner\", is_owner);\n }\n } \n });\n}", "highlight_move(args) {\n\n }", "function grayOutMatch(text, reg) {\n return replaceMatch(text, reg, chalk_1.default.gray.dim);\n}", "function SearchDoc_HighlightAllOccurencesOfStringForElement(element,keyword) {\n if (element) \n {\n if (element.nodeType == 3) \n { // Text node\n while (true) \n {\n var value = element.nodeValue; // Search for keyword in text node\n var idx = value.toLowerCase().indexOf(keyword);\n\n if (idx < 0) break; // not found, abort\n\n var span = document.createElement(\"span\");\n var text = document.createTextNode(value.substr(idx,keyword.length));\n span.appendChild(text);\n span.setAttribute(\"class\",\"MyAppHighlight\");\n span.style.backgroundColor=\"yellow\";\n span.style.color=\"black\";\n text = document.createTextNode(value.substr(idx+keyword.length));\n element.deleteData(idx, value.length - idx);\n var next = element.nextSibling;\n element.parentNode.insertBefore(span, next);\n element.parentNode.insertBefore(text, next);\n element = text;\n SearchDoc_SearchResultCount++;\t// update the counter\n }\n } \n else if (element.nodeType == 1) \n { // Element node\n if (element.style.display != \"none\" && element.nodeName.toLowerCase() != 'select') {\n for (var i=element.childNodes.length-1; i>=0; i--) \n {\n SearchDoc_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);\n }\n }\n } //else element node\n } //element not nil\n}", "function highlight(props){\n //change stroke\n var selected = d3.selectAll(\".\" + props.adm1_code)\n .style(\"stroke\", \"#62030F\")\n .style(\"stroke-width\", \"3\");\n\n setLabel(props);\n } //last line of highlight function", "function hSeq(seq) {\n\t\t/** unhighlight all others */\n\t\tfor (var i=0; i<sequences.length; i++)\n\t\t\thmatch(sequences[i], false);\n\t\t/** highlight selected sequence */\n\t\thmatch(sequences[seq], true);\t\n\t}", "function hSeq(seq) {\n\t\t/** unhighlight all others */\n\t\tfor (var i=0; i<sequences.length; i++)\n\t\t\thmatch(sequences[i], false);\n\t\t/** highlight selected sequence */\n\t\thmatch(sequences[seq], true);\t\n\t}", "function MyApp_HighlightAllOccurencesOfString(keyword) {\n// alert(keyword);\n\nMyApp_RemoveAllHighlights();\nMyApp_HighlightAllOccurencesOfStringForElement(document.body,\n\t\tkeyword.toLowerCase());\n}", "function highlightSelection(e) \n{\n selection = window.getSelection();\n \n //Skip this section if mouse event is undefined\n if (e != undefined)\n {\n \n //Ignore right clicks; avoids odd behavior with CTRL key\n if (e.button == 2)\n {\n return;\n }\n\n //Exit if CTRL key is held while auto highlight is checked on\n if(imedBool && e.ctrlKey)\n {\n return;\n }\n \n //Exit if CTRL key not held and auto highlight is checked off\n if(!imedBool && !e.ctrlKey)\n {\n return;\n }\n }\n \n var selectionTagName;\n //Avoid inputs like the plague..\n try {\n selectionTagName = selection.anchorNode.childNodes[0].tagName.toLowerCase();\n } catch (err) {\n //fail silently :-D\n }\n if (selectionTagName == \"input\") {\n return;\n }\n \n // Clear all highlights if requested\n if (clearBetweenSelections && highlightedPage == true)\n {\n clearHighlightsOnPage();\n }\n \n var selectedText = window.getSelection().toString().replace(/^\\s+|\\s+$/g, \"\");\n var testText = selectedText.toLowerCase();\n \n //Exit if selection is whitespace or what was previously selected\n if (selectedText == '' || lastText == testText)\n {\n return;\n }\n \n if (selection.toString() != '') {\n var mySpan = document.createElement(\"span\");\n var prevSpan = document.getElementById(\"mySelectedSpan\");\n if (prevSpan != null) {\n prevSpan.removeAttribute(\"id\");\n }\n mySpan.id = \"mySelectedSpan\";\n var range = selection.getRangeAt(0).cloneRange();\n mySpan.appendChild(range.extractContents());\n range.insertNode(mySpan);\n }\n \n //Perform highlighting\n localSearchHighlight(selectedText, singleSearch);\n highlightedPage = true;\n \n //Store processed selection for next time this method is called\n lastText = testText;\n if (selection.toString() != '') {\n if (!triggeredOnce) {\n triggeredOnce = !triggeredOnce;\n }\n }\n}", "function hlsSyntax(regex) {\n\t\t$(\"#demo-1\").highlight(regex);\n }", "function highlight(text, terms) {\n var index = text.toLowerCase().indexOf(terms.toLowerCase());\n // the terms could not exist in the text at all\n if (index < 0) {\n return text;\n }\n var pre = text.substring(0, index);\n var mid = text.substring(index, index + terms.length);\n var post = text.substring(index + terms.length, text.length);\n return [].concat(pre, \"<strong>\", mid, \"</strong>\", post).join(\"\");\n}", "function highlight(text, style) {\n var page_html = document.getElementById('page').innerHTML;\n var page = document.getElementById('page');\n var draft_html = document.getElementById('draft').innerHTML;\n var draft = document.getElementById('draft');\n text = text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); //https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex\n\n var re = new RegExp(text, 'g');\n var m;\n\n if (text.length > 0) {\n page.innerHTML = page_html.replace(re, `<span style='background-color:${style};'>$&</span>`);\n draft.innerHTML = draft_html.replace(re, `<span style='background-color:${style};'>$&</span>`);\n\n } else {\n page.innerHTML = page_html;\n draft.innerHTML = draft_html;\n }\n }" ]
[ "0.74854064", "0.7059232", "0.69366884", "0.6896546", "0.6806591", "0.67445165", "0.6729877", "0.6652738", "0.6623489", "0.65778184", "0.6573902", "0.6482448", "0.64426565", "0.63798726", "0.63251483", "0.625088", "0.6231483", "0.6223302", "0.6188613", "0.6187376", "0.6173059", "0.61593735", "0.61582965", "0.61370265", "0.61279535", "0.6105606", "0.6104723", "0.610232", "0.6099884", "0.60934836", "0.6066454", "0.6066228", "0.6060433", "0.60298026", "0.6022996", "0.60050994", "0.60016453", "0.59965944", "0.59650624", "0.59593964", "0.5955197", "0.59503853", "0.5948699", "0.5948699", "0.5948699", "0.5936169", "0.5936111", "0.5936111", "0.5936111", "0.5936111", "0.5936111", "0.5936111", "0.5935382", "0.5935382", "0.5933102", "0.5921082", "0.5920328", "0.5911484", "0.590761", "0.5903825", "0.5903597", "0.589628", "0.5891136", "0.58830565", "0.58830565", "0.58830565", "0.58830565", "0.5881979", "0.5879234", "0.58743167", "0.5868291", "0.5868291", "0.5868291", "0.5868291", "0.58553046", "0.5848558", "0.5843125", "0.5824228", "0.58130383", "0.57931626", "0.5763705", "0.5759078", "0.5749869", "0.57496905", "0.5737722", "0.57287383", "0.57241094", "0.57204705", "0.57189333", "0.5718285", "0.5714642", "0.5709934", "0.56977177", "0.56977177", "0.56955975", "0.5692508", "0.56872267", "0.5680874", "0.56772846" ]
0.6758682
6
generate list of all homophones for each unique plaintext letter in the 408 solution
function homophonesFor408() { var d = interestingHash[1][0]["decoder"]; var u = {}; for (i=0;i<alphabet[1].length; i++) { var symbol = alphabet[1][i]; var plaintext = d[i]; if (u[plaintext]) u[plaintext].push(symbol); else u[plaintext] = [symbol]; } return u; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "get uniqueLettersInPhrase() {\n let uniqueLetters = \"\";\n\n for (let letter of this.phrase) {\n if (uniqueLetters.indexOf(this.phrase) === -1 && letter !== ' ') {\n uniqueLetters += letter;\n }\n }\n\n return uniqueLetters;\n }", "getLettersToBeGuessed() {\r\n let uniqueLetters = new Array();\r\n for (let i = 0; i < this.text.length; i++) {\r\n if (!uniqueLetters.includes(this.text.charAt(i)) && Utilities.alphabet.includes(this.text.charAt(i).toLowerCase())) {\r\n uniqueLetters.push(this.text.charAt(i));\r\n }\r\n }\r\n uniqueLetters.sort();\r\n return uniqueLetters;\r\n }", "function part2(data) {\n let items = data\n .map(answer => {\n let sorted = answer.join('').split('').sort().join('');\n let letterGroups = sorted.match(/(\\S)\\1*/g);\n return letterGroups.filter(letterGroup => letterGroup.length == answer.length).length;\n })\n .reduce((acc, cur) => acc + cur);\n return items;\n}", "function groupAnagrams(words) {\n // Write your code here.\n // hashtables are the thing that comes to my mind\n // store each number with its own individual object/hashtable\n // ahastable will contain the letters with the index\n // I Iterate once to store\n // then iterate again to compare and push into similar arrays togethor \n\n\n }", "function gen_words_array(num_words) { \r\n\r\n\tvar word = \"\";\r\n var possible_char = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\r\n var array_words =[];\r\n\r\n for (var i = 0; i < num_words; i++) {\r\n \t//console.log(i);\r\n num_letters = Math.floor(Math.random() * (10) + 1);\r\n //console.log(num_letters);\r\n for (var x= 0; x < num_letters; x++) {\r\n \tramdom_letter = \r\n \tword += possible_char.substr( Math.floor(Math.random() * (61)), 1);\r\n }\r\n array_words.push(word);\r\n word = \"\";\r\n }\r\n return array_words;\r\n}", "function hachage(chaine) {\n let condensat = 0;\n \n for (let i = 0; i < chaine.length; i++) {\n condensat = (condensat +chaine.charCodeAt(i) * 3 ** i) % 65536;\n }\n \n return condensat;\n}", "pronounceable(pwl) {\n let output = '';\n let c1;\n let c2;\n let c3;\n let sum = 0;\n let nchar;\n let ranno;\n // let pwnum;\n let pik;\n\n const alphabet = 'abcdefghijklmnopqrstuvwxyz';\n\n // letter frequencies\n const trigram = data;\n // Pick a random starting point.\n pik = Math.random(); // random number [0,1]\n ranno = pik * 125729.0;\n sum = 0;\n for (c1 = 0; c1 < 26; c1++) {\n for (c2 = 0; c2 < 26; c2++) {\n for (c3 = 0; c3 < 26; c3++) {\n sum += trigram[c1][c2][c3];\n if (sum > ranno) {\n output += alphabet.charAt(c1);\n output += alphabet.charAt(c2);\n output += alphabet.charAt(c3);\n c1 = 26; // Found start. Break all 3 loops.\n c2 = 26;\n c3 = 26;\n } // if sum\n } // for c3\n } // for c2\n } // for c1\n // Now do a random walk.\n nchar = 3;\n while (nchar < pwl) {\n c1 = alphabet.indexOf(output.charAt(nchar - 2));\n c2 = alphabet.indexOf(output.charAt(nchar - 1));\n sum = 0;\n for (c3 = 0; c3 < 26; c3++) {\n sum += trigram[c1][c2][c3];\n }\n if (sum === 0) {\n // alert(\"sum was 0, outut=\"+output);\n break; // exit while loop\n }\n // pik = ran.nextDouble();\n pik = Math.random();\n ranno = pik * sum;\n sum = 0;\n for (c3 = 0; c3 < 26; c3++) {\n sum += trigram[c1][c2][c3];\n if (sum > ranno) {\n output += alphabet.charAt(c3);\n c3 = 26; // break for loop\n } // if sum\n } // for c3\n nchar++;\n } // while nchar\n\n return output;\n }", "function generateAll(str) {\n //build an output\n //separate chars into 1 and 1, 2 and 2 and so on\n let myStr = [];\n //separated 1 and 1\n for (let i = 0, j = 1; i < str.length; i++, j++) {\n // myStr.push(str[i]);\n myStr[i] = str.substring(i, j);\n }\n let kosing = [];\n let temp = \"\";\n let sizes = Math.pow(2, myStr.length);\n\n for (let j = 0; j < sizes; j++) {\n temp = \"\";\n for (let k = 0; k < myStr.length; k++) {\n if ((j & Math.pow(2, k))) {\n temp += myStr[k];\n }\n\n }\n if (temp !== \"\") {\n kosing.push(temp);\n }\n // str[j];\n\n }\n kosing.join(\"\\n\");\n return kosing;\n}", "function powerSet(str) {\n let obj = {}\n //This loop is to take out all duplicate number/letter\n for(let i=0;i<str.length; i++){\n obj[str[i]] = true;\n }\n //variable array will have no duplicates\n let array = Object.keys(obj);\n let result = [[]];\n for(let i=0; i<array.length ;i++){\n //this line is crucial! It prevents us from infinite loop\n let len = result.length; \n for(let x=0; x<len ;x++){\n result.push(result[x].concat(array[i]))\n }\n }\nreturn result;\n}", "function getRandomPhraseAsArray(phr) {\n const randomPhrase = phr[Math.floor(Math.random()*phr.length)];\n const splitRandomPhrase = randomPhrase.split(\"\");\n return splitRandomPhrase;\n}", "function getRandomPhraseAsArray(arr) {\n var a = arr[Math.floor(Math.random() * 6)];\n const b = [];\n \n for (let i = 0; i < a.length; i++) {\n b.push(a.charAt(i));\n }\n\n return b\n}", "get uniqueHiddenLettersInPhrase() {\n const letterElements = document.getElementsByClassName('letter');\n let uniqueHiddenLetters = '';\n\n for (let letterElement of letterElements) {\n if (uniqueHiddenLetters.indexOf(letterElement.textContent) === -1 && letterElement.classList.contains('hide')) {\n uniqueHiddenLetters += letterElement.textContent;\n }\n }\n return uniqueHiddenLetters;\n }", "function generateLetterDistribution(json) {\n let distri = [];\n for (var i = 0; i < 27; i++) {\n for (var j = 0; j < json.pieces[i].amount; j++) {\n distri.push(json.pieces[i].letter);\n }\n }\n return distri;\n }", "hash (affected_permutation, affected_orientation) {\n var defaultAffected = () => {\n return {\n corners: [0, 1, 2, 3, 4, 5, 6, 7, 8],\n edges: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],\n centers: [0, 1, 2, 3, 4, 5]\n }\n }\n\n if (affected_permutation == undefined) affected_permutation = defaultAffected()\n if (affected_orientation == undefined) affected_orientation = defaultAffected()\n\n var hashString = ''\n for (var i in this.ep) {\n if (affected_permutation.hasOwnProperty('edges') && affected_permutation.edges.indexOf(this.ep[i]) >= 0) {\n hashString += String.fromCharCode(this.ep[i] + 48)\n } else hashString += String.fromCharCode(47)\n if (affected_orientation.hasOwnProperty('edges') && affected_orientation.edges.indexOf(this.ep[i]) >= 0) {\n hashString += String.fromCharCode(this.eo[i] + 48)\n } else hashString += String.fromCharCode(47)\n }\n for (var i in this.cp) {\n if (affected_permutation.hasOwnProperty('corners') && affected_permutation.corners.indexOf(this.cp[i]) >= 0) {\n hashString += String.fromCharCode(this.cp[i] + 48)\n } else hashString += String.fromCharCode(47)\n if (affected_orientation.hasOwnProperty('corners') && affected_orientation.corners.indexOf(this.co[i]) >= 0) {\n hashString += String.fromCharCode(this.co[i] + 48)\n } else hashString += String.fromCharCode(47)\n }\n for (var i in this.c) {\n if (affected_permutation.hasOwnProperty('centers') && affected_permutation.centers.indexOf(this.c[i]) >= 0) {\n hashString += String.fromCharCode(this.c[i] + 48)\n } else hashString += String.fromCharCode(47)\n }\n\n return hashString\n }", "function anagramGroup(arr){\n const newArray=[];\n const anagramDB = new HashMap();\n arr.forEach(word=>{\n let wordVal=0;\n for(let letter of word){\n wordVal += letter.charCodeAt(0); \n }\n try{\n anagramDB.set(wordVal, [word, ...anagramDB.get(wordVal)]);\n }catch(error){\n anagramDB.set(wordVal, [word]);\n }\n wordVal=0;\n });\n\n anagramDB.slots.forEach(slot=>{\n newArray.push(slot.value);\n });\n\n\nconsole.log(newArray);\n\n}", "function ultapiramid(n) {\n let b = 65\n let mt = \"\"\n for (var i = n; i > 0; i--) {\n let s = '';\n for (var j = 0; j < i; j++) {\n s = s + String.fromCharCode(b + (j % 26)) + \" \";\n }\n console.log(mt + s);\n mt = mt + \" \"\n }\n\n mt = \"\"\n s = \"\"\n for (var i = 0; i < n; i++) {\n mt = '';\n for (var j = n - 1; j > i; j--) {\n mt = mt + \" \"\n }\n s = s + String.fromCharCode(b + (j % 26)) + \" \";\n if (i != 0)\n console.log(mt + s);\n }\n}", "function initGrid(){\n var key = document.getElementById(\"inp\").value\n grid = []\n\n // Loop through the rows computing hashes\n for (var i = 0; i < 128; i++){\n var hash = knotHash(key + \"-\" + i)\n grid[i] = tostr2(hash)\n }\n }", "function randHash() {\n var text = \"\";\n\t var possible = \"abcdefghijklmnopqrstuvwxyz0123456789\";\n var length = 7;\n \n\t for (var i = 0; i < length; i++) {\n\t\t text += possible.charAt(Math.floor(Math.random() * possible.length));\n\t }\n\t return text;\n }", "function generateSolution() {\n for (let i = 0; i < 4; i++) {\n const randomIndex = getRandomInt(0, letters.length);\n solution += letters[randomIndex];\n }\n return solution;\n }", "function toHash(text)\n {\n var hash = \"\";\n for( i = 0; i < text.length ; ++ i)\n switch(text[i])\n {\n case \"A\" : \n case \"a\" : hash = hash + \"@\";break;\n case \"B\" :\n case \"b\" : hash = hash + \"6\";break;\n case \"C\" :\n case \"c\" : hash = hash + \"(\";break;\n case \"D\" :\n case \"d\" : hash = hash + \"cl\";break;\n case \"E\" :\n case \"e\" : hash = hash + \"n\";break;\n case \"F\" :\n case \"f\" : hash = hash + \"8\";break;\n case \"G\" :\n case \"g\" : hash = hash + \"9\";break;\n case \"H\" :\n case \"h\" : hash = hash + \"#\";break;\n case \"I\" :\n case \"i\" : hash = hash + \"!\";break;\n case \"J\" :\n case \"j\" : hash = hash + \"j\";break;\n case \"K\" :\n case \"k\" : hash = hash + \"lc\";break;\n case \"L\" :\n case \"l\" : hash = hash + \"1\";break;\n case \"M\" :\n case \"m\" : hash = hash + \"nn\";break;\n case \"N\" :\n case \"n\" : hash = hash + \"e\";break;\n case \"O\" :\n case \"o\" : hash = hash + \"0\";break;\n case \"P\" :\n case \"p\" : hash = hash + \"q\";break;\n case \"Q\" :\n case \"q\" : hash = hash + \"?\";break;\n case \"R\" :\n case \"r\" : hash = hash + \"v\";break;\n case \"S\" :\n case \"s\" : hash = hash + \"5\";break;\n case \"T\" :\n case \"t\" : hash = hash + \"+\";break;\n case \"U\" :\n case \"u\" : hash = hash + \"y\";break;\n case \"V\" :\n case \"v\" : hash = hash + \"r\";break;\n case \"W\" :\n case \"w\" : hash = hash + \"uu\";break;\n case \"X\" :\n case \"x\" : hash = hash + \"*\";break;\n case \"Y\" :\n case \"y\" : hash = hash + \"T\";break;\n case \"Z\" :\n case \"z\" : hash = hash + \"7\";break;\n default :hash = hash + text[i];\n }\n return hash;\n }", "function getRandomPhraseAsArray () {\n var result= phrase[Math.floor(Math.random() * phrase.length)]; \n result = result.split(\"\");\n return result;\n}", "function extractFirstLetter(words) {\n //store all found letters to letters array variable.\n var letters = [];\n //loop through gigVoice object and push first character of each object key to letters array.\n words.forEach(function(l) {\n letters.push(l.charAt(0));\n });\n //remove any duplicate letters from letters array variable.\n return Array.from(new Set(letters));\n\n }", "function findallsolutions(grid, dictionary)\n{\n\twindow.grid = grid;\n\twindow.finaldictionary = [];\n\tdictionary.forEach(lettersplitter);\n\tconsole.log('Final Dictionary'); \n\tconsole.log(finaldictionary)\n\treturn(finaldictionary);\n}", "function getRandomPhraseAsArray (pharses) {\n \n/*\n input: pharses is an array\n\n instruction: \n 1. randomly choose a phrase from the phrases array\n a. understand how to randomly get number\n b. choose a phrase from the phrases array\n 2. split that phrase into a new array of characters. \n\n output: The function should then return the new character array.\n */\n\n let randomNumber = getRandomNumber(pharses.length)\n let randomPhrase = pharses[randomNumber].toLowerCase()\n let splitPhrase = randomPhrase.split('');\n return splitPhrase;\n}", "function main() {\n var n = parseInt(readLine());\n let counter = n;\n let hash = ''\n for (let i = 0; i < (n * n); i++){\n if ( (counter === n) && (hash.length !== n) ){\n hash += ' ';\n } else if ( (counter === n) && (hash.length === n) ){\n let split = hash.split('');\n split[split.length - 1] = '#'\n hash = split.join('');\n console.log(hash);\n counter--\n } else if ( (counter < n) && (counter !== 0) ){\n split = hash.split('');\n split[counter - 1] = '#'\n hash = split.join('');\n console.log(hash);\n counter--\n }\n }\n}", "function findSolutions(challenge) {\n return [];\n}", "function grp(eNfa, nfa)\n{var listWord=[];\n \n \n for(var i=0; i<eNfa.length; i++)\n {\n for(var j=0; j<nfa.trans.length; j++)\n {\n \n if(eNfa[i]==nfa.trans[j].src)\n {\n listWord.push({enumString: nfa.trans[j].ch, enumNfa:nfa.trans[j].dest});\n \n\n }\n }\n }\n // console.log(\"listword size: \"+ listWord.length);\n return listWord; \n \n}", "function createRandomLettersHE(len){\n var text = \"\";\n var possible = \"אבגדהוזחטיכלמנסעפצקרשת0123456789\";\n for( var i=0; i < len; i++ )\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n return text;\n}", "function gameOfThrones(s) {\n \n var set = new Set();\n var result = \"\";\n s = s.toLowerCase();\n var strArr = [...s];\n if(s.length % 2 == 0) {\n \n for(var ch of strArr) {\n if(set.has(ch)) {\n set.delete(ch);\n }else {\n set.add(ch);\n }\n }\n console.log(set);\n console.log(\"if\"+set.size);\n if(set.size == 0) {\n result = \"YES\";\n }else {\n result = \"NO\";\n }\n }else {\n for(var ch of strArr) {\n if(set.has(ch)) {\n set.delete(ch);\n }else {\n set.add(ch);\n }\n }\n console.log(set);\n console.log(\"else\"+set.size);\n if(set.size == 1) {\n result = \"YES\";\n }else {\n result = \"NO\";\n }\n \n }\n\n return result;\n\n\n}", "function KUniqueCharacters(str) { \nlet arr = [];\nlet longest = str[0];\n \nfor (let i=1; i<str.length; i++) {\n let table = {}\n let ans = \"\"\n let count = 0\n for (let j=i; j<str.length; j++) {\n if (table[str[j]] === undefined) { \n table[str[j]] = 1\n count++\n }\n if (count <= str[0]) {\n ans += str[j]\n }\n }\n if (ans.length > longest) {\n longest = ans.length\n arr.push(ans)\n }\n}\nreturn arr.sort(function(a,b) {return b.length-a.length})[0]\n}", "function isogram(word){\n\tnewArr=[];\n\t//make lower case\n\tlower = word.toLowerCase().split(\"\");\n\tconsole.log(lower);\n\n\t//cycle through word\n\tfor(var i=0; i<lower.length; i++){\n\t\t\n\t\tif(newArr.indexOf(lower[i])==-1){\n\t\t\tnewArr.push(lower[i]);\t\t\n\t\t}\n\t\telse{\n\t\t\treturn false;\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn true;\n}", "function fnHomography(out, inp, X) {\n var w = X[8] + X[2] * inp[0] + X[5] * inp[1];\n out[0] = (X[6] + X[0] * inp[0] + X[3] * inp[1]) / w;\n out[1] = (X[7] + X[1] * inp[0] + X[4] * inp[1]) / w;\n return out;\n}", "function hash(s) {\n\tlet h = 7;\n\n\tfor (let i = 0; i < s.length; i++) {\n\t\th = h * 37 + lettresPossibles.indexOf(s[i]);\n\t}\n\n\treturn h;\n}", "function hipsterfy(sentence) {\n var words = sentence.split(\" \");\n var hipsterfied = [];\n\n for(var i = 0; i < words.length; i ++){\n hipsterfied.push(hipsterfyWord(words[i]));\n }\n return hipsterfied.join(\" \");\n}", "function triGram(word){\n var set = 3;\n var arr = [];\n var words = word.toLowerCase().trim().split(\" \");\n for(key in words){\n var length = words[key].length;\n arr.push(words[key]);\n for(var i = 0; i < length-set+1; i++){\n arr.push(words[key].substring(i,i+set));\n }\n }\n //output is array\n return arr;\n}", "function getRandomPhraseAsArray(arr){\n // Remove 1 from the array length to get the max number (inclusive)\n const length = arr.length - 1;\n // Generate a random number between 0 and length\n const choose = getRandomNumber(0, length);\n const currentPhrase = arr[choose];\n // Split the phrase into array of individual characters\n const letters = currentPhrase.split('');\n return letters;\n}", "function getpyraoptscramble(mn) {\n var j = 1, b = [], g = [], f = [], d = [], e = [], k = [], h = [], i = [];\n\n function u() {\n var c, p, q, l, m;\n for (p = 0; p < 720; p++) {\n g[p] = -1;\n d[p] = [];\n for (m = 0; m < 4; m++)d[p][m] = w(p, m)\n }\n g[0] = 0;\n for (l = 0; l <= 6; l++)for (p = 0; p < 720; p++)if (g[p] == l)for (m = 0; m < 4; m++) {\n q = p;\n for (c = 0; c < 2; c++) {\n q = d[q][m];\n if (g[q] == -1)g[q] = l + 1\n }\n }\n for (p = 0; p < 2592; p++) {\n f[p] = -1;\n e[p] = [];\n for (m = 0; m < 4; m++)e[p][m] = x(p, m)\n }\n f[0] = 0;\n for (l = 0; l <= 5; l++)for (p = 0; p < 2592; p++)if (f[p] == l)for (m = 0; m < 4; m++) {\n q = p;\n for (c = 0; c < 2; c++) {\n q = e[q][m];\n if (f[q] == -1)f[q] = l + 1\n }\n }\n for (c = 0; c < j; c++) {\n k = [];\n var t = 0, s = 0;\n q = 0;\n h = [0, 1, 2, 3, 4, 5];\n for (m = 0; m < 4; m++) {\n p = m + n(6 - m);\n l = h[m];\n h[m] = h[p];\n h[p] = l;\n if (m != p)s++\n }\n if (s % 2 == 1) {\n l = h[4];\n h[4] = h[5];\n h[5] = l\n }\n s = 0;\n i = [];\n for (m = 0; m < 5; m++) {\n i[m] = n(2);\n s += i[m]\n }\n i[5] = s % 2;\n for (m = 6; m < 10; m++) {\n i[m] = n(3)\n }\n for (m = 0; m < 6; m++) {\n l = 0;\n for (p = 0; p < 6; p++) {\n if (h[p] == m)break;\n if (h[p] > m)l++\n }\n q = q * (6 - m) + l\n }\n for (m = 9; m >= 6; m--)t = t * 3 + i[m];\n for (m = 4; m >= 0; m--)t = t * 2 + i[m];\n if (q != 0 || t != 0)for (m = mn; m < 99; m++)if (v(q, t, m, -1))break;\n b[c] = \"\";\n for (p = 0; p < k.length; p++)b[c] += [\"U\", \"L\", \"R\", \"B\"][k[p] & 7] + [\"\", \"'\"][(k[p] & 8) / 8] + \" \";\n var a = [\"l\", \"r\", \"b\", \"u\"];\n for (p = 0; p < 4; p++) {\n q = n(3);\n if (q < 2)b[c] += a[p] + [\"\", \"'\"][q] + \" \"\n }\n }\n }\n\n function v(q, t, l, c) {\n if (l == 0) {\n if (q == 0 && t == 0)return true\n } else {\n if (g[q] > l || f[t] > l)return false;\n var p, s, a, m;\n for (m = 0; m < 4; m++)if (m != c) {\n p = q;\n s = t;\n for (a = 0; a < 2; a++) {\n p = d[p][m];\n s = e[s][m];\n k[k.length] = m + 8 * a;\n if (v(p, s, l - 1, m))return true;\n k.length--\n }\n }\n }\n return false\n }\n\n function w(p, m) {\n var a, l, c, s = [], q = p;\n for (a = 1; a <= 6; a++) {\n c = Math.floor(q / a);\n l = q - a * c;\n q = c;\n for (c = a - 1; c >= l; c--)s[c + 1] = s[c];\n s[l] = 6 - a\n }\n if (m == 0)y(s, 0, 3, 1);\n if (m == 1)y(s, 1, 5, 2);\n if (m == 2)y(s, 0, 2, 4);\n if (m == 3)y(s, 3, 4, 5);\n q = 0;\n for (a = 0; a < 6; a++) {\n l = 0;\n for (c = 0; c < 6; c++) {\n if (s[c] == a)break;\n if (s[c] > a)l++\n }\n q = q * (6 - a) + l\n }\n return q\n }\n\n function x(p, m) {\n var a, l, c, t = 0, s = [], q = p;\n for (a = 0; a <= 4; a++) {\n s[a] = q & 1;\n q >>= 1;\n t ^= s[a]\n }\n s[5] = t;\n for (a = 6; a <= 9; a++) {\n c = Math.floor(q / 3);\n l = q - 3 * c;\n q = c;\n s[a] = l\n }\n if (m == 0) {\n s[6]++;\n if (s[6] == 3)s[6] = 0;\n y(s, 0, 3, 1);\n s[1] ^= 1;\n s[3] ^= 1\n }\n if (m == 1) {\n s[7]++;\n if (s[7] == 3)s[7] = 0;\n y(s, 1, 5, 2);\n s[2] ^= 1;\n s[5] ^= 1\n }\n if (m == 2) {\n s[8]++;\n if (s[8] == 3)s[8] = 0;\n y(s, 0, 2, 4);\n s[0] ^= 1;\n s[2] ^= 1\n }\n if (m == 3) {\n s[9]++;\n if (s[9] == 3)s[9] = 0;\n y(s, 3, 4, 5);\n s[3] ^= 1;\n s[4] ^= 1\n }\n q = 0;\n for (a = 9; a >= 6; a--)q = q * 3 + s[a];\n for (a = 4; a >= 0; a--)q = q * 2 + s[a];\n return q\n }\n\n function y(p, a, c, t) {\n var s = p[a];\n p[a] = p[c];\n p[c] = p[t];\n p[t] = s\n }\n\n function n(c) {\n return Math.floor(Math.random() * c)\n }\n\n u();\n ss[0] += b[0];\n}", "function verhoeffCheck(str) {\n var d_table = [\n [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9\n ],\n [\n 1,\n 2,\n 3,\n 4,\n 0,\n 6,\n 7,\n 8,\n 9,\n 5\n ],\n [\n 2,\n 3,\n 4,\n 0,\n 1,\n 7,\n 8,\n 9,\n 5,\n 6\n ],\n [\n 3,\n 4,\n 0,\n 1,\n 2,\n 8,\n 9,\n 5,\n 6,\n 7\n ],\n [\n 4,\n 0,\n 1,\n 2,\n 3,\n 9,\n 5,\n 6,\n 7,\n 8\n ],\n [\n 5,\n 9,\n 8,\n 7,\n 6,\n 0,\n 4,\n 3,\n 2,\n 1\n ],\n [\n 6,\n 5,\n 9,\n 8,\n 7,\n 1,\n 0,\n 4,\n 3,\n 2\n ],\n [\n 7,\n 6,\n 5,\n 9,\n 8,\n 2,\n 1,\n 0,\n 4,\n 3\n ],\n [\n 8,\n 7,\n 6,\n 5,\n 9,\n 3,\n 2,\n 1,\n 0,\n 4\n ],\n [\n 9,\n 8,\n 7,\n 6,\n 5,\n 4,\n 3,\n 2,\n 1,\n 0\n ]\n ];\n var p_table = [\n [\n 0,\n 1,\n 2,\n 3,\n 4,\n 5,\n 6,\n 7,\n 8,\n 9\n ],\n [\n 1,\n 5,\n 7,\n 6,\n 2,\n 8,\n 3,\n 0,\n 9,\n 4\n ],\n [\n 5,\n 8,\n 0,\n 3,\n 7,\n 9,\n 6,\n 1,\n 4,\n 2\n ],\n [\n 8,\n 9,\n 1,\n 6,\n 0,\n 4,\n 3,\n 5,\n 2,\n 7\n ],\n [\n 9,\n 4,\n 5,\n 3,\n 1,\n 2,\n 6,\n 8,\n 7,\n 0\n ],\n [\n 4,\n 2,\n 8,\n 6,\n 5,\n 7,\n 3,\n 9,\n 0,\n 1\n ],\n [\n 2,\n 7,\n 9,\n 3,\n 8,\n 0,\n 6,\n 4,\n 1,\n 5\n ],\n [\n 7,\n 0,\n 4,\n 6,\n 9,\n 1,\n 3,\n 2,\n 5,\n 8\n ]\n ]; // Copy (to prevent replacement) and reverse\n var str_copy = str.split('').reverse().join('');\n var checksum = 0;\n for(var i = 0; i < str_copy.length; i++)checksum = d_table[checksum][p_table[i % 8][parseInt(str_copy[i], 10)]];\n return checksum === 0;\n}", "function yugioh(param){\r\n let finalArray = []\r\n for (let index = 1; index <= param; index++) {\r\n if (index % 2 === 0 && index % 3 === 0 && index % 5 === 0) {\r\n finalArray.push('yu-gi-oh')\r\n } else if (index % 2 === 0 && index % 3 === 0) {\r\n finalArray.push('yu-gi')\r\n } else if (index % 2 === 0 && index % 5 === 0) {\r\n finalArray.push('yu-oh')\r\n } else if (index % 3 === 0 && index % 5 === 0) {\r\n finalArray.push('gi-oh')\r\n } else if (index % 2 === 0) {\r\n finalArray.push('yu')\r\n } else if (index % 3 === 0) {\r\n finalArray.push('gi')\r\n } else if (index % 5 === 0) {\r\n finalArray.push('oh')\r\n } else {\r\n finalArray.push(index)\r\n }\r\n }\r\n return finalArray\r\n}", "function getUniqueLetters() {\n const getUnique = new Set(movieTitleToArray()); //create an object of unique letters\n const unique = [...getUnique]; //turn above object back into an array\n return unique;\n}", "function convertToAlpha(num) {\n\n let perm = [];\n num = num.toString().split('');\n let temp = num.slice();\n\n perm.push(mapper(num));\n\n for (var i = 0; i < num.length; i++) {\n for (var j = i; j < num.length; j++) {\n let sum = num[j] + num[j+1]\n if (sum <= 26) {\n num[j] = sum;\n num.splice(j+1, 1);\n console.log(num);\n perm.push(mapper(num));\n }\n }\n num = temp.slice();\n }\n return perm;\n}", "function crypto(inputText){\n var letter = /^[a-zA-Z]+$/;\n let sentenceOne = inputText.toLowerCase().split(\"\");\n console.log('sentenceOne (after split) = ', sentenceOne);\n var array=[];\n for(var i = 0 ; i < sentenceOne.length; i++){\n if(sentenceOne[i].match(letter)){\n array.push(sentenceOne[i]);\n }\n }\n\n // array = ['b', 'u', 'n', 'm', 'a', ..,]\n // finalSentence = 'bunmannunsun'\n var rows = Math.ceil(Math.sqrt(array.length));\n var cols = Math.ceil(array.length/rows);\n var finalSentence = array.join(\"\");\n console.log('stripped sentence - ', finalSentence);\n\n for(var i=1; i < rows+1 ; i ++){\n this[\"row\"+i] = finalSentence.slice(0,cols);\n finalSentence = finalSentence.slice(cols);\n console.log(\"row\"+i+\" = \", this[\"row\"+i]);\n }\n\n for(var i = 1; i < cols+1; i++){\n this[\"cols\"+i] = \"\";\n }\n\n for(var i = 0; i < cols; i++) {\n let colName = \"cols\"+ (i + 1);\n for(var j = 1; j < rows+1; j++){\n this[colName] = this[colName] + this[\"row\"+j][i];\n }\n\n console.log(`${colName} = ${this[colName]}`);\n }\n var colsJoin = \"\";\n for(var i = 1; i < cols+1; i++){\n colsJoin = colsJoin + this[\"cols\"+i];\n }\n\n // nn\n // bmnsu; bmnsu\n // uuunn; bmnsu uuunn nn\n var output = \"\";\n while(colsJoin.length > 0){\n output = output + colsJoin.slice(0,5) + \" \";\n colsJoin= colsJoin.slice(5);\n console.log(`output: ${output}`);\n }\n return output;\n }", "function getHexagramGroup(hexagramCode){\n\tvar externalTrigram = hexagramCode.substring(0, 3),\n\t\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 1);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 2);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 3);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 4);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 5);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 4);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\thexagramCode = toggleAt(hexagramCode, 3);\n\thexagramCode = toggleAt(hexagramCode, 2);\n\thexagramCode = toggleAt(hexagramCode, 1);\n\texternalTrigram = hexagramCode.substring(0, 3);\n\tinternalTrigram = hexagramCode.substring(3);\t\n\tif (externalTrigram == internalTrigram){ return externalTrigram; }\n\t\n\treturn null;\n}", "function generateBoard(frequencyMap) {\n var board = [\n [null, null, null, null],\n [null, null, null, null],\n [null, null, null, null],\n [null, null, null, null]\n ];\n\n var pathTaken = [\n [false, false, false, false],\n [false, false, false, false],\n [false, false, false, false],\n [false, false, false, false]\n ];\n\n var letters = {};\n\n function pickLetter(soFar, i, j) {\n if (board[i][j] === null) {\n return;\n }\n pathTaken[i][j] = true; \n soFar = soFar + board[i][j];\n _pickLetter(soFar, i, j);\n pathTaken[i][j] = false;\n }\n\n function _pickLetter(soFar, i, j) {\n // for each letter, create a probability distribution based on the frequencyMap for 3 letter\n // combinations\n var inci, incj, newi, newj;\n\n if (soFar.length >= 2) {\n letters[soFar.charAt(0)] += frequencyMap[soFar] || 0;\n }\n\n if (soFar.length >= 3) {\n return;\n }\n\n for (inci = -1; inci <= 1; inci += 1) {\n for (incj = -1; incj <= 1; incj += 1) {\n newi = inci + i;\n newj = incj + j;\n if (newi >= 0 && newi < boardSize && newj >= 0 && newj < boardSize && !pathTaken[newi][newj]) {\n pickLetter(soFar, newi, newj);\n }\n }\n }\n }\n\n function pickLetterStart(i, j) {\n\n for (var c = 97; c <= 122; c += 1) {\n var letter = String.fromCharCode(c);\n letters[letter] = 1;\n board[i][j] = letter;\n pickLetter(\"\", i, j);\n }\n\n board[i][j] = null;\n var total = 0;\n Object.keys(letters).forEach(function(k) {\n total += letters[k];\n });\n var i = randomNumber(total)\n\n total = 0;\n var selected = \"\";\n Object.keys(letters).forEach(function(k) {\n total += letters[k];\n if (!selected && total > i) {\n selected = k;\n }\n });\n\n return selected;\n }\n\n var i, j, letter, coords = []\n for (i = 0; i < boardSize; i += 1) {\n for (j = 0; j < boardSize; j += 1) {\n coords.push([i, j])\n }\n }\n // coords = coords.concat(coords.slice());\n\n // This didn't seem to get me better results, so I've commented it out.\n // shuffle(coords);\n\n coords.forEach(function(coord) {\n var i = coord[0], j = coord[1];\n letters = {};\n letter = pickLetterStart(i, j);\n board[i][j] = letter;\n });\n\n\n return board;\n}", "function dictionary(initial, words) {\n console.log('initial', initial)\n const outputArr = []\n for (var i = 0; i < words.length; i++) {\n var len = initial.length\n const word = words[i]\n // console.log('word', word)\n const tempArr = []\n for (var y = 0; y < len; y++) {\n const letter = word[y]\n // console.log('letter', letter)\n tempArr.push(letter)\n }\n // console.log('tempArr-', tempArr)\n const wordStart = tempArr.join('') // first x letters of word, where x = initial.length\n // console.log('wordstart::', wordStart)\n if (wordStart === initial) {\n outputArr.push(word)\n }\n }\n console.log('outputArr', outputArr)\n return outputArr\n}", "async function genPads(length){\n var vrfNum = await vrfNumber();\n const arrayOfDigits = Array.from(String(vrfNum), Number);\n var arrayOfLetters = [];\n for(let i = 0; i < arrayOfDigits.length; i++)\n arrayOfLetters.push(String.fromCharCode(97 + arrayOfDigits[i]))\n arrayOfLetters = chunkArray(arrayOfLetters, length);\n for(let i = 0; i < arrayOfLetters.length; i++){\n if(arrayOfLetters[i].length < length)\n delete arrayOfLetters[i];\n }\n return arrayOfLetters;\n}", "function putzolo_getTheCheesyPairs(){\n var pairs = [];\n pairs.push({\n killIf: [\n \"kar\"+String.fromCharCode(225)+\"csony\", \n \"karacsony\"\n ],\n butKeepIf: [\n \"kar\"+String.fromCharCode(225)+\"csonyi zsolt\", \n \"kar\"+String.fromCharCode(225)+\"csony ben\", \n \"zsolt kar\", \n \"karacsony beno\", \n \"csonyi zsolt\", \n \"halmaz\" \n ]\n })\n pairs.push({\n killIf: [\"christmas\"],\n butKeepIf: [\"last christmas\", \"apod\", \"cluster\"]\n })\n pairs.push({\n killIf: [\n String.fromCharCode(252)+\"nnepek\", \n \"husvet\", \n \"h\"+String.fromCharCode(250)+\"sv\"+String.fromCharCode(233)+\"t\", \n \"happy new year\",\n \"isten \"+String.fromCharCode(233)+\"ltessen\", \n \"isten eltessen\", \n \"boldog szuletesnapot\", \n \"boldog sz\"+String.fromCharCode(252)+\"let\"+String.fromCharCode(233)+\"snapot\", \n \"boldog szulinapot\", \n \"boldog sz\"+String.fromCharCode(252)+\"linapot\"\n ]\n });\n return pairs;\n }", "function generatesInitials() {\r\n let uniqueCode = [];\r\n for (var i = 0; i < 2; i++) {\r\n uniqueCode.push(String.fromCharCode((Math.random() * (91 - 65) + 65).toFixed(0)));\r\n }\r\n return uniqueCode.join(\"\");\r\n}", "function getRandomPhraseAsArray(array) {\n let getRandomPhrase = array[Math.floor(Math.random() * array.length)];\n let newPhraseArray = [];\n currentPhrase = getRandomPhrase;\n\n for (let i = 0; i < getRandomPhrase.length; i++) {\n newPhraseArray.push(getRandomPhrase.charAt(i));\n }\n return newPhraseArray;\n}", "makeHash(str) {\n let hash = 0;\n let limit = this.limit;\n let letter;\n \n for (var i = 0; i < str.length; i++) {\n letter = str[i];\n hash = (hash << 5) + letter.charCodeAt(0);\n hash = (hash & hash) % limit;\n }\n \n return hash;\n }", "function cipher(cipherPhrase) { // y decipher (revisar luego nombres de variables)\r\n var upperCiphPhrase = cipherPhrase.toUpperCase();// sin return porque no necesito que me la muestre\r\n // var arrayFrase = array.from(upperCiphPhrase); charcode at no funciona con array\r\n var cipherArray = []; // la ponemos fuera del for ya que sino se va limpiando en cada vuelta del recorrido\r\n for (var i = 0; i < upperCiphPhrase.length; i++) {\r\n // console.log(i);\r\n var onAscci = upperCiphPhrase.charCodeAt(i); // para sacar el numero ascii correspondiente al numero de los elementos\r\n // console.log(onAscci);\r\n var algorithm = ((onAscci - 65 + 33) % 26 + 65) ; // nos da el numero ascci de la letra desplazada\r\n // console.log(desplazamiento);\r\n var cipherMsg = String.fromCharCode(algorithm); // pasamos los numeros ascii a sus letras correspondientes\r\n // console.log(newLetra);\r\n cipherArray.push(cipherMsg); // ingresamos cada letra al array para tener todas las letras en un array y luego convertirla a cadena\r\n // console.log(finalArray);\r\n var cypherStr = cipherArray.join(''); // array a string porque es solicitadoque se presente de sta forma\r\n // console.log(strCifrado);\r\n }\r\n // return strCifrado;\r\n return alert('Su mensaje es ' + cypherStr); // porque tengo que hacerle doble enter??\r\n }", "function flatArr() {\n var toArr = [];\n for (var i = 0; i < chosenWord.length; i++) {\n if(/[a-zA-Z0-9]/.test(chosenWord[i])) {\n toArr.push(chosenWord[i]);\n }\n }\n turnCount = toArr.length;\n}", "function FindWords(letters, finalsolutions){\n\tvar letters_or = getOrdered(letters); \n\tif (letters_or in wordhash){\t// check if ordered version has words\n\t\tfor (var i=0; i<wordhash[letters_or].length; i++){\n\t\t\tfinalsolutions.push(wordhash[letters_or][i]);\t// grab each mapped word\n\t\t}\n\t}\n\treturn finalsolutions;\n\n\n\n\n}", "function Hamming(P) {\r\n var W1 = P,\r\n R = P[0].length,\r\n B = [],\r\n e = (1.0 / (P.length - 1.0)) / 2.0,\r\n W2 = [],\r\n a1 = [],\r\n a2 = [],\r\n newRow,\r\n i,j,k,test,z;\r\n \r\n for (i = 0; i < P.length; i++){\r\n B.push([R]);\r\n }\r\n for (i = 0; i < P.length; i++){\r\n newRow = new Array();\r\n for (j = 0; j < R; j++){\r\n if (i === j) {\r\n newRow.push(1.0);\r\n } else {\r\n newRow.push(-1.0 * e);\r\n }\r\n }\r\n W2.push(newRow);\r\n }\r\n \r\n P = tranposeMatrix(P);\r\n\r\n for (i = 0; i < P[0].length; i++) {\r\n a1 = addTwoMatrix(multiplyTwoMatrix(W1,P,i),B);\r\n z = 0;\r\n do{\r\n a2 = transferFunction(multiplyTwoMatrix(W2,a1,0),\"poslin\");\r\n a1 = a2;\r\n console.log(\"after a2 of \" + i + \": \" + a2);\r\n test = 0;\r\n for(k = 0; k < a2.length; k++){\r\n if(a2[k][0] > 0){\r\n test++;\r\n j = k;\r\n }\r\n }\r\n z++;\r\n }while(test > 1 && z < 15);\r\n if(z !== 15){\r\n console.log(\"output of \"+ i + \" is: \" + j);\r\n }\r\n \r\n }\r\n \r\n \r\n \r\n}", "function stringWord() {\n for (var x = 0; x < letterObjects.length; x++) {\n var strings = [];\n var newStrings = letterObjects[x].guessLetter();\n strings.push(newStrings);\n // console.log(strings.join(\" \"));\n }\n }", "function getRandomPhraseAsArray(arr) {\n return arr[Math.floor(Math.random() *arr.length)].split('');\n}", "function letterGenerator(){\n\tconst letters = \"abcdefghijklmnopqrstuvwxyz\"; //string of possible letters\n\t\n\tlet randomLetters = []; //random letter array\n\t\n\twhile(randomLetters.length < 9 ){ //add a random letter while array length less than 9\n\t\trandomLetters.push(letters[Math.floor(Math.random() * 25)]);\n\t\t\n\t\tif(randomLetters.length === 9){ // if array size = 9, then check to see if there's enough consonants & vowels\n\t\t\tlet vowels = 0;\n\t\t\tlet consonants = 0;\n\t\t\trandomLetters.forEach((letter)=>{\n\t\t\t\tswitch(letter){\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\tcase \"e\":\n\t\t\t\t\tcase \"i\":\n\t\t\t\t\tcase \"o\":\n\t\t\t\t\tcase \"u\":\n\t\t\t\t\t\tvowels++;\n\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tconsonants++;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif(vowels < 2 || consonants < 2){ // erase array if there are not enough vowels/consonants\n\t\t\t\trandomLetters = [];\n\t\t\t}\n\t\t\telse{\n\t\t\t\treturn randomLetters; // return array if length === 9 and vowels/consonants > 2\n\t\t\t}\n\t\t}\n\t}\n}", "function _mashingBigramFrequencies() {\n const mBF = {};\n MASH_BIGRAMS.forEach((bigram) => {\n if (bigram[0] == bigram[1] || [...bigram].every(c => c !== ' ' && MASH_CHARS.indexOf(c) > -1)) {\n mBF[bigram] = 0.5 / (16 + 26)\n } else {\n mBF[bigram] = 0.5 / (MASH_BIGRAMS.length - 16 - 26)\n }\n });\n return mBF;\n}", "function permutationsWithDups4(str) {\n return createPerms('', str.length, buildLetterMap(str));\n}", "function list_transcribe(){\n\t\tfor(element in input.list){\n\t\t\tindex = 0\n\t\t\twhile(input.list[element] != alphabet[index]){\n\t\t\t\tindex += 1;\n\t\t\t}\n\t\t\tinput.transcribedsingle.push(index);\n\t\t}\n}", "function generatePassPhrase() {\n\n var s = new Uint16Array(WORDCOUNT);\n var phrase_words = [];\n\n var bytes = forge.random.getBytesSync(2*WORDCOUNT);\n for(var n=0; n < WORDCOUNT; n++)\n {\n var idx = (bytes.charCodeAt(n*2) & 0x7) << 8;\n idx = idx | bytes.charCodeAt(n*2+1) & 0xFF;\n\n phrase_words.push(words[idx]);\n }\n\n var phrase = phrase_words.join(' ');\n $('#put_passphrase').text(phrase);\n}", "function anagramGroup(arr){\n let charHash = new HashMap;\n let results = [];\n \n for(const word of arr) {\n let charSorted = word.split('').sort().join('');\n try{\n let group = charHash.get(charSorted);\n group.push(word);\n } \n catch (error){\n results.push(charSorted);\n charHash.set(charSorted, [word]);\n }\n }\n \n let newArray = results.map(group =>{\n return charHash.get(group);\n });\n\n return newArray;\n\n}", "function eliminateDuplicates(pArray) {\n var auxLetters = [];\n\tvar lettersJson = {};\n\n\tfor (var letterPosition = 0; letterPosition < pArray.length; letterPosition++) {\n\t lettersJson[pArray[letterPosition]] = 0;\n\t}\n\n\tfor (letter in lettersJson) {\n\t auxLetters.push(letter);\n\t}\n\n\treturn auxLetters;\n}", "function findLetterIndexes(letter) {\n var letterIndexes = [];\n for (var i = 0; i < randomWordArray.length; i++) {\n if (randomWordArray[i] === letter) {\n letterIndexes.push(i);\n }\n }\n replaceDashes(letterIndexes); // returns an array of number indexes like [1, 2, 3]\n }", "function getRandomPhraseAsArray(arr) {\n const randomPhrase = arr[Math.floor(Math.random() * arr.length)];\n // showing letter of pharse and split is gaps between the words.\n return randomPhrase.toUpperCase().split('');\n}", "_hash(key) {//Generate a hash for us between 0 and length of array - 1\n\t\t//In real life this is soooo fast that its O(1) even tho there is a loop\n\t\tlet hash = 0;\n\t\tfor (let i=0; i < key.length; i++) {\n\t\t\t//charCodeAt(i) gives character code 0-65535 UTF code\n\t\t\thash = (hash + key.charCodeAt(i) * i) % this.data.length;\n\t\t //concat //get utf code //multiply by idx for duplicate characters to get unique\n\t\t //Mod so it fits in the hash size\n\t\t}\n\t\treturn hash;\n\t}", "function makeSpoonHeads(a)\n{\n let heads = [];\n for (let i = 0; i < a.length; i++)\n {\n let head = makeSpoonHead(a[i]);\n heads.push(head);\n }\n return heads;\n}", "function splitLetter() {\n for (var h = 0; h < nameLength; h++) {\n splitArray.push(chosenGame[h]);\n }\n return splitArray;\n}", "function oaep_mgf1_arr(seed, len, hash)\n{\n var mask = '', i = 0;\n\n while (mask.length < len)\n {\n mask += hash(String.fromCharCode.apply(String, seed.concat([\n (i & 0xff000000) >> 24,\n (i & 0x00ff0000) >> 16,\n (i & 0x0000ff00) >> 8,\n i & 0x000000ff])));\n i += 1;\n }\n\n return mask;\n}", "function oaep_mgf1_arr(seed, len, hash)\n{\n var mask = '', i = 0;\n\n while (mask.length < len)\n {\n mask += hash(String.fromCharCode.apply(String, seed.concat([\n (i & 0xff000000) >> 24,\n (i & 0x00ff0000) >> 16,\n (i & 0x0000ff00) >> 8,\n i & 0x000000ff])));\n i += 1;\n }\n\n return mask;\n}", "function soloUnaVez(texto) {\n\n //Definir variables\n let contadores = {},\n resultado = [];\n letras = texto.split('').filter(letra => letra.trim().length >= 1);\n\n //Generar contadores\n for (letra of letras) {\n if (!contadores[letra]) {\n contadores[letra] = 1;\n } else {\n contadores[letra]++;\n }\n }\n\n //Eliminar las letras que se repitan\n for (letra in contadores) {\n if (contadores[letra] === 1) {\n resultado.push(letra);\n }\n }\n\n return [resultado, resultado[0]];\n}", "function generateChars() {\n var chars = '0123456789';\n\n // Get ALL half-width katakana characters by unicode value\n for (var i = 0; i <= 55; i++) {\n chars += String.fromCharCode(i + 65382);\n }\n \n return chars.split('');\n}", "generateWords() {\n let encoded = [];\n let rand = Math.floor(Math.random() * this.words.length);\n encoded.push(this.words.splice(rand, 1));\n rand = Math.floor(Math.random() * this.words.length);\n encoded.push(this.words.splice(rand, 1));\n rand = Math.floor(Math.random() * this.words.length);\n encoded.push(this.words.splice(rand, 1));\n rand = Math.floor(Math.random() * this.words.length);\n encoded.push(this.words.splice(rand, 1));\n return encoded;\n }", "function solution4(givenWord, givenList){\n sortString = str => {\n return str.toLowerCase().split('').sort().join('') }\n let sortedWord = sortString(givenWord);\n let anagrams = givenList.reduce((acc, item) => {\n sortedWord === sortString(item) && acc.push(item)\n return acc;\n }, []);\nreturn anagrams; \n}", "function getPasswordEntropy(password) {\n let base = 0 // Amount of unique letters\n let length = 0 // amount of letters\n let freqCount = {} // how many times each letter appears\n\n // Count up the frequencies\n for(let letter of password) {\n length += 1\n if(letter in freqCount) {\n freqCount[letter] += 1\n } else {\n base += 1\n freqCount[letter] = 1\n }\n }\n\n // What percent of the password is unique\n let originality = base / length\n\n // If there is one letter, calculation\n // will return NaN, but 1 is what it should return\n if(base == 1) {\n return originality\n } else {\n let entropy = 0\n \n for(let letter in freqCount) {\n freq = freqCount[letter] / length\n entropy -= freq * (Math.log(freq) / Math.log(base))\n }\n \n\n return Math.sqrt(originality * entropy)\n }\n}", "function nounForms() {\n return [...Array(28).keys()].map(i => (plurality[i >= cases.length ? 1 : 0] + \" \" + cases[i % cases.length]));\n}", "function staircase(n) {\n let noOfSpaces = 0, noOfHashes = 0;\n let result = \"\";\n for (let i = 1; i <= n; i++) {\n result = \"\";\n noOfSpaces = n-i;\n noOfHashes = i;\n for (let j = 1; j <= noOfSpaces; j++) {\n result += \" \";\n }\n for (let k = 1; k <= noOfHashes; k++) {\n result += \"#\";\n }\n console.log(result);\n }\n\n}", "function getHuffmanCodes() {\r\n var huff = new HuffmanCoding(originalText);\r\n $('#huffman-tbody').empty();\r\n for (var [key, value] of huff.sortedCodes) {\r\n $('#huffman-tbody').append('<tr><td>' + key + '</td><td>' + value + '</td></tr>');\r\n }\r\n\r\n compressedText = huff.huffmanString;\r\n}", "createPhrase( ) {\n for (let i = 0; i < 5; i++) {\n let randomPhrase = '';\n let adjective = '';\n let noun = '';\n let declaration = '';\n let verb = '';\n const words = { // excuse the absurdities; I got carried away. This is an object of arrays. \n adjective: ['rich', 'ugly', 'divorced', 'skilled','widowed', 'frisky', 'pregnant', 'infected', 'smart', 'scared', 'pretty', 'nice', 'evil', 'virgin', 'married', 'baptised', 'acquitted', 'drunk', 'christian'],\n noun: ['dogs', 'cats', 'husbands', 'women', 'athletes','housewives', 'zoomers', 'cosmonauts','immigrants','hipsters', 'lawyers', 'priests', 'artists', 'fish', 'zombies', 'veterans', 'inmates', 'hippies'],\n declaration: ['never', 'always', 'rarely', 'long to','often', 'cannot', 'refuse to', 'are willing to', 'love to', 'eagerly'],\n verb: ['cry', 'smile', 'snuggle','surrender', 'offend', 'lose', 'win','say thank you','settle','beg', 'spoon','die', 'nark', 'drive','eat', 'lie', 'sleep', 'fart', 'sweat', 'puke', 'help', 'talk', 'divorce', 'kill', 'have sex', 'remarry', 'pray', 'protest']\n } \n /**\n * generates a random index based on @param.length\n * @param {array} wordList - an object of arrays \n */\n const randomIndex = (wordList) => Math.floor( Math.random() * wordList.length );\n\n for (let prop in words) {\n const list = words[`${prop}`];\n const index = randomIndex(list);\n if (prop === 'adjective') adjective = words[`${prop}`][index];\n if (prop === 'noun') noun = words[`${prop}`][index];\n if (prop === 'declaration') declaration = words[`${prop}`][index];\n if (prop === 'verb') verb = words[`${prop}`][index];\n }\n randomPhrase = `${adjective} ${noun} ${declaration} ${verb}`; \n this.phrases.push(new Phrase(randomPhrase, noun, adjective, verb)); \n }\n }", "function generateAlphabet () {\n const letters = []\n for (let i = 0; i < 26; i++) {\n letters.push(String.fromCharCode(i + 97))\n }\n return letters\n}", "function getRandomPhraseAsArray(arr) {\n let arrayPosition = Math.floor(Math.random() * arr.length);\n let randomPhrase = arr[arrayPosition];\n let phraseCharacters = [];\n\n for (let i = 0; i < randomPhrase.length; i += 1) {\n phraseCharacters.push(randomPhrase[i]);\n }\n\n return phraseCharacters;\n}", "function generatePassword() {\n var storage = infograb();\n var results = []; \n var characters = []; \n var verify = []; \n if (storage.lowercasecharacter){\n characters = characters.concat(lowercase);\n }\n if (storage.uppercasecharacter){\n characters = characters.concat(uppercase);\n }\n if (storage.specialcharacter){\n characters = characters.concat(specialcharacters);\n }\n if (storage.number) {\n characters = characters.concat(numbers);\n }\n\n for (var i = 0; i < storage.length; i ++) {\n var NewCharacter = getRandomindex(characters);\n results.push(NewCharacter);\n // generate random index \n }\n console.log(results);\n return results.join(\"\") ;\n}", "function anagrams(word, words) {\n /*\n let w = [...word].sort().join(\"\");\n let ws = [...words].map(word => [...word].sort().join(\"\"));\n let arr = [];\n for (let i = 0; i < ws.length; i ++) {\n if (w == ws[i]) {\n arr.push(words[i])\n }\n }\n return arr;\n */\n \n return words.filter(x => [...x].sort().join(\"\") == [...word].sort().join(\"\"));\n }", "function regroup(pairs_list){\n var mapping = { 'a-e': [],\n 'f-j': [],\n 'k-o': [],\n 'p-t': [],\n 'u-z': []};\n for (var i in pairs_list){\n var pairs = pairs_list[i];\n for (var j in pairs){\n var p = pairs[j];\n var firstLetterASCII = p[0].charCodeAt(0);\n if((97 <= firstLetterASCII) && (firstLetterASCII <= 101)){\n mapping['a-e'].push(p);\n } else if ((102 <= firstLetterASCII) && (firstLetterASCII <= 106)){\n mapping['f-j'].push(p);\n } else if ((107 <= firstLetterASCII) && (firstLetterASCII <= 111)) {\n mapping['k-o'].push(p);\n } else if ((112 <= firstLetterASCII) && (firstLetterASCII <= 116)) {\n mapping['p-t'].push(p);\n } else if ((117 <= firstLetterASCII) && (firstLetterASCII <= 122)) {\n mapping['u-z'].push(p);\n } else {}\n }\n }\n return mapping;\n}", "function genCharArray(charA, charZ) {\n var a = [], i = charA.charCodeAt(0), j = charZ.charCodeAt(0);\n for (i = charA.charCodeAt(0); i <= j; i++) {\n console.log(i);\n a.push(String.fromCharCode(i));\n }\n return a;\n}", "function generateBank() {\n\tvar text;\n\tvar alphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\tvar vowels = \"AEIOU\"\n\tvar vowelCount = 0;\n\t\n\twhile(vowelCount < 2 || vowelCount > 7) {\n\t\ttext = \"\";\n\t\tvowelCount = 0;\n\t\tthing = [];\n\t\tfor (var i = 0; i < 9; i++) {\n\t\t\tvar letter = alphabet.charAt(Math.floor(Math.random() * alphabet.length));\n\t\t\ttext += letter;\n\t\t\tif(vowels.includes(letter))\n\t\t\t\tvowelCount++;\n\t\t}\n\t}\n\treturn text;\n}", "function anagrams(string) {\n let list = [];\n\n if(string.length === 1) {\n list.push(string);\n return list;\n }\n\n for(let i = 0; i < string.length; i++) {\n let firstChar = string[i];\n let otherChar = string.substring(0, i) + string.substring(i + 1);\n let otherPermutations = anagrams(otherChar);\n\n for(let j = 0; j < otherPermutations.length; j++) {\n list.push(firstChar + otherPermutations[j]);\n }\n }\n return list;\n}", "function generate_data(int)\n{\n\tvar word_array = [];\n\tvar possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n\tfor (i = 0; i < int; i++)\n\t{\n\t\tvar word = \"\";\n\t\trandom = Math.floor((Math.random() * ((10 - 1) + 1)) + 1);\n\t\tfor (j = 0; j < random; j++)\n\t\t{\n\t\t\tword += possible.charAt(Math.floor(Math.random() * possible.length));\n\t\t}\n\t\tword_array.push(word);\n\t}\n\treturn word_array;\n}", "function process_string(string) {\n const alph = \"abcdefghijklmnopqrstuvwxyz\";\n let hash_table = {};\n\n for (let i = 0; i < string.length; i++) {\n let char = alph.indexOf(string[i]);\n if (i === 0) {\n hash_table[i] = new Array(26).fill(0);\n hash_table[i][char]++;\n } else {\n hash_table[i] = hash_table[i - 1].slice(0);\n hash_table[i][char]++;\n };\n };\n return hash_table;\n}", "function main() {\n var n = parseInt(readLine());\n var s = readLine();\n var k = parseInt(readLine());\n let newPhrase = '';\n \n for (let i = 0; i < n; ++i) {\n const lowerCase = { min: 97, max: 122 };\n const upperCase = { min: 65, max: 90};\n let isTitle = null;\n let isPunctuation = null;\n let currCharCode = s.charCodeAt(i);\n \n if (currCharCode >= lowerCase.min && currCharCode <= lowerCase.max) {\n isTitle = false;\n } \n else if (currCharCode >= upperCase.min && currCharCode <= upperCase.max) {\n isTitle = true;\n } else {\n isPunctuation = true;\n }\n \n if (!isTitle && !isPunctuation) {\n currCharCode -= lowerCase.min;\n currCharCode = ((currCharCode + k) % 26) + lowerCase.min;\n } \n else if (isTitle && !isPunctuation) {\n currCharCode -= upperCase.min;\n currCharCode = ((currCharCode + k) % 26) + upperCase.min;\n }\n \n newPhrase += String.fromCharCode(currCharCode);\n }\n \n console.log(newPhrase);\n}", "function getAlphabetArray() {\n const result = [];\n for (i = a; i <= b; i++) {\n result.push(String.fromCharCode(i));\n }\n return result;\n}", "function firstLayerEncryption(input) {\n var output = [];\n var i;\n for ( i in input) {\n output[i] = String.fromCharCode((input[i].charCodeAt(0)) ^ (Math.random()*(255-1)+1));\n }\n //writeToFile(output,\"AsciiEncoded.js\");\n return output;\n}", "function newPss() {\n var text = \"\";\n var possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\n for (var i = 0; i < 8; i++)\n text += possible.charAt(Math.floor(Math.random() * possible.length));\n\n return text;\n}", "function findHiatos(aWSplitted){\n\tvar hiatosIndex = []\n\tfor (var i = 0; i < aWSplitted.length; i++) {\n\t\t//finds if there is an open vowel\n\t\tfor (var e = 0; e < openVowels.length; e++) {\n\t\t\tif (aWSplitted[i] === openVowels[e]) {\n\t\t\t\tfor (var o = 0; o < openVowels.length; o++) {\n\t\t\t\t\tif (aWSplitted[i+1] === openVowels[o]) {\n\t\t\t\t\t\thiatosIndex.push(i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t}\n\n\t//eliminates duplicates caused by two closed vowels diptongos\n\tvar uniqueArray = hiatosIndex.filter(function(item, pos) {\n\t return hiatosIndex.indexOf(item) == pos;\n\t})\n\n\treturn uniqueArray\n}", "function allConstruct(target, wordBank) {\n const table = new Array(target.length + 1)\n .fill()\n .map(() => []);\n table[0] = [[]];\n\n for (let i = 0; i <= target.length; i++) {\n for (let word of wordBank) {\n if (target.slice(i, i + word.length) === word) {\n const combination = table[i].map(sub => [...sub, word]);\n console.log('combo', combination, 'table', table)\n table[i + word.length].push(...combination);\n console.log('afterTable', table)\n }\n }\n }\n return table[target.length];\n}", "function makeLowerArray(){\n var letterArray = [];\n for(var i = 0; i < 26; i++){\n // lowercase letters have an ascii index of 97 - 122\n letterArray[i] = String.fromCharCode(97 + i);\n }\n return(letterArray);\n}", "function findPalidrom(input) {\n var words = true;\n var spacesOut = function (sentence) {\n var letters = \"\";\n for (var i = 0; i < sentence.length; i++) {\n if (sentence[i] === \" \") {\n continue;\n }\n else {\n letters += sentence[i];\n }\n } return letters;\n }\n var finalArray = spacesOut(input);\n for (var i = 0, j = finalArray.length - 1; i < finalArray.length / 2; i++ , j--) {\n if (finalArray[i] === finalArray[j]) {\n continue;\n }\n else {\n return !words;\n }\n } return words;\n}", "function isHeterogram(string){\n // Dictionary for determining the frequency of characters in the string\n let stringFreq = {};\n\n // Check if the string has more than 20 characters\n if(string.length > 20){\n return false;\n }\n\n // iterate over each character in the string\n for(let i = 0; i < string.length; i++){\n // Check if the character has frequency > 1, character is a number or character is a punctuation.\n if(stringFreq.hasOwnProperty(string.charAt(i)) || !isNaN(string.charAt(i)) || !string.charAt(i).match(/[a-z]/i)){\n return false;\n } else {\n stringFreq[string.charAt(i)] = 1;\n }\n }\n // String is a valid heterogram we can react with. Return true.\n return true;\n}", "function commonLetter(word,guess){\n\tlet count = 0;\n\tlet map = [];\n\tfor (let letter of word) {\n\t\tif (!map[letter]){\n\t\t\tmap[letter] = 0;\n\t\t}\n\t\tmap[letter]++;\t\n\t}\n\t//console.log(map);\n\tfor (let i = 0; i < guess.length; i++) {\n\t\tif ( map[guess[i]] && map[guess[i]] != 0) {\n\t\t\tmap[guess[i]]--;\n\t\t\tcount++;\n\t\t}else{\n\t\t\tcontinue;\n\t\t}\n\t}\n\t//console.log(map);\n\treturn count;\n}" ]
[ "0.61886054", "0.6108243", "0.56711155", "0.5660597", "0.56365174", "0.5630204", "0.56205755", "0.5566037", "0.5561889", "0.55251133", "0.55091715", "0.55090034", "0.5504746", "0.5432786", "0.5431474", "0.5431005", "0.5402302", "0.5346259", "0.5323693", "0.52928305", "0.52874476", "0.5271309", "0.52548105", "0.52539295", "0.5234547", "0.5232844", "0.5230922", "0.5224626", "0.52233183", "0.5217512", "0.52154404", "0.5209788", "0.51999557", "0.519926", "0.5197668", "0.518642", "0.5185954", "0.51823413", "0.5174351", "0.51735437", "0.5169823", "0.51662576", "0.51620674", "0.5154263", "0.51542586", "0.51493305", "0.5118864", "0.5118123", "0.51168585", "0.51147825", "0.51147544", "0.51118785", "0.5102875", "0.50971454", "0.50936234", "0.50846976", "0.50803953", "0.50796753", "0.5075515", "0.5063991", "0.5062405", "0.5042462", "0.5034164", "0.5018891", "0.5013462", "0.50099653", "0.5006189", "0.5001117", "0.49930894", "0.49930894", "0.4992114", "0.4984786", "0.49795297", "0.4969983", "0.4967429", "0.49657062", "0.49653938", "0.49638242", "0.49629974", "0.49626747", "0.49592677", "0.49513522", "0.49476904", "0.4944062", "0.49422723", "0.49410427", "0.49396664", "0.4937387", "0.4931979", "0.49319312", "0.49284643", "0.49284142", "0.4927939", "0.49258494", "0.49238726", "0.49225152", "0.49220535", "0.4920509", "0.4917272" ]
0.6928506
1
if we're leaving a node that created a new scope, update the scopeChain so that the current scope is always represented by the last item in the scopeChain array.
function leave(node) { if (createsNewScope(node)) { let currentScope = scopeChain.pop(); printScope(currentScope, node); programScopes.push(currentScope); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "exitScope() {\n // Free up all the identifiers used in the previous scope\n this.scopes.pop().free(this.context);\n this.scope = this.scopes[this.scopes.length - 1];\n }", "function popScopeId() {\r\n currentScopeId = null;\r\n}", "function popScopeId() {\r\n currentScopeId = null;\r\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "function popScopeId() {\n currentScopeId = null;\n}", "endScope(result) {\n const tensorsToTrackInParent = Object(_tensor_util__WEBPACK_IMPORTED_MODULE_8__[\"getTensorsInContainer\"])(result);\n const tensorsToTrackInParentSet = new Set(tensorsToTrackInParent.map(t => t.id));\n // Dispose the arrays tracked in this scope.\n for (let i = 0; i < this.state.activeScope.track.length; i++) {\n const tensor = this.state.activeScope.track[i];\n if (!tensor.kept && !tensorsToTrackInParentSet.has(tensor.id)) {\n tensor.dispose();\n }\n }\n const oldScope = this.state.scopeStack.pop();\n this.state.activeScope = this.state.scopeStack.length === 0 ?\n null :\n this.state.scopeStack[this.state.scopeStack.length - 1];\n // Track the current result in the parent scope.\n tensorsToTrackInParent.forEach(tensor => {\n // Only track the tensor if was allocated in the inner scope and is not\n // globally kept.\n if (!tensor.kept && tensor.scopeId === oldScope.id) {\n this.track(tensor);\n }\n });\n }", "function setScope(node) {\n scope = node.scope;\n }", "function setScope(node) {\n scope = node.scope;\n }", "function endNode() {\n if (parent.children) {\n mergeChildren(parent.children);\n sortChildren(parent.children);\n }\n parent = parentsStack.pop();\n }", "end() {\n Object.assign(this.previousState, this.state); // Save the previous state\n this.state.inside = false;\n\n // Notify the nodes\n this.notify();\n }", "function addNodeScope(scope) {\n\tif (scope !== null) {\n\t addVariables(scope.variables);\n\t addNodeScope(scope.parent_scope);\n\t}\n }", "function applyScope() {\n\t\t\t\tif (!scope.$$phase) {\n\t\t\t\t\tscope.$apply();\n\t\t\t\t}\n\t\t\t}", "function mergeScopes(localScopes, parentScopes)\n {\n for (const scopeName in parentScopes)\n {\n if (!localScopes[scopeName])\n {\n localScopes[scopeName] = parentScopes[scopeName];\n }\n }\n }", "function Scope(node,parent){\n\t\tthis._nr = STACK.incr('scopes');\n\t\tthis._head = [];\n\t\tthis._node = node;\n\t\tthis._parent = parent;\n\t\tthis._vars = new VariableDeclaration([]);\n\t\tthis._meta = {};\n\t\tthis._annotations = [];\n\t\tthis._closure = this;\n\t\tthis._virtual = false;\n\t\tthis._counter = 0;\n\t\tthis._varmap = {};\n\t\tthis._varpool = [];\n\t}", "enterScope(branchIndex) {\n let parentScope;\n if (branchIndex == undefined) {\n parentScope = this.scope;\n\n } else if (branchIndex < this.scopes.length) {\n parentScope = this.scopes[branchIndex];\n\n } else {\n throw new Error(\"branchIndex out of range - environment.js\")\n }\n\n // Create the new scope\n let newScope = new Scope(parentScope);\n this.scopes.push(newScope);\n this.scope = newScope;\n }", "newStack() {\n const program = this.programsBuffer[this.currentProgram];\n if (program.attributeBuffer[program.currentStack].length == 0) {\n return program.currentStack;\n }\n program.attributeBuffer.push([]);\n program.currentStack = program.attributeBuffer.length - 1;\n return program.currentStack;\n }", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n }", "function party_leave(){\n\n\t//log.info(this.tsid+'.party_leave()');\n\n\tif (this.party) this.party.leave(this, 'left');\n}", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n }", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n }", "function findScope(tree, key) {\n var q = []\n , scope\n , info\n , node\n\n // Queue node for processing.\n function push(node) {\n q.push({node: node, scope: scope})\n }\n\n push(tree)\n\n while ((info = q.pop())) {\n node = info.node\n scope = info.scope\n\n // Stop processing and return the scope if this is the wanted node.\n if (key(node)) {\n return scope\n }\n\n // Add child nodes to visit from select attributes of this node, if the\n // current node is a block it will be used as the scope for the child\n // nodes otherwise the scope is inherited from the parent.\n\n if (node.type === 'BlockStatement') {\n scope = node\n }\n\n if (node.expression) {\n push(node.expression)\n }\n\n if (node.body) {\n if (node.body.forEach) {\n node.body.forEach(push)\n } else {\n push(node.body)\n }\n }\n\n if (node.callee) {\n node.arguments.forEach(push)\n push(node.callee)\n }\n\n if (node.object) {\n push(node.object)\n }\n }\n}", "_notifyScopeListeners() {\n\t // We need this check for this._notifyingListeners to be able to work on scope during updates\n\t // If this check is not here we'll produce endless recursion when something is done with the scope\n\t // during the callback.\n\t if (!this._notifyingListeners) {\n\t this._notifyingListeners = true;\n\t this._scopeListeners.forEach(callback => {\n\t callback(this);\n\t });\n\t this._notifyingListeners = false;\n\t }\n\t }", "function deleteScope(scope, newScope) {\n var handlers = void 0;\n var i = void 0;\n\n // No scope specified, get scope\n if (!scope) scope = getScope();\n\n for (var key in _handlers) {\n if (Object.prototype.hasOwnProperty.call(_handlers, key)) {\n handlers = _handlers[key];\n for (i = 0; i < handlers.length;) {\n if (handlers[i].scope === scope) handlers.splice(i, 1); else i++;\n }\n }\n }\n\n // If scope is deleted, reset scope to all\n if (getScope() === scope) setScope(newScope || 'all');\n }", "_notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }", "function updateAngular(e) {\n if (e.isTransactionFinished) scope.$apply();\n }", "function getScope (node, blockScope) {\n var parent = node\n while (parent.parent) {\n parent = parent.parent\n if (isFunction(parent)) {\n break\n }\n if (blockScope && parent.type === 'BlockStatement') {\n break\n }\n if (parent.type === 'Program') {\n break\n }\n }\n return parent\n}", "_notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }", "function updateAngular(e) {\n\t\t\t\tif (e.isTransactionFinished) {\n\t\t\t\t scope.$apply();\n\t\t\t\t}\n\t\t\t}", "function setScope(vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope(vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope(vnode) {\n\t var i;\n\t if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function scopeAndTypeCheck(root) {\n //Block sets scope\n if (root.nodeName === \"Block\") {\n //If seen before, go to parent scope\n if (root.visited === true) {\n currentScope = currentScope.parent;\n }\n else {\n //Has been visited, now\n root.visited = true;\n //Make new scope for new block\n if (currentScope !== null) {\n var oldScope = currentScope; //current scope is now old\n currentScope = new SymbolTableNode('Scope', currentScope.nodeVal + 1, {}, currentScope, []); //create a new scope\n oldScope.children.push(currentScope); //child of old scope\n currentScope.parent = oldScope; //scope is now the parent\n }\n else {\n currentScope = new SymbolTableNode('Scope', 0, {}, null, []);\n SymbolTableInstance = new SymbolTable(currentScope, currentScope);\n }\n //Check each Statement\n for (var i = 0; i < root.children.length; i++) {\n scopeAndTypeCheck(root.children[i]);\n }\n //When done checking all Statements under this Block, close the scope and return to the parent scope\n if (currentScope.parent !== null) {\n currentScope = currentScope.parent;\n }\n }\n }\n else if (root.nodeName === \"VariableDeclaration\") {\n //Set scope of variables\n root.children[1].scope = currentScope.nodeVal;\n //If this variable already exists in this scope...\n if (currentScope.find(root.children[1])) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[1].nodeVal + \" was redeclared on line \" + root.children[1].lineNumber);\n }\n else {\n currentScope.addVariable(root.children[1], root.children[0]);\n }\n }\n else if (root.nodeName === \"Assignment\") {\n //Set scope of variables\n root.children[1].scope = currentScope.nodeVal;\n root.children[0].scope = currentScope.nodeVal;\n //Variable has not been found yet\n var isFound = false;\n //Type of parent variable\n var parentType = \"\";\n //Check if var exists in current scope in symbol table - and parent scope, if not...\n if (root.children[0].nodeName === \"LeftVal\") {\n isFound = currentScope.find(root.children[0]);\n }\n //If variable is not found in current scope... must search parent scopes\n if (!isFound) {\n //Search all parent scopes, and save type if found\n if (currentScope.parent !== null) {\n var searchScope = currentScope.parent;\n isFound = searchScope.find(root.children[0]);\n if (isFound) {\n parentType = searchScope.getType(root.children[0]);\n }\n while (searchScope.parent !== null && !isFound) {\n searchScope = searchScope.parent;\n isFound = searchScope.find(root.children[0]);\n if (isFound) {\n parentType = searchScope.getType(root.children[0]);\n }\n }\n }\n //If still not found, it's undeclared.\n if (!isFound) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is not found on line \" + root.children[0].lineNumber);\n }\n else {\n root.children[0].isUsed = true;\n }\n }\n //Find the type - whether in this scope or in parent scope.\n var type = \"\";\n if (parentType === \"\") {\n type = currentScope.getType(root.children[0]);\n }\n else {\n type = parentType;\n }\n //The type of the RightVal.\n var otherType = \"\";\n if (root.children[1].nodeType === \"ID\") {\n otherType = currentScope.getType(root.children[1]);\n }\n //Type errors - mismatch of Left and Right sides\n if (otherType !== \"\" && type !== otherType) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is of type \" + type + \" and cannot be set to type \" + otherType + \" on line \" + root.children[0].lineNumber);\n }\n else if (otherType === \"\" && type !== root.children[1].nodeType) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is of type \" + type + \" and cannot be set to type \" + root.children[1].nodeType + \" on line \" + root.children[0].lineNumber);\n }\n }\n else if (root.nodeName === \"Output\") {\n //Set scope of variable\n root.children[0].scope = currentScope.nodeVal;\n //Variable is not yet found\n var isFound = false;\n //Check if var exists in current scope in symbol table - and parent scope, if not\n if (root.children[0].nodeName === \"OutputVal\") {\n if (root.children[0].nodeVal !== \"?\") {\n isFound = currentScope.find(root.children[0]);\n }\n }\n //\"?\" means literal - no scope errors are shown in case of printing a literal int, bool or string\n if (!isFound && root.children[0].nodeVal !== \"?\") {\n if (currentScope.parent !== null) {\n var searchScope = currentScope.parent;\n isFound = searchScope.find(root.children[0]);\n while (searchScope.parent !== null && !isFound) {\n searchScope = searchScope.parent;\n isFound = searchScope.find(root.children[0]);\n }\n }\n if (!isFound) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is not found on line \" + root.children[0].lineNumber);\n }\n else {\n root.children[0].isUsed = true; //Printing counts as variable use\n }\n }\n }\n else if (root.nodeName === \"If\" || root.nodeName === \"While\") {\n //Set scope of variables\n root.children[1].scope = currentScope.nodeVal;\n root.children[0].scope = currentScope.nodeVal;\n scopeAndTypeCheck(root.children[0]); //check test\n scopeAndTypeCheck(root.children[1]); //check block\n }\n else if (root.nodeName === \"CompareTest\") {\n //Set scope of variables\n root.children[0].scope = currentScope.nodeVal;\n root.children[1].scope = currentScope.nodeVal;\n var isFound = false;\n var parentType = \"\";\n //Check if var exists in current scope in symbol table - and parent scope, if not\n if (root.children[0].nodeName === \"LeftVal\") {\n isFound = currentScope.find(root.children[0]);\n }\n if (!isFound) {\n if (currentScope.parent !== null) {\n var searchScope = currentScope.parent;\n isFound = searchScope.find(root.children[0]);\n if (isFound) {\n parentType = searchScope.getType(root.children[0]);\n }\n while (searchScope.parent !== null && !isFound) {\n searchScope = searchScope.parent;\n isFound = searchScope.find(root.children[0]);\n if (isFound) {\n parentType = searchScope.getType(root.children[0]);\n }\n }\n }\n if (!isFound) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is not found on line \" + root.children[0].lineNumber);\n }\n else {\n root.children[0].isUsed = true; //Comparing counts as variable use\n }\n }\n var type = \"\";\n if (parentType === \"\") {\n type = currentScope.getType(root.children[0]);\n }\n else {\n type = parentType;\n }\n var otherType = \"\";\n if (root.children[1].nodeType === \"ID\") {\n otherType = currentScope.getType(root.children[1]);\n }\n //Type mismatches in comparability\n if (otherType !== \"\" && type !== otherType) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is of type \" + type + \" and cannot be compared to type \" + otherType + \" on line \" + root.children[0].lineNumber);\n }\n else if (otherType === \"\" && type !== root.children[1].nodeType) {\n errorlog(\"Semantic Analysis Error - Variable \" + root.children[0].nodeVal + \" is of type \" + type + \" and cannot be compared to type \" + root.children[1].nodeType + \" on line \" + root.children[0].lineNumber);\n }\n }\n else if (root.nodeName === \"Add\") {\n }\n else {\n }\n}", "function saveParamsToScope(node, state) {\n if (!node.scope) node.scope = {}\n node.params.forEach(function (param) {\n node.scope[param.name] = true\n })\n if (node.id) {\n var func = getCurrentScope(state.slice(0, -1))\n if (!func.scope) func.scope = {}\n func.scope[node.id.name] = true\n }\n}", "function checkscope() {\n var scope = \"local\"; // Here we overwrite the variable, scope now is \"local\".\n return scope;\n}", "function setScope(vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function setScope(vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "_rehydrateScope() {\n // We refill the scope here to not have an empty one\n core_1.configureScope(scope => {\n // tslint:disable:no-unsafe-any\n const loadedScope = core_1.Scope.clone(this._scopeStore.get());\n if (loadedScope._user) {\n scope.setUser(loadedScope._user);\n }\n scope.setTags(loadedScope._tags);\n scope.setExtras(loadedScope._extra);\n if (loadedScope._breadcrumbs) {\n loadedScope._breadcrumbs.forEach((crumb) => {\n scope.addBreadcrumb(crumb);\n });\n }\n // tslint:enable:no-unsafe-any\n });\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n\t var i;\n\t if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function setScope (vnode) {\n\t var i;\n\t if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function setScope (vnode) {\n\t var i;\n\t if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n}", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n}", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n}", "function lastAncestor(node, pred) {\n var ancestors = listAncestor(node);\n return lists.last(ancestors.filter(pred));\n}", "function checkscope2() {\n\t var scope = \"Local\";\n\t function nested() {\n\t\t var scope = \"nested\";\n\t\t return scope;\n\t }\n\t return nested();\n }", "getScopeIndex() {\n return this.scopes.length - 1;\n }", "assignMaxChainFromNeibhourNode(nodeIndex,currentChain, isChainModified,callBack){\r\n if(currentChain==null){\r\n currentChain=this.chain;\r\n }\r\n \r\n let currentChainLength=currentChain.length;\r\n if(nodeIndex==this.nodes.length){\r\n return callBack(isChainModified); \r\n }\r\n \r\n request(this.nodes[nodeIndex]+'/chain',{json:true},(err,response,data)=>{\r\n let newChain=currentChain;\r\n let newNodeIndex=nodeIndex+1;\r\n let chainModified=isChainModified;\r\n if(data.length>currentChainLength && this.isChainValid(data.chain)){\r\n newChain=data.chain; \r\n chainModified=true; \r\n }\r\n return this.assignMaxChainFromNeibhourNode(newNodeIndex,newChain,chainModified,callBack);\r\n });\r\n }", "function end() {\n currentLevel++;\n resetLevel();\n}", "function setScope (vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function setScope (vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function setScope (vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "function handleScope(scope) {\n // TODO (v8): Remove this guard. This was put in place because we introduced\n // Scope.getLastBreadcrumb mid-v7 which caused incompatibilities with older SDKs.\n // For now, we'll just return null if the method doesn't exist but we should eventually\n // get rid of this guard.\n const newBreadcrumb = scope.getLastBreadcrumb && scope.getLastBreadcrumb();\n\n // Listener can be called when breadcrumbs have not changed, so we store the\n // reference to the last crumb and only return a crumb if it has changed\n if (_LAST_BREADCRUMB === newBreadcrumb || !newBreadcrumb) {\n return null;\n }\n\n _LAST_BREADCRUMB = newBreadcrumb;\n\n if (\n newBreadcrumb.category &&\n (['fetch', 'xhr', 'sentry.event', 'sentry.transaction'].includes(newBreadcrumb.category) ||\n newBreadcrumb.category.startsWith('ui.'))\n ) {\n return null;\n }\n\n return createBreadcrumb(newBreadcrumb);\n }", "function setScope (vnode) {\n\t var i;\n\t var ancestor = vnode;\n\t while (ancestor) {\n\t if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t ancestor = ancestor.parent;\n\t }\n\t // for slot content they should also get the scopeId from the host instance.\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)\n\t ) {\n\t nodeOps.setAttribute(vnode.elm, i, '');\n\t }\n\t }", "replaceChain(chain) {\n if(chain.length> this.chain.length) {\n this.chain = chain\n }\n\n }", "function exit() {\n context[key] = current\n }", "scopesUpdated(scopes) {\n var role = _.cloneDeep(this.state.role);\n role.scopes = scopes;\n this.setState({role});\n }", "replaceChain(chain) {\n var condition1 = Blockchain.isValidChain(chain);\n var condition2 = this.chain.length < chain.length;\n if (condition1 && condition2) {\n this.chain = chain;\n console.log(\"Replacing chain with\", chain);\n }\n if (!condition2) {\n console.error(\"The incoming chain must be longer\");\n return;\n }\n if (!condition1) {\n console.error(\"The incoming chain must be valid\");\n return;\n }\n }", "function setScope (vnode) {\n let i\n let ancestor = vnode\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '')\n }\n ancestor = ancestor.parent\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)\n ) {\n nodeOps.setAttribute(vnode.elm, i, '')\n }\n }", "function elementEnd() {\n if (isParent) {\n isParent = false;\n }\n else {\n ngDevMode && assertHasParent();\n previousOrParentTNode = previousOrParentTNode.parent;\n }\n ngDevMode && assertNodeType(previousOrParentTNode, 3 /* Element */);\n currentQueries &&\n (currentQueries = currentQueries.addNode(previousOrParentTNode));\n queueLifecycleHooks(previousOrParentTNode.flags, tView);\n elementDepthCount--;\n}", "function setScope (vnode) {\n var i;\n if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n var i;\n if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n if (isDef(i = activeInstance) &&\n i !== vnode.context &&\n isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope (vnode) {\n\t var i\n\t if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '')\n\t }\n\t if (isDef(i = activeInstance) &&\n\t i !== vnode.context &&\n\t isDef(i = i.$options._scopeId)) {\n\t nodeOps.setAttribute(vnode.elm, i, '')\n\t }\n\t }", "function onItemLeaveEnd() {\n setActiveArray(function (prev) {\n prev.shift();\n return prev;\n });\n }", "propagateDownFromRight(node, parentPos, rightSibling) {\n let parentElement = node.parent.popAt(parentPos);\n this.addAtLastIndexOfCallStack(\n this.undoPopAt.bind(this, parentElement, node.parent, parentPos)\n );\n\n if (node.parent.hasLeftChildAt(parentPos)) {\n let nodeParentAtLeftChildOldValue = node.parent.at(parentPos).leftChild;\n node.parent.at(parentPos).leftChild = node;\n this.addAtLastIndexOfCallStack(\n () => {\n node.parent.at(parentPos).leftChild = nodeParentAtLeftChildOldValue;\n }\n )\n }\n\n let parentElementLeftChildOldValue = parentElement.leftChild;\n parentElement.leftChild = node.hasRightmostChild() ? node.getRightmostChild() : this.recentNode;\n this.addAtLastIndexOfCallStack(\n () => {\n parentElement.leftChild = parentElementLeftChildOldValue;\n }\n );\n\n let parentElementRightChildOldValue = parentElement.rightChild;\n parentElement.rightChild = null;\n this.addAtLastIndexOfCallStack(\n () => {\n parentElement.rightChild = parentElementRightChildOldValue;\n }\n );\n\n node.addLast(parentElement);\n this.addAtLastIndexOfCallStack(\n this.undoAddLast.bind(this, node)\n );\n\n let nodeIsLeafOldValue = node.isLeaf;\n node.isLeaf = node.isLeaf && rightSibling.isLeaf;\n this.addAtLastIndexOfCallStack(\n () => {\n node.isLeaf = nodeIsLeafOldValue;\n }\n );\n\n this.mergeToLeft(node, rightSibling);\n\n\n if (node.parent === this.root && this.root.size() === 0) {\n let rootOldValue = this.root;\n this.root = node;\n this.addAtLastIndexOfCallStack(\n () => {\n this.root = rootOldValue;\n }\n )\n\n let nodeParentOldValue = node.parent;\n node.parent = null;\n this.addAtLastIndexOfCallStack(\n () => {\n node.parent = nodeParentOldValue;\n }\n );\n }\n }", "function process_ir(scope_data) {\n var name, scope;\n\n // This loop is only needed if root_elements are not marked as shard_roots.\n for (name in scope_data.root_element_scopes) {\n scope = scope_data.root_element_scopes[name];\n if (!scope.is_shard_root()) {\n gather_dependencies(scope);\n }\n }\n for (name in scope_data.element_scopes) {\n scope = scope_data.element_scopes[name];\n if (scope.is_shard_root()) {\n gather_dependencies(scope);\n }\n }\n\n var pushed_deps = 0;\n for (name in scope_data.element_scopes) {\n scope = scope_data.element_scopes[name];\n if (!scope.is_shard_root() && !scope_data.root_element_scopes[name]) {\n var deps = get_scope_dependencies(scope_data.element_scopes[name]);\n for (var i = 0; i < deps.length; i++) {\n deps[i].destroy();\n pushed_deps++;\n }\n }\n }\n\n if (pushed_deps) {\n var pluralized = pushed_deps > 1 ? 'dependencies.' : 'dependency.';\n console.log('Moved', pushed_deps, 'scope', pluralized);\n }\n\n return scope_data;\n}", "endFrame() {\n this.#stack.push(this.#currentFrame);\n this.#currentFrame = new StateFrame();\n }", "function push(node) {\n q.push({node: node, scope: scope})\n }", "function setScope(vnode) {\n var i;\n if (isDef(i = vnode.fnScopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n } else {\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope(vnode) {\n var i;\n if (isDef(i = vnode.fnScopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n } else {\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function setScope(vnode) {\n var i;\n if (isDef(i = vnode.fnScopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n } else {\n var ancestor = vnode;\n while (ancestor) {\n if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n ancestor = ancestor.parent;\n }\n }\n // for slot content they should also get the scopeId from the host instance.\n if (isDef(i = activeInstance) && i !== vnode.context && i !== vnode.fnContext && isDef(i = i.$options._scopeId)) {\n nodeOps.setAttribute(vnode.elm, i, '');\n }\n }", "function walk(node, fn){\n\t\tvar previous = node.prev();\n\t\tif (!previous.length){\n\t\t\tprevious = node.parent();\n\t\t}\n\t\tvar oldContext = node.data('context'); // maintain contexts as a stack\n\t\tnode = fn(node);\n\t\tif (!node.length){\n\t\t\tprint('node replaced, backtracking');\n\t\t\tnode = previous;\n\t\t// } if (oldContext){\n\t\t// \tnode.data('context', oldContext);\n\t\t}\n\t\tvar child = node.children().first();\n\t\twhile(child.length){\n\t\t\tchild = walk(child, fn).next();\n\t\t}\n\t\treturn node;\n\t}", "function Scope( parent ) {\n\tthis.names = {}; // names defined in this scope\n\tthis.mangled = {}; // mangled names (orig.name => mangled)\n\tthis.rev_mangled = {}; // reverse lookup (mangled => orig.name)\n\tthis.cname = -1; // current mangled name\n\tthis.refs = {}; // names referenced from this scope\n\tthis.uses_with = false; // will become TRUE if with() is detected in this or any subscopes\n\tthis.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes\n\tthis.parent = parent; // parent scope\n\tthis.children = []; // sub-scopes\n\tif ( parent ) {\n\t\tthis.level = parent.level + 1;\n\t\tparent.children.push( this );\n\t} else {\n\t\tthis.level = 0;\n\t}\n}" ]
[ "0.6931558", "0.58581436", "0.58581436", "0.5771105", "0.5771105", "0.5771105", "0.5771105", "0.5771105", "0.5771105", "0.5771105", "0.5709378", "0.53929764", "0.5392312", "0.52479994", "0.5239648", "0.5136417", "0.5017755", "0.50041234", "0.49919394", "0.4937601", "0.48566982", "0.4832688", "0.48303926", "0.48269868", "0.48269868", "0.48185098", "0.4809464", "0.48017898", "0.47974327", "0.47879398", "0.47685677", "0.47623217", "0.47512725", "0.47420675", "0.47420675", "0.47402057", "0.47311258", "0.47179756", "0.4716232", "0.4714349", "0.4714349", "0.47122467", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.4708725", "0.47055563", "0.47055563", "0.47055563", "0.47055563", "0.47055563", "0.46905997", "0.46905997", "0.46905997", "0.46888897", "0.46888897", "0.46888897", "0.46888897", "0.46797854", "0.46748948", "0.4665437", "0.4658184", "0.4654841", "0.4654841", "0.4654841", "0.46544415", "0.46509707", "0.4633914", "0.46312252", "0.46310008", "0.4616826", "0.4612702", "0.45962167", "0.45945546", "0.45945546", "0.45945546", "0.45945546", "0.45945546", "0.45888165", "0.45869142", "0.4570676", "0.45704934", "0.45646077", "0.45595697", "0.4559162", "0.4559162", "0.4559162", "0.455372", "0.45533815" ]
0.7695766
0
pretty printing for scope information
function printScope(scope, node) { const declaredVars = scope.slice(1); const varsDisplay = declaredVars.length === 0 ? "NONE" : declaredVars.join(", "); if (node.type === "Program") { spprint( "printScope", `Variables declared in the global scope: ${varsDisplay}` ); } else { if (node.id && node.id.name) { spprint( "printScope", `Variables declared in the function ${node.id.name}(): ${varsDisplay}` ); } else { spprint( "printScope", `Variables declared in anonymous function: ${varsDisplay}` ); } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "dump() {\n\t\t\tconst lines = [];\n\n\t\t\tlines.push(\"# Scope \" + this.kind);\n\n\t\t\tif (this.globals.size > 0) {\n\t\t\t\tconst filteredGlobals = [];\n\t\t\t\tfor (const name of this.globals) {\n\t\t\t\t\tif (\n\t\t\t\t\t\t___R$$priv$project$rome$$internal$compiler$scope$Scope_ts$globalGlobals.includes(\n\t\t\t\t\t\t\tname,\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tfilteredGlobals.push(name);\n\t\t\t\t}\n\n\t\t\t\tif (filteredGlobals.length > 0) {\n\t\t\t\t\tlines.push(\"## Globals\");\n\n\t\t\t\t\tfor (const name of filteredGlobals) {\n\t\t\t\t\t\tlines.push(\" * \" + name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (this.bindings.size > 0) {\n\t\t\t\tlines.push(\"## Variables\");\n\t\t\t\tfor (const [name, binding] of this.bindings) {\n\t\t\t\t\tlines.push(\" * \" + binding.kind + \" \" + name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn lines.join(\"\\n\");\n\t\t}", "getScope() {}", "function scopeDemo(){\n\tvar name = \"function\";\n\tconsole.log(name);\n}", "function formatSuccess(scope) {\n return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(\", \") : scope}.`;\n}", "function printDetailsModified() {\n\treturn `${this.name} (${this.type}) - ${this.age}`;\n}", "inspect(opts = {}) {\n const options = {\n indent: 0,\n ...opts,\n };\n\n let indentation = '';\n for (let i = 0; i < options.indent; i++) {\n indentation += ' ';\n }\n\n let inspectString = `${indentation}(${this.constructor.name} marker=${this.marker.id})`;\n if (this.marker.isDestroyed()) {\n inspectString += ' [destroyed]';\n }\n if (!this.marker.isValid()) {\n inspectString += ' [invalid]';\n }\n return inspectString + '\\n';\n }", "function translateScope(rule) {\n if (rule.scope) {\n return `in ${rule.scope} tag`;\n }\n return '';\n}", "function scopeTestFunction() { \n const next = \"I am a writen second and Child Scoped.\" \n //will print \"I am a writen second and Child Scoped.\"\n console.log(next);\n //will print \"I am the first thing writen and from Global\"\n console.log(start);\n }", "function inspect(depth, opts) {\n return `[AwilixContainer (${parentContainer ? 'scoped, ' : ''}registrations: ${Object.keys(container.registrations).length})]`;\n }", "function Pretty(){}", "function printOrgChart(org, depth = 0) {\n const spacer = ' '.repeat(depth * 4);\n\n const keys = Object.keys(org);\n keys.forEach(key => {\n console.log(spacer + key);\n printOrgChart(org[key], depth + 1);\n });\n}", "function scope(){\n var a = 'A';\n let b = 'B';\n const c = 'C';\n console.log('FUNCION: '+ a,b,c)\n}", "function seeScope() {\n var testVar = \"first\";\n\n function showF() {\n console.log(testVar);\n // var testVar = \"second\";\n }\n\n showF();\n}", "function checkScope() {\n var myVars = 'local'; // Declare a local variable\n console.log(myVars);\n}", "printDebugString() {\n for (let i = 0; i < this.branches.length; i++) {\n if (this.branches[i] != null) {\n this.branches[i].printDebugString();\n }\n else {\n console.log(\"branch \" + i + \" hasn't been created yet.\");\n }\n }\n }", "function tlvScopeStyle(state, indentation, type) {\n // Begin scope.\n var depth = indentation / tlvIndentUnit; // TODO: Pass this in instead.\n return \"tlv-\" + state.tlvIndentationStyle[depth] + \"-\" + type;\n }", "function debug() {\n if (attrs.isDebug) {\n //stringify func\n var stringified = scope + \"\";\n \n // parse variable names\n var groupVariables = stringified\n //match var x-xx= {};\n .match(/var\\s+([\\w])+\\s*=\\s*{\\s*}/gi)\n //match xxx\n .map(d => d.match(/\\s+\\w*/gi).filter(s => s.trim()))\n //get xxx\n .map(v => v[0].trim());\n \n //assign local variables to the scope\n groupVariables.forEach(v => {\n main[\"P_\" + v] = eval(v);\n });\n }\n }", "function printClosureRecord(item) {\n\treturn item.head + \" --> \" + item.body.slice(0, item.dotPosition) + \" (*) \" + item.body.slice(item.dotPosition);\n}", "getScope() {\n\t return this.getStackTop().scope;\n\t }", "printPerson() {\n console.log(`Id ${this.id}, Name ${this.fname}, City ${this.city}`);\n console.log(\"Project \" , this.project);\n }", "getScope() {\n return this.getStackTop().scope;\n }", "pretty() {\n // output pretty formatted string\n let str = [];\n /**\n * Make a specified length space string\n * @param numberOfSpaces Length of output string\n */\n function makeSpaceStr(numberOfSpaces) {\n let res = [];\n for (let i = 0; i < numberOfSpaces; i++) {\n res.push(' ');\n }\n return res.join('');\n }\n function recursive(node, prefix, isLastChild, isRoot = false) {\n str.push(prefix);\n if (!isRoot) {\n str.push(\"--\");\n }\n str.push(node.name + '\\n');\n if (isLastChild) {\n prefix = makeSpaceStr(prefix.length);\n }\n if (!isRoot) {\n prefix += ' ';\n }\n if (node.childs != null) {\n let numberOfChilds = node.childs.length;\n for (let indexOfChild = 0; indexOfChild < numberOfChilds; indexOfChild++) {\n let child = node.childs[indexOfChild];\n if (indexOfChild == numberOfChilds - 1) {\n recursive(child, prefix + '`', true);\n }\n else {\n recursive(child, prefix + '|', false);\n }\n }\n }\n }\n recursive(this.root, '', false, true);\n return str.join('');\n }", "dump () {\n\t\tconsole.log(this.name + \" : \" + this.type);\n\t\tconsole.log(\"\\tActions\", this.actions);\n\t\tconsole.log(\"\\tConditions\", this.conditions);\n\t\tconsole.log(\"\\tExpressions\", this.expressions);\n\t}", "function inspect() {\n return '#<Hash:{' + this.map(function(pair) {\n return pair.map(Object.inspect).join(': ');\n }).join(', ') + '}>';\n }", "function inspect() {\n return '#<Hash:{' + this.map(function(pair) {\n return pair.map(Object.inspect).join(': ');\n }).join(', ') + '}>';\n }", "function print(objeto) {\n console.log(util.inspect(objeto,true,12,true))\n}", "function checkscope() {\n myVar = \"local\"; // Declare a local variable\n document.write(\"</br>\")\n document.write(myVar);\n}", "getScope() {\n return this.getStackTop().scope;\n }", "print() {\n return `${this.name} | E: ${this.email} | P: ${this.phone} | R: ${this.relation}`;\n }", "print(){\n\t return `eta = ${this._eta}\ntau_SFE = ${this._tau_SFE}`;\n\t}", "function deepPrint(x){\n console.log(util.inspect(x, {showHidden: false, depth: null}));\n}", "scopeName(prefix) {\n return this._extScope.name(prefix);\n }", "logBinding(lValue, rValue, scope) {\n if (this.logLevel < 20 /* VERBOSE */)\n return;\n console.log(`${scope == null ? \"\" : chalk.green(`(${scope}): `)}${chalk.red(lValue)} ->`, this.compactValue(rValue));\n }", "function logScope() {\n let localVar = 2;\n\n if (localVar) {\n let localVar = \"I'm different!\";\n console.log(\"nested: \", localVar)\n }\n\n console.log(\"logScope local: \", localVar);\n}", "function logScope() {\n var localVar = 2;\n\n if(localVar){\n var localVar = \"I'm Different!\";\n console.log(\"nested localVar: \", localVar);\n }\n\n console.log(\"logScope localVar: \", localVar);\n}", "print(){\n console.log(`${this.userName}, ${this.fileName}, ${this.descriptionOfRepoistory}, ${this.code}`); // method that prints the properties!\n\n }", "function printIntrospectionSchema(schema) {\n\t return printFilteredSchema(schema, isSpecDirective, isIntrospectionType);\n\t}", "show() {\n\t\tlet self=this;\n\t\tfor(let i in self.queue) {\n\t\t\tlet indent=0;\n\t\t\tself.prettyCommandObject(self.queue[i],indent);\n\t\t\tfor(let j in self.queue[i].commands) {\n\t\t\t\tindent++;\n\t\t\t\tself.prettyCommandObject(self.queue[i].commands[j],indent);\n\n\t\t\t}\n\t\t}\n\t}", "function printVar2() {\n const costanza = 'Belongs to the local scope of a function.'\n console.log(costanza); //Belongs to the local scope of a function.\n\n}", "print() {\n console.log(`${this.movieName}, ${this.rating}, ${this.yearRelased}`);\n }", "function currentNameScopePrefix() {\n if (_nameScopeStack.length === 0) {\n return '';\n }\n else {\n return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;\n }\n}", "function currentNameScopePrefix() {\n if (_nameScopeStack.length === 0) {\n return '';\n }\n else {\n return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;\n }\n}", "function currentNameScopePrefix() {\n if (_nameScopeStack.length === 0) {\n return '';\n }\n else {\n return _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;\n }\n}", "function getScope(element) {\n var path = [];\n var value = element.getAttribute(\"scope\")// || element.getAttribute(\"loop\");\n if(value) {\n // if(value.indexOf(\"window.\") != -1) return undefined;\n if(value[0] == \".\") return undefined; \n path = [value]\n }\n\n var element = element.parentNode;\n while(element.getAttribute) {\n var scope = element.getAttribute(\"scope\");\n if(scope) path.push(scope);\n element = element.parentNode\n } \n return path.length > 0 ? path.reverse().join(\".\") : undefined\n }", "printStack() {\n let str = '';\n this.items.forEach(item => str += (item + ' '));\n return str;\n }", "function pretty(obj){\n\tconsole.log(obj.length , obj);\n}", "function echo(text) {\n document.getElementById(\"lblScope\").innerHTML += text + \"<br />\";\n }", "print() {\n\t\treturn \"(\" + this._head + \", \" + this._tail + \" , \" + this._capacity + \", \" + this._flow + \")\";\n\t}", "prettyCommandObject(commandObject,indent) {\n\t\tlet self=this;\n\t\tlet string='';\n\t\tfor(var i=0;i<indent;i++) {\n\t\t\tstring+=' ';\n\t\t}\n\t\tlet color=self.DEFINE.CONSOLE_COL_GREEN;\n\t\tswitch(commandObject.state) {\n\t\t\tcase self.DEFINE.QUEUE_FINISHED:\n\t\t\t\tcolor=self.DEFINE.CONSOLE_COL_AMBER;\n\t\t\t\tbreak;\n\t\t\tcase self.DEFINE.QUEUE_ERROR:\n\t\t\t\tcolor=self.DEFINE.CONSOLE_COL_RED;\n\t\t\t\tbreak;\n\n\t\t}\n\t\tstring+=commandObject.queueable+'.'+commandObject.command+'('+JSON.stringify(commandObject.json)+','+JSON.stringify(commandObject.options)+');'\n\t\tconsole.log('%c '+string,color);\n\t\tif(commandObject.error)\n\t\t\tconsole.log('%c Stopped: '+commandObject.error,self.DEFINE.CONSOLE_COL_AMBER);\n\t}", "print() {\n if (!this.rangeCollection.length) return console.log('()')\n return console.log(this.rangeCollection.map(element => element.toString()).join(' '))\n }", "function scope(){\n \n var localScope = 'LOCALSCOPE';\n\n console.log ( globalScope );\n\n return localScope;\n\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n let result = \"\";\n const keys = getKeysOfEnumerableProperties(val);\n if (keys.length) {\n result += config.spacingOuter;\n const indentationNext = indentation + config.indent;\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const name = printer(key, config, indentationNext, depth, refs);\n const value = printer(val[key], config, indentationNext, depth, refs);\n result += indentationNext + name + \": \" + value;\n if (i < keys.length - 1) {\n result += \",\" + config.spacingInner;\n } else if (!config.min) {\n result += \",\";\n }\n }\n result += config.spacingOuter + indentation;\n }\n return result;\n}", "function scoper() {\n // let cat = 'Toby';\n console.log('cat inside scoper ', cat);\n function innerScope() {\n console.log('cat inside innerScope ', cat);\n }\n innerScope();\n}", "function logScope()\n{\n let localVar = 2; /* or var localVar = 2 */\n if (localVar)\n {\n let localVar = \"I'm different\";\n console.log(\"nested localVar: \", localVar);\n }\n console.log(\"logScope: \", localVar);\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';var keys$$1 = _Object$keys(val).sort();var symbols = getSymbols(val);if (symbols.length) {\n keys$$1 = keys$$1.filter(function (key) {\n return !isSymbol(key);\n }).concat(symbols);\n }if (keys$$1.length) {\n result += config.spacingOuter;var indentationNext = indentation + config.indent;for (var i = 0; i < keys$$1.length; i++) {\n var key = keys$$1[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys$$1.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n }", "function scopeExample() {\n let local = 'Indianapolis'; //'let' is tracked to the neareast curly boy/bracket - so 'local' can't be used anywhere other than these brackets = local scope \n let inner = 'it has many places to visit'\n console.log(local);\n console.log(`${local} is a humble city on ${global}`)\n if(true) {\n let inner = 'what a large city';\n console.log(inner); //this one reads the 'large city' - reads in purple curly boys \n }\n console.log(inner); // this one reads 'many places to visit' reads in the yellow curly boys\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';\n var keys = _Object$keys(val).sort();\n var symbols = getSymbols(val);\n\n if (symbols.length) {\n keys = keys.filter(function (key) {\n return !isSymbol(key);\n }).concat(symbols);\n }\n\n if (keys.length) {\n result += config.spacingOuter;\n\n var indentationNext = indentation + config.indent;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n }", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';\n var keys = _Object$keys(val).sort();\n var symbols = getSymbols(val);\n\n if (symbols.length) {\n keys = keys.filter(function (key) {\n return !isSymbol(key);\n }).concat(symbols);\n }\n\n if (keys.length) {\n result += config.spacingOuter;\n\n var indentationNext = indentation + config.indent;\n\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n }", "function logScope() {\n let localVar = 2;\n\n if (localVar) {\n let localVar = \"I'm different!\";\n console.log(\"nested localVar: \", localVar);\n }\n console.log(\"LogScope localVar: \", localVar);\n}", "get scope() {\n return this._scope;\n }", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n let result = '';\n const keys = getKeysOfEnumerableProperties(val, config.compareKeys);\n if (keys.length) {\n result += config.spacingOuter;\n const indentationNext = indentation + config.indent;\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const name = printer(key, config, indentationNext, depth, refs);\n const value = printer(val[key], config, indentationNext, depth, refs);\n result += `${indentationNext + name}: ${value}`;\n if (i < keys.length - 1) {\n result += `,${config.spacingInner}`;\n } else if (!config.min) {\n result += ',';\n }\n }\n result += config.spacingOuter + indentation;\n }\n return result;\n}", "prettyPrintCallback( cb ) {\n // get rid of \"function gen\" and start with parenthesis\n // const shortendCB = cb.toString().slice(9)\n const cbSplit = cb.toString().split('\\n')\n const cbTrim = cbSplit.slice( 3, -2 )\n const cbTabbed = cbTrim.map( v => ' ' + v ) \n \n return cbTabbed.join('\\n')\n }", "function print_well(){\n document.getElementById(\"well_json_prettyprint\").innerHTML = vkbeautify.json(JSON.stringify(temp_json),1);\n console.log('JSON.stringify(temp_json) = ',vkbeautify.json(JSON.stringify(temp_json),4))\n}", "function emitScopeProc (env, args) {\n\t var scope = env.proc('scope', 3);\n\t env.batchId = 'a2';\n\t\n\t var shared = env.shared;\n\t var CURRENT_STATE = shared.current;\n\t\n\t emitContext(env, scope, args.context);\n\t\n\t if (args.framebuffer) {\n\t args.framebuffer.append(env, scope);\n\t }\n\t\n\t sortState(Object.keys(args.state)).forEach(function (name) {\n\t var defn = args.state[name];\n\t var value = defn.append(env, scope);\n\t if (isArrayLike(value)) {\n\t value.forEach(function (v, i) {\n\t scope.set(env.next[name], '[' + i + ']', v);\n\t });\n\t } else {\n\t scope.set(shared.next, '.' + name, value);\n\t }\n\t });\n\t\n\t emitProfile(env, scope, args, true, true)\n\t\n\t ;[S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(\n\t function (opt) {\n\t var variable = args.draw[opt];\n\t if (!variable) {\n\t return\n\t }\n\t scope.set(shared.draw, '.' + opt, '' + variable.append(env, scope));\n\t });\n\t\n\t Object.keys(args.uniforms).forEach(function (opt) {\n\t scope.set(\n\t shared.uniforms,\n\t '[' + stringStore.id(opt) + ']',\n\t args.uniforms[opt].append(env, scope));\n\t });\n\t\n\t Object.keys(args.attributes).forEach(function (name) {\n\t var record = args.attributes[name].append(env, scope);\n\t var scopeAttrib = env.scopeAttrib(name);\n\t Object.keys(new AttributeRecord()).forEach(function (prop) {\n\t scope.set(scopeAttrib, '.' + prop, record[prop]);\n\t });\n\t });\n\t\n\t function saveShader (name) {\n\t var shader = args.shader[name];\n\t if (shader) {\n\t scope.set(shared.shader, '.' + name, shader.append(env, scope));\n\t }\n\t }\n\t saveShader(S_VERT);\n\t saveShader(S_FRAG);\n\t\n\t if (Object.keys(args.state).length > 0) {\n\t scope(CURRENT_STATE, '.dirty=true;');\n\t scope.exit(CURRENT_STATE, '.dirty=true;');\n\t }\n\t\n\t scope('a1(', env.shared.context, ',a0,', env.batchId, ');');\n\t }", "function printRole() {\n for (i=0; i<devs.length; i++){\n let name = devs[i].name;\n let tech = devs[i].tech_stack;\n console.log(`${name} specializes is ${tech}.`);\n }\n }", "function showPrintingDiagnostics() {\n showPrintingCropMarks();\n showPrintingDescription();\n showPrintingRulers();\n}", "function watchExp(){\n var obj = parsed(scope);\n return [obj, obj.$priority, obj.$value];\n }", "function watchExp(){\n var obj = parsed(scope);\n return [obj, obj.$priority, obj.$value];\n }", "debug() {\n var counts = {};\n for (var key in BlockType) {\n counts[key] = 0;\n }\n for (var i = 0; i < this.blocks.length; ++i) {\n console.log(`${this.blocks[i].type}: ${this.blocks[i].lines[0]}`);\n }\n console.log(counts);\n }", "function printVars(){\n console.log(\"current account:\", account);\n console.log(\"network id\", networkId);\n console.log(\"DAI balance: \", daiTokenBalance);\n console.log(\"fiji balance: \", fijiTokenBalance);\n console.log(\"staking balance: \", stakingBalance);\n }", "print () {\n return this.ranges.reduce((acc, cur, idx) => {\n if (idx % 2) {\n acc += `${cur}) `\n } else {\n acc += `[${cur}, `\n }\n return acc\n }, '').trim()\n }", "print() {\n if (this._isEdge) {\n return this._printEdgeFriendly();\n }\n\n this._openGroup();\n\n this._logs.forEach((logDetails) => {\n this._printLogDetails(logDetails);\n });\n\n this._childGroups.forEach((group) => {\n group.print();\n });\n\n this._closeGroup();\n }", "static inspect(obj) {\n const str = util.inspect(obj, false, null);\n\n for (let count = -1, index = 0; index !== -1; count++, index = str.indexOf('\\n', index + 1))\n if (count > 1)\n return this.indent(\"\\n\" + str, 8);\n\n return str;\n }", "function debugDisplayMembers(obj) {\n\tvar getters = new Array();\n\tvar setters = new Array();\n\tvar others = new Array();\n\tvar sKey;\n\n\tfor (var key in obj) {\n\t\tsKey = key + \"\";\n\t\tif (!((sKey.length > 0) && (sKey[0] == '_'))) {\n\t\t\tswitch (sKey.substr(0, 4)) {\n\t\t\t\tcase 'get_':\n\t\t\t\t\tgetters.push(key);\n\t\t\t\t\tbreak;\n\t\t\t\tcase 'set_':\n\t\t\t\t\tsetters.push(key);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tothers.push(key);\n\t\t\t}\n\t\t}\n\t}\n\n\tgetters.sort();\n\tsetters.sort();\n\tothers.sort();\n\n\talert(others.join(\", \") + \"\\r\\n\\r\\n\" +\n\t\tgetters.join(\", \") + \"\\r\\n\\r\\n\" +\n\t\tsetters.join(\", \"));\n}", "function printTypeDecl(type) {\n if (type.kind === TypeKind.LIST) {\n return '[' + printTypeDecl(type.ofType) + ']';\n } else if (type.kind === TypeKind.NON_NULL) {\n return printTypeDecl(type.ofType) + '!';\n } else {\n return type.name;\n }\n}", "printListPretty() {\n \tconst array = [];\n \tlet currentNode = this.head;\n \twhile(currentNode !== null) {\n \t\tarray.push(currentNode.value);\n \t\tcurrentNode = currentNode.next;\n \t}\n \treturn array.join('->');\n }", "__init4() {this.scopes = []}", "displayInConsole() {\n console.log(\"{ name: \" + this.name + \", colors: \" + this.colors + \", manaCost: \" + this.manaCost + \", type: \" + this.modifier + \", TCGPlayer price: \" + this.tcgprice + \", Card Kingdom price: \" + this.ckprice);\n }", "function cashTransactionsPageScopeChanged($scope) {\n return \" Cash Balance Counter: \" + $scope.current.cashbalanceCounter +\n \t \" Display Deleted: \" + $scope.current.displayDeleted;\n}", "function printExprOfPrototype(id, localToArea, localToDefun) {\n var area;\n\n function allExpr(areaId, nodes) {\n var node = nodes[id];\n\n if (node && node.prototype.localToArea === localToArea &&\n node.prototype.localToDefun === localToDefun) {\n console.log(areaId.join(\":\"), \"#\" + node.watcherId, \n \"active=\" + node.nrActiveWatchers,\n \"value=\" + (node.result === undefined? \"<undefined>\": vstringifyLim(node.result.value, 80)),\n \"size=\" + (node.result !== undefined && node.result.value instanceof Array? node.result.value.length: 1));\n }\n if (localToDefun !== 0) {\n for (var i = 0; i < nodes.length; i++) {\n node = nodes[i];\n if (node) {\n if (node instanceof EvaluationApply ||\n node instanceof EvaluationMap ||\n node instanceof EvaluationFilter ||\n node instanceof EvaluationMultiQuery) {\n if (node.environment !== undefined) {\n allExpr(areaId, node.environment.cache);\n } else if (node.environments !== undefined) {\n for (var j = 0; j < node.environments.length; j++) {\n allExpr(areaId, node.environments[j].cache);\n }\n }\n }\n }\n }\n }\n }\n\n if (localToArea > 0) {\n for (var areaId in allAreaMonitor.allAreas) {\n area = allAreaMonitor.allAreas[areaId];\n if (area.template.id === localToArea || localToDefun !== 0) {\n allExpr([area.areaId], area.evaluationNodes[0]);\n }\n }\n } else {\n allExpr([\"global\"], globalEvaluationNodes);\n }\n}", "displayAspects() { console.log(this.logtags); }", "function printSchema(schema) {\n return printFilteredSchema(schema, function (n) {\n return !isSpecDirective(n);\n }, isDefinedType);\n}", "function printSchema(schema) {\n return printFilteredSchema(schema, function (n) {\n return !isSpecDirective(n);\n }, isDefinedType);\n}", "getDump(indent = '') {\n let result = indent + ts.SyntaxKind[this.node.kind] + ': ';\n if (this.prefix) {\n result += ' pre=[' + this._getTrimmed(this.prefix) + ']';\n }\n if (this.suffix) {\n result += ' suf=[' + this._getTrimmed(this.suffix) + ']';\n }\n if (this.separator) {\n result += ' sep=[' + this._getTrimmed(this.separator) + ']';\n }\n result += '\\n';\n for (const child of this.children) {\n result += child.getDump(indent + ' ');\n }\n return result;\n }", "function printStacks() {\n console.log(\"a: \" + stacks.a);\n console.log(\"b: \" + stacks.b);\n console.log(\"c: \" + stacks.c);\n}", "function printStacks() {\n console.log(\"a: \" + stacks.a);\n console.log(\"b: \" + stacks.b);\n console.log(\"c: \" + stacks.c);\n}", "function printStacks() {\n console.log(\"a: \" + stacks.a);\n console.log(\"b: \" + stacks.b);\n console.log(\"c: \" + stacks.c);\n}", "function printStacks() {\n console.log(\"a: \" + stacks.a);\n console.log(\"b: \" + stacks.b);\n console.log(\"c: \" + stacks.c);\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n var result = '';\n var keys$$1 = _Object$keys(val).sort();\n var symbols = getSymbols(val);\n\n if (symbols.length) {\n keys$$1 = keys$$1.filter(function (key) {\n return !isSymbol$1(key);\n }).concat(symbols);\n }\n\n if (keys$$1.length) {\n result += config.spacingOuter;\n\n var indentationNext = indentation + config.indent;\n\n for (var i = 0; i < keys$$1.length; i++) {\n var key = keys$$1[i];\n var name = printer(key, config, indentationNext, depth, refs);\n var value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys$$1.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n}", "function prettyPrintObject(obj){\n console.log(chalk.gray('----------------------'));\n for(let prop in obj){\n console.log(` |> ${chalk.magenta(prop)}: ${chalk.cyan(obj[prop])}`);\n }\n console.log(chalk.gray('----------------------'));\n}", "function printChain(o){\n console.log(\"=== printChain (begin) ===\");\n var level = 1;\n\n function print(level, value){\n\tconsole.log(\" \".repeat(level-1) + \"+--- \" + value);\n }\n \n function browseProperties (o,level) {\n\tvar temp = Object.getOwnPropertyNames(o);\n\tfor (var i in temp)\n\t print(level, temp[i] + ': ' + o[temp[i]]);\n\tvar proto = Object.getPrototypeOf(o);\n\tif ((proto === undefined) || (proto === null))\n\t return;\n\telse {\n\t level += 1;\n\t browseProperties(proto,level);\n\t}\n }\n\n browseProperties(o, 1);\n console.log(\"=== printChain (end) ===\");\n}", "function printObjectProperties(val, config, indentation, depth, refs, printer) {\n let result = '';\n let keys = Object.keys(val).sort();\n const symbols = getSymbols(val);\n\n if (symbols.length) {\n keys = keys.filter(key => !isSymbol(key)).concat(symbols);\n }\n\n if (keys.length) {\n result += config.spacingOuter;\n\n const indentationNext = indentation + config.indent;\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n const name = printer(key, config, indentationNext, depth, refs);\n const value = printer(val[key], config, indentationNext, depth, refs);\n\n result += indentationNext + name + ': ' + value;\n\n if (i < keys.length - 1) {\n result += ',' + config.spacingInner;\n } else if (!config.min) {\n result += ',';\n }\n }\n\n result += config.spacingOuter + indentation;\n }\n\n return result;\n}", "function anotherlogScope () {\n let localVar = 2 ; \n if (localVar ) {\n let localVar = \"i'm different \" ; \n console.log(\"nested localVar : \" , localVar) ; \n }\n console.log(\"logScope localVar : \" , localVar) ; \n}", "function printName(value){ //the variable \"lastName\" is function scoped, only avaiale\n var lastName = \"dennis\"; //inside of the function. The globally scoped \"name\" variable\n console.log(name + \" \" + lastName);}", "function dump_state()\n{\n var str = \"\";\n var comma = \"\";\n for (i in stock.cards) {\n var card = stock.cards[i];\n str += comma + card.toString();\n comma = \", \";\n }\n console.log(\"stock: \" + str);\n\n str = \"\";\n comma = \"\";\n for (i in waste.cards) {\n var card = waste.cards[i];\n str += comma + card.toString();\n comma = \", \";\n }\n console.log(\"waste: \" + str);\n\n for (ti in tableaus) {\n str = \"\"\n comma = \"\"\n var tableau = tableaus[ti];\n for (ci in tableau.cards) {\n var card = tableau.cards[ci];\n str += comma + card.toString();\n comma = \", \";\n }\n console.log(\"tableau \" + ti + \": \" + str);\n }\n\n for (fi in foundations) {\n str = \"\"\n comma = \"\"\n var foundation = foundations[fi];\n for (ci in foundation.cards) {\n var card = foundation.cards[ci];\n str += comma + card.toString();\n comma = \", \";\n }\n console.log(\"foundation \" + fi + \": \" + str);\n }\n}", "debug() {\n console.log(this.get_all().map(x => `${x}`).join(\"; \"));\n }", "printStack() \n { \n var str = \"\"; \n for (var i = 0; i < this.items.length; i++) \n str += this.items[i] + \" \"; \n return str; \n }", "function scope1() {\n var top = \"top\";\n bottom = \"bottom\";\n console.log(bottom);\n\n var bottom;\n}", "print() {\n const printout = JSON.stringify(this.graph, null, 4);\n console.log(printout);\n return printout;\n }", "function emitScopeProc (env, args) {\n var scope = env.proc('scope', 3);\n env.batchId = 'a2';\n\n var shared = env.shared;\n var CURRENT_STATE = shared.current;\n\n emitContext(env, scope, args.context);\n\n if (args.framebuffer) {\n args.framebuffer.append(env, scope);\n }\n\n sortState(Object.keys(args.state)).forEach(function (name) {\n var defn = args.state[name];\n var value = defn.append(env, scope);\n if (isArrayLike(value)) {\n value.forEach(function (v, i) {\n scope.set(env.next[name], '[' + i + ']', v);\n });\n } else {\n scope.set(shared.next, '.' + name, value);\n }\n });\n\n emitProfile(env, scope, args, true, true)\n\n ;[S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach(\n function (opt) {\n var variable = args.draw[opt];\n if (!variable) {\n return\n }\n scope.set(shared.draw, '.' + opt, '' + variable.append(env, scope));\n });\n\n Object.keys(args.uniforms).forEach(function (opt) {\n scope.set(\n shared.uniforms,\n '[' + stringStore.id(opt) + ']',\n args.uniforms[opt].append(env, scope));\n });\n\n Object.keys(args.attributes).forEach(function (name) {\n var record = args.attributes[name].append(env, scope);\n var scopeAttrib = env.scopeAttrib(name);\n Object.keys(new AttributeRecord()).forEach(function (prop) {\n scope.set(scopeAttrib, '.' + prop, record[prop]);\n });\n });\n\n function saveShader (name) {\n var shader = args.shader[name];\n if (shader) {\n scope.set(shared.shader, '.' + name, shader.append(env, scope));\n }\n }\n saveShader(S_VERT);\n saveShader(S_FRAG);\n\n if (Object.keys(args.state).length > 0) {\n scope(CURRENT_STATE, '.dirty=true;');\n scope.exit(CURRENT_STATE, '.dirty=true;');\n }\n\n scope('a1(', env.shared.context, ',a0,', env.batchId, ');');\n }" ]
[ "0.7366412", "0.6223988", "0.5859145", "0.5858953", "0.5725868", "0.5722273", "0.5664104", "0.5657852", "0.5618329", "0.557921", "0.55308086", "0.55182993", "0.5517898", "0.5510549", "0.5502653", "0.54921526", "0.5486849", "0.545588", "0.5449265", "0.5442129", "0.54404306", "0.5431499", "0.5418189", "0.54167503", "0.54167503", "0.5413527", "0.54109883", "0.53984034", "0.5392056", "0.53909916", "0.53906995", "0.53905725", "0.5369127", "0.53634757", "0.5338805", "0.5325859", "0.53240883", "0.5319332", "0.5302938", "0.5286797", "0.5285362", "0.5285362", "0.5285362", "0.5280591", "0.52801454", "0.5273183", "0.52474445", "0.5242252", "0.5231256", "0.52170306", "0.5212007", "0.5209946", "0.5206815", "0.5204592", "0.52039754", "0.5198347", "0.5196956", "0.5196956", "0.5195", "0.51937324", "0.51907784", "0.5186841", "0.5184139", "0.51768434", "0.51723605", "0.5161092", "0.5158607", "0.5158607", "0.51526946", "0.5147508", "0.5145872", "0.5145053", "0.51397175", "0.51378703", "0.51268196", "0.5114873", "0.5111698", "0.5109839", "0.51043534", "0.5104166", "0.5099489", "0.5098721", "0.5098721", "0.5090289", "0.5082804", "0.5082804", "0.5082804", "0.5082804", "0.5081835", "0.50803065", "0.5078891", "0.5075949", "0.50750744", "0.50698066", "0.50680447", "0.5061495", "0.50576556", "0.5057004", "0.5056527", "0.50564563" ]
0.67236197
1
the name of a variable is located in different spots depending on the AST node type. This helper function accesses the name of a variable depending on the node type.
function getVarName(node) { let varName = null; switch (node.type) { case "AssignmentExpression": varName = node.left.name; break; case "VariableDeclarator": varName = node.id.name; break; case "ExpressionStatement": if (node.expression.left.type === "MemberExpression") { if (typeof node.expression.left.name === "string") { varName = node.expression.left.name; } else { varName = node.expression.left.object.name; } break; } else { varName = node.expression.left.name; break; } default: varName = `"DIDN'T CATCH CASE for type ${node.type}"`; } return varName; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "determineName() {\r\n\t\t\t\t\tvar message, name, node, ref1, tail;\r\n\t\t\t\t\tif (!this.variable) {\r\n\t\t\t\t\t\treturn null;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tref1 = this.variable.properties, [tail] = slice1.call(ref1, -1);\r\n\t\t\t\t\tnode = tail ? tail instanceof Access && tail.name : this.variable.base;\r\n\t\t\t\t\tif (!(node instanceof IdentifierLiteral || node instanceof PropertyName)) {\r\n\t\t\t\t\t\treturn null;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tname = node.value;\r\n\t\t\t\t\tif (!tail) {\r\n\t\t\t\t\t\tmessage = isUnassignable(name);\r\n\t\t\t\t\t\tif (message) {\r\n\t\t\t\t\t\t\tthis.variable.error(message);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (indexOf.call(JS_FORBIDDEN, name) >= 0) {\r\n\t\t\t\t\t\treturn `_${name}`;\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\treturn name;\r\n\t\t\t\t\t}\r\n\t\t\t\t}", "parseVarName() {\n const token = this.input.next();\n if (token.type != \"var\") this.input.croak(\"Expect variable name\");\n return token.value;\n }", "function getName(node) {\n\tvar str = node.name;\n\tif (varTab.hasOwnProperty(str)) return varTab[str];\n var name = \"_\" + (++count);\n return varTab[str] = { name: name, node: node };\n}", "variableOf(name) {\n\t\tfor (const v of this._vars) {\n\t\t\tif (v.name() === name) return v;\n\t\t}\n\t\treturn null;\n\t}", "function extractVariableName(node) {\n return node !== undefined && ts.isIdentifier(node) ? node.escapedText.toString() : '$';\n}", "function getIdentifierVariableName(path) {\n if (path.isIdentifier() && path.parentPath.isCallExpression() && path.parentPath.parentPath.isVariableDeclarator()) {\n const variableName = path.parentPath.parentPath.node.id.name;\n return variableName;\n }\n\n return '';\n}", "function getVariable(str) {\n\n return str;\n}", "static getVariableNames(node) {\n if (node.type === 'VariableDeclaration') {\n let decl = node;\n return decl.declarations.map(d => {\n let varName = EsprimaHelper.patternToString(d.id);\n return varName;\n });\n }\n else if (node.type === 'AssignmentExpression') {\n let decl = node;\n let varName = EsprimaHelper.patternToString(decl.left);\n return [varName];\n }\n else if (node.type === 'FunctionDeclaration') {\n let func = node;\n return func.params.map(p => {\n let varName = EsprimaHelper.patternToString(p);\n return varName;\n });\n }\n return [];\n }", "function readVariable(){\r\n\t\tvar ret={name:\"\"};\r\n\t\tnext();\r\n\t\treturn {name:word}\r\n\t\tswitch(type){\r\n\t\t\tcase \"word\":\r\n\t\t\t\tret.name=word;\r\n\t\t\tbreak;default:\r\n\t\t\t\treadNext=0;\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\t\treturn ret;\r\n\t}", "variable(name) {\r\n\r\n // Check which one it is\r\n name = name.toLowerCase()\r\n if (name == \"user.displayname\") {\r\n\r\n // Get user's name\r\n return Account.username || \"User\"\r\n\r\n } else if (name == \"input\") {\r\n\r\n // Get previous action's input\r\n return this.lastActionInput\r\n\r\n } else {\r\n\r\n // Unkown variable, return value from the variable storage\r\n return this.localEntity.variables[name]\r\n\r\n }\r\n\r\n }", "function getNameValue(variable) {\n switch (variable.expression.type) {\n case 'StringLiteral':\n return { name: variable.name, value: variable.expression.value }\n case 'NumberLiteral':\n return { name: variable.name, value: variable.expression.number }\n default:\n throw new Error(`Unknown Expressions ${variable.expression.type}`)\n }\n }", "function getvar(name) {\n\t\treturn window[name];\n\t}", "function setVariableName(varName, alias, variableData, generateNewName){\n\t// console.log(\"----------------------------------------\");\n\t// console.log(varName, alias, variableData);\n\t// console.log(\"expressionLevelNames\", expressionLevelNames);\n\t// console.log(\"variableNamesClass\", variableNamesClass);\n\t// console.log(\"variableNamesAll\", variableNamesAll);\n\t// console.log(\"rrrrrrrrr\", variableNamesClass[varName]);\n\t// console.log(\"----------------------------------------\");\n\t// console.log(\" \");\n\tif(alias != null) {\n\t\t//console.log(\"1111\", varName, alias);\n\t\tvar aliasSet = false;\n\t\tfor(var key in idTable){\n\t\t\tif (idTable[key] == alias) {\n\t\t\t\tvariableNamesAll[alias] = {\"alias\" : alias + \"_\" +counter, \"nameIsTaken\" : true, \"counter\" : counter, \"isVar\" : true};\n\t\t\t\taliasSet = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aliasSet == false) variableNamesAll[alias] = {\"alias\" : alias, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : true};\n\t\t\n\t\treturn variableNamesAll[alias][\"alias\"];\n\t}\n\telse if(variableData[\"kind\"] == \"PROPERTY_NAME\" || typeof variableData[\"kind\"] === 'undefined'){\n\t\t// console.log(\"2222\", varName);\n\t\t//??????????????????????????????????????\n\t\t//if(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && typeof variableNamesClass[varName][\"isvar\"] !== 'undefined' && variableNamesClass[varName][\"isvar\"] != true))applyExistsToFilter = true;\n\t\tif(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && (variableNamesClass[varName][\"isVar\"] != true ||\n\t\t\tvariableData[\"type\"] != null && (typeof variableData[\"type\"][\"maxCardinality\"] === 'undefined' || variableData[\"type\"][\"maxCardinality\"] > 1 || variableData[\"type\"][\"maxCardinality\"] == -1))))applyExistsToFilter = true;\n\t\t//??????????????????????????????????????\n\t\tif(generateNewName != null && generateNewName == true ){\n\t\t\t// console.log(\"2aaaa\", varName);\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\tif(typeof variableNamesClass[varName]=== 'undefined'){\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\texpressionLevelNames[varName] = varName;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false};\n\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false};\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\texpressionLevelNames[varName] = varName + \"_\" +count;\n\t\t\t\t\t\tvariableNamesAll[varName][\"counter\"] = count;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName + \"_\" +count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesAll[varName][\"isVar\"]};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\texpressionLevelNames[varName] = varName + \"_\" +count;\n\t\t\t\t\tvariableNamesClass[varName][\"counter\"] = count;\n\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName + \"_\" +count, \"nameIsTaken\" : variableNamesClass[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesClass[varName][\"isVar\"]};\n\t\t\t\t\t//console.log(count, varName + \"_\" +count, variableNamesClass[varName][\"counter\"], variableNamesAll[varName][\"counter\"])\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t// cardinality is more then 1 or is unknown (for each variable new definition)\n\t\t} else if(variableData[\"type\"] != null && (typeof variableData[\"type\"][\"maxCardinality\"] === 'undefined' || variableData[\"type\"][\"maxCardinality\"] > 1 || variableData[\"type\"][\"maxCardinality\"] == -1)){\n\t\t// console.log(\"2bbbb\", varName);\t\t \n\t\t //if not used in given expression\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\t//if not used in class scope\n\t\t\t\tif(typeof variableNamesClass[varName] === 'undefined'){\n\t\t\t\t\t//if not used in query scope\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\t//not used at all\n\t\t\t\t\t\t\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_1\", \"nameIsTaken\" : false, \"counter\" : 1, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t\n\t\t\t\t\t//is used in query, but not in a given class (somewhere else)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\t\tif(variableNamesAll[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesAll[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar}; //????? vai vajag\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//is expression\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t}\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t//is used in a given class\n\t\t\t\t}else{\n\t\t\t\t\t//if simple variable\n\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesClass[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t}\n\t\t\t\t\t//is expression\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t}\n\t\t\t//used in given expression\n\t\t\t} else {\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}\n\t\t// cardinality is <=1\n\t\telse{\n\t\t\t// console.log(\"2cccc\", varName, isSimpleVariableForNameDef);\n\t\t\t//if not used in given expression\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\t// console.log(\"2c 1\", varName);\n\t\t\t\t//if not used in class scope\n\t\t\t\tif(typeof variableNamesClass[varName] === 'undefined'){\n\t\t\t\t\t// console.log(\"2c 11\", varName);\n\t\t\t\t\t//if not used in query scope\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\t//not used at all\n\t\t\t\t\t\t// console.log(\"2c 111\", varName, parseType);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_1\", \"nameIsTaken\" : false, \"counter\" : 1, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t\n\t\t\t\t\t//is used in query, but not in a given class (somewhere else)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// console.log(\"2c 112\", varName);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\t\tif(variableNamesAll[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesAll[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar}; //????? vai vajag\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//is expression\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t}\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t//is used in a given class\n\t\t\t\t}else{\n\t\t\t\t\t// console.log(\"2c 12\", varName);\n\t\t\t\t\t//if simple variable\n\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t// console.log(\"2c 121\", varName);\n\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\tif(parseType == \"attribute\") tempIsVar = true;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName, \"nameIsTaken\" : true, \"counter\" : variableNamesClass[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//if name is not defined as variable\n\t\t\t\t\t\t\tif(variableNamesClass[varName][\"isVar\"] != true) {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t//is expression\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// console.log(\"2c 122\", varName);\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : false, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} //else {\n\t\t\t\t\t\t//\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t//\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count};\n\t\t\t\t\t\t//}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t}\n\t\t\t//used in given expression\n\t\t\t} else {\n\t\t\t\t// console.log(\"2c 2\", varName);\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}\n\t\treturn expressionLevelNames[varName];\n\t} else {\n\t\t//console.log(\"3333\", varName);\n\t\treturn varName;\n\t}\n}", "function findVariable(name, varsByScope)\n{\n // Search outwards through the scopes for any variables with the same\n // name. Innermost scope is at the end of the array.\n for (var i = varsByScope.length - 1; i >= 0 ; i--)\n {\n // Look for a variable with the same name in this scope\n if (name in varsByScope[i])\n {\n return varsByScope[i][name];\n }\n }\n return null;\n}", "function makeVar(root, name) {\n name = name.toLowerCase().replace(/\\W/g, '_');\n return ' var ' + root + '_' + name;\n }", "function translate(varName)\n{\n with(this)\n {\n var name = varName.toLowerCase();\n if(name.indexOf(\"[\") != -1)\n name = name.substr(0, name.indexOf(\"[\"));\n // does javascript do perl type substitution?? i wish\n if(name == \"definitions\")\n return definitions;\n else if(name == \"service\")\n return service;\n else if(name == \"porttype\")\n return porttype;\n else if(name == \"binding\")\n return binding;\n } \n}", "function pgp_getVar(varName){\r\n\treturn varName+pgp_location;\r\n}", "function findVariable (dataClass, varName)\n{\n\t\n\t//search qualitative\n\tif(dataClass=='super')\n\t{\n\t\tfor(var j in superUsage.names)\n\t\t{\n\t\t\tif(superUsage.names[j].toLowerCase()==varName)\n\t\t\t\treturn j;\n\t\t}\n\t}\n\t\n\t//search quantitative\n\telse\t\n\t{\n\t\tfor(var j in varUsage.names)\n\t\t{\n\t\t\tif(varUsage.names[j].toLowerCase()==varName)\n\t\t\t{\n\t\t\t\treturn j;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t//no match\n\tconsole.error(\"ERROR: Invalid dataset name: \"+varName);\n\treturn -1;\n}", "get name() {\n const context = getLContext(this.nativeNode);\n if (context !== null) {\n const lView = context.lView;\n const tData = lView[TVIEW].data;\n const tNode = tData[context.nodeIndex];\n return tNode.value;\n }\n else {\n return this.nativeNode.nodeName;\n }\n }", "function tryGetName(node) {\n if (node.kind === 225 /* ModuleDeclaration */) {\n return getModuleName(node);\n }\n var decl = node;\n if (decl.name) {\n return ts.getPropertyNameForPropertyNameNode(decl.name);\n }\n switch (node.kind) {\n case 179 /* FunctionExpression */:\n case 180 /* ArrowFunction */:\n case 192 /* ClassExpression */:\n return getFunctionOrClassName(node);\n case 279 /* JSDocTypedefTag */:\n return getJSDocTypedefTagName(node);\n default:\n return undefined;\n }\n }", "function getObjectName(node) {\n\t\tif ( node.type === Syntax.MemberExpression ) {\n\t\t\tvar prefix = getObjectName(node.object);\n\t\t\treturn prefix ? prefix + \".\" + node.property.name : null;\n\t\t} else if ( node.type === Syntax.Identifier ) {\n\t\t\treturn scope[node.name] ? scope[node.name] : node.name;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}", "function varType( obj ) {\n\t\treturn ({}).toString.call(obj).match(/\\s([a-zA-Z]+)/)[1].toLowerCase()\n}", "function getForInVariableSymbol(node) {\n var initializer = node.initializer;\n if (initializer.kind === 219 /* VariableDeclarationList */) {\n var variable = initializer.declarations[0];\n if (variable && !ts.isBindingPattern(variable.name)) {\n return getSymbolOfNode(variable);\n }\n }\n else if (initializer.kind === 69 /* Identifier */) {\n return getResolvedSymbol(initializer);\n }\n return undefined;\n }", "function nameOf_(formula) {\n var nameExtractRegex = new RegExp(\"^=?\\\\(\"+commentStart+\"(\"+varName+\")(?:\\\\([^\\\\)]*\\\\))?=\"+commentEnd+any+\"*\\\\)$\");\n nameExtractRegex.lastIndex = 0;\n var m = nameExtractRegex.exec(formula);\n if(m) {\n return m[1];\n }\n nameExtractRegex = new RegExp(\"^=?(\"+varName+\")@\"+any+\"*$\");\n nameExtractRegex.lastIndex = 0;\n var m = nameExtractRegex.exec(formula);\n if(m) {\n return m[1];\n }\n return LAST_NAME;// Default name undefined; // means no value\n}", "function addVar(type) {\n\t\tif (isIntoFunction) {\n\t\t\tlocalVarTable.push(type);\n\t\t\tlocalVarTable.push(thisToken);\n\t\t} else {\n\t\t\tvarTable.push({\n\t\t\t\tname: thisToken,\n\t\t\t\ttype: type,\n\t\t\t\tlength: 1\n\t\t\t});\n\t\t\tasm.push(' _' + thisToken + ' word ? ');\n\t\t\tasm.push(' ');\n\t\t}\n\t}", "function letVsVar() {\n var num1 = 3;\n var num2 = 3;\n // num2 = 'Hola mundo'\n if (true) {\n var num1_1 = 5;\n var num2 = 5;\n console.log('N1: ', num1_1);\n console.log('N2: ', num2);\n }\n console.log('N1: ', num1);\n console.log('N2: ', num2);\n}", "function createVariable() {\n var id = nextVariableId++;\n var name = '$V';\n\n do {\n name += variableTokens[id % variableTokensLength];\n id = ~~(id / variableTokensLength);\n } while (id !== 0);\n\n return name;\n}", "function createVariable() {\n var id = nextVariableId++;\n var name = '$V';\n\n do {\n name += variableTokens[id % variableTokensLength];\n id = ~~(id / variableTokensLength);\n } while (id !== 0);\n\n return name;\n }", "getVar(variable) {\n\t\tconst tag = variable.toLowerCase();\n\t\treturn this._customVar[tag];\n\t}", "function getVar(t) {\n\t\tfor (var i = 0; i < varTable.length; i++) {\n\t\t\tif (varTable[i].name == t)\n\t\t\t\treturn varTable[i];\n\t\t}\n\t\treturn {\n\t\t\tname: 'null',\n\t\t\ttype: 'void',\n\t\t\tlength: 1\n\t\t}\n\t}", "async function processVariableDeclaration(node) {\n // console.log(node);\n \n // Constant variables do not use storage.\n if(node.constant) return;\n\n // Print variable declaration.\n const declaration = getVariableDeclaration(node);\n console.log(declaration);\n // console.log(` offset: ${rightOffset}`);\n \n // Get variable type.\n const type = node.typeDescriptions.typeString;\n // console.log(` type: ${type}`);\n\n // Calculate variable size.\n const size = getVariableSize(type, web3);\n const sizeRemainingInWord = 64 - rightOffset;\n if(sizeRemainingInWord < size) advanceSlot(size);\n console.log(` size: ${size / 2} bytes`);\n \n // Read corresponding storage.\n console.log(` slot: ${slot}`);\n const raw = await web3.eth.getStorageAt(contractAddress, slot);\n const word = web3.utils.padLeft(raw, 64, '0').substring(2, 66);\n console.log(` word: ${word}`);\n\n // Read sub-word.\n const start = 64 - rightOffset - size;\n const end = start + size;\n let subword;\n if(type === 'string') subword = word.substring(start, end - 2);\n else subword = word.substring(start, end);\n console.log(` subword: ${subword}`);\n\n // Read value in word according to type.\n const value = getVariableValue(subword, type, web3);\n console.log(` value: ${value}`);\n\n advanceSlot(size);\n }", "function getTypeName(node) {\n if (node.type == 'Identifier') {\n return node.name;\n } else if (node.type == 'QualifiedTypeIdentifier') {\n return getTypeName(node.qualification) + '.' + getTypeName(node.id);\n }\n\n throw this.errorWithNode('Unsupported type: ' + node.type);\n }", "type(name) {\r\n\t\t\t\tvar i, len, ref, v;\r\n\t\t\t\tref = this.variables;\r\n\t\t\t\tfor (i = 0, len = ref.length; i < len; i++) {\r\n\t\t\t\t\tv = ref[i];\r\n\t\t\t\t\tif (v.name === name) {\r\n\t\t\t\t\t\treturn v.type;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\treturn null;\r\n\t\t\t}", "function AccessVariableGlobally() {\n globalName=\"Block360\"\n var localVariable=\"CIE-NUST\"\n}", "function scanVariable(input, index, variableSet) {\n\tvar variableName = tryReadVariableName(input, index);\n\t/* variableName should not be null here, by contract. */\n\t\n\tvariableSet[variableName] = true;\n\treturn variableName;\n}", "function get_variable_label_from_id(varid, varinfo, hide){\n for(var i = 0; i < varinfo.length; i++)\n if(varinfo[i].id == varid)\n return (varinfo[i].label.substr(hide.length));\n return \"unknown\";\n }", "getVariable(varName){\n\n\t\t// To support derivate, I think this function needs to return the object\n\t\t// rather than the value\n\t\treturn this._variables[varName];\n\t\t// return this._variables[varName].valueOf();\n\n\t}", "getVariable(varName){\n\n\t\t// To support derivate, I think this function needs to return the object\n\t\t// rather than the value\n\t\treturn this._variables[varName];\n\t\t// return this._variables[varName].valueOf();\n\n\t}", "variableAt(index) {\n\t\treturn this._vars[index];\n\t}", "function isVariable(let)\n{\n\tvar j;\n\tfor(j=0; j<vars.length; ++j)\n\t{\n\t if(let==vars[j]) return(j);\n\t}\n\treturn(-1);\n}", "function extractVariable() {\n extract('var');\n}", "function ref(list, name, loose) {\n return contains(list, name) ? \"variable-2\" : (loose ? \"variable\" : \"variable-2 error\");\n }", "function getName(instance_var) {\n instance_var = instance_var.name;\n instance_var = instance_var.split(\" \");\n instance_var = instance_var[instance_var.length - 1];\n return instance_var;\n}", "type(name) {\n var i, len, ref, v;\n ref = this.variables;\n for (i = 0, len = ref.length; i < len; i++) {\n v = ref[i];\n if (v.name === name) {\n return v.type;\n }\n }\n return null;\n }", "function parseVariable(lexer) {\n var start = lexer.token;\n expectToken(lexer, _tokenKind__WEBPACK_IMPORTED_MODULE_4__[\"TokenKind\"].DOLLAR);\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_6__[\"Kind\"].VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function userVarName(){\nvar var_name = 'function';\nvar n = 100;\nthis[var_name] = n;\nalert(this[var_name]);\n}", "function retr(input)\n{\n var index = names.indexOf(input);\n return variables[index];\n}", "function typeVarNames(t) {\n return Z.concat (\n t.type === VARIABLE ? [t.name] : [],\n Z.chain (function(k) { return typeVarNames (t.types[k]); }, t.keys)\n );\n }", "function setVariableName(varName, alias, variableData, generateNewName){\n\t// console.log(\"----------------------------------------\");\n\t // console.log(varName, alias, variableData, generateNewName);\n\t// console.log(\"expressionLevelNames\", expressionLevelNames);\n\t// console.log(\"variableNamesClass\", variableNamesClass);\n\t// console.log(\"variableNamesAll\", variableNamesAll);\n\t// console.log(\"rrrrrrrrr\", typeof variableNamesClass[varName]);\n\t// console.log(\"----------------------------------------\");\n\t// console.log(\" \");\n\t//console.log(\"eeeeeeeeeeeee\", attributesNames, classID, symbolTable[classID][varName])\n\tvar isPropertyFromSubQuery = null;\n\tvar isOwnProperty = false;\n\tif(typeof symbolTable[classID] !== 'undefined' && typeof symbolTable[classID][varName] !== 'undefined'){\n\t\tif( symbolTable[classID][varName].length > 1){\n\t\t\tvar parentTypeIsNull = false;\n\t\t\tvar isNotJoinedClass = false;\n\t\t\tvar definedInJoinClass = null;\n\t\t\tfor(var key in symbolTable[classID][varName]){\n\t\t\t\tif(symbolTable[classID][varName][key][\"context\"] != classID && typeof symbolTable[classID][varName][key][\"type\"] !== 'undefined' && symbolTable[classID][varName][key][\"type\"][\"parentType\"] != null) isNotJoinedClass = true;\n\t\t\t\tif(typeof symbolTable[classID][varName][key][\"type\"] !== 'undefined' && symbolTable[classID][varName][key][\"type\"][\"parentType\"] == null) {\n\t\t\t\t\tparentTypeIsNull = true;\n\t\t\t\t}\n\t\t\t\tif(typeof symbolTable[classID][varName][key][\"type\"] !== 'undefined' \n\t\t\t\t&& symbolTable[classID][varName][key][\"context\"] != classID\n\t\t\t\t&& typeof symbolTable[classID][varName][key][\"upBySubQuery\"] === 'undefined') {\n\t\t\t\t\tdefinedInJoinClass = idTable[symbolTable[classID][varName][key][\"context\"]];\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tif( definedInJoinClass != null && parentTypeIsNull == true && isNotJoinedClass == true){\n\t\t\t\tmessages.push({\n\t\t\t\t\t\"type\" : \"Warning\",\n\t\t\t\t\t\"message\" : \"The name '\"+varName+\"' in '\"+idTable[classID]+\"' class may refer both to '\"+varName+\"' field in '\"+definedInJoinClass+\"' class node and to some instance attribute name. Introduce an alias to '\"+varName+\"' field in '\"+definedInJoinClass+\"' node to disambiguate.\",\n\t\t\t\t\t\"listOfElementId\" : [classID],\n\t\t\t\t\t\"isBlocking\" : true\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\tfor(var key in symbolTable[classID][varName]){\n\t\t\tif(typeof symbolTable[classID][varName][key][\"upBySubQuery\"] !== 'undefined' && symbolTable[classID][varName][key][\"upBySubQuery\"] == 1) {\n\t\t\t\tisPropertyFromSubQuery = symbolTable[classID][varName][key][\"context\"];\n\t\t\t}\n\t\t\tif(symbolTable[classID][varName][key][\"context\"] == classID \n\t\t\t&& typeof symbolTable[classID][varName][key][\"type\"] !== \"undefined\" && symbolTable[classID][varName][key][\"type\"] != null \n\t\t\t&& symbolTable[classID][varName][key][\"type\"][\"parentType\"] != null) {\n\t\t\t\tisOwnProperty = true;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(isPropertyFromSubQuery!= null && isOwnProperty){\n\t\t\tmessages.push({\n\t\t\t\t\t\"type\" : \"Warning\",\n\t\t\t\t\t\"message\" : \"The name '\"+varName+\"' in '\"+idTable[classID]+\"' class is defined both as its schema attribute name, and as a field from a subquery. Introduce an alias to the subquery field to disambiguate.\",\n\t\t\t\t\t\"listOfElementId\" : [classID],\n\t\t\t\t\t\"isBlocking\" : true\n\t\t\t\t});\n\t\t}\n\t}\n\t\n\t//console.log(\"qqqqqqqqqqqqqqqqqqq\", isPropertyFromSubQuery, isOwnProperty, idTable[classID], varName)\n\t\n\tvar varNameRep = varName.replace(/-/g, '_');\n\tif(alias != null) {\n\t\t// console.log(\"1111\", varName, alias);\n\t\tvar aliasSet = false;\n\t\tfor(var key in idTable){\n\t\t\tif (idTable[key] == alias) {\n\t\t\t\tvar classes = [];\n\t\t\t\tif(typeof variableNamesAll[alias] !== 'undefined' && typeof variableNamesAll[alias][\"classes\"] !== 'undefined') classes = variableNamesAll[alias][\"classes\"];\n\t\t\t\tclasses[classID] = alias + \"_\" +count;\n\t\t\t\tvariableNamesAll[alias] = {\"alias\" : alias + \"_\" +counter, \"nameIsTaken\" : true, \"counter\" : counter, \"isVar\" : true, \"classes\": classes};\n\t\t\t\taliasSet = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (aliasSet == false) {\n\t\t\tvar classes = [];\n\t\t\tif(typeof variableNamesAll[alias] !== 'undefined' && typeof variableNamesAll[alias][\"classes\"] !== 'undefined') classes = variableNamesAll[alias][\"classes\"];\n\t\t\tclasses[classID] = alias;\n\t\t\tvariableNamesAll[alias] = {\"alias\" : alias, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : true, \"classes\": classes};\n\t\t}\n\t\t\n\t\treturn variableNamesAll[alias][\"alias\"];\n\t}\n\t//if symbol table has variable with property upBySubQuery = 1\n\telse if(isPropertyFromSubQuery != null && !isOwnProperty && typeof attributesNames[varName] != 'undefined'){\n\t\t// console.log(\"aaaaaaa\", attributesNames[varName][\"classes\"][isPropertyFromSubQuery][\"name\"], isPropertyFromSubQuery);\n\t\treturn attributesNames[varName][\"classes\"][isPropertyFromSubQuery][\"name\"];\n\t}\n\t\n\telse if(variableData[\"kind\"] == \"PROPERTY_NAME\" || typeof variableData[\"kind\"] === 'undefined'){\n\t\t// console.log(\"2222\", varName);\n\t\t//Aply exists to filter if variable is not defined\n\t\tif(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && (variableNamesClass[varName][\"isVar\"] != true ||\n\t\t\tvariableData[\"type\"] != null && false)))applyExistsToFilter = true;\n\t\t// if(typeof variableNamesClass[varName] === 'undefined' || (typeof variableNamesClass[varName] !== 'undefined' && (variableNamesClass[varName][\"isVar\"] != true ||\n\t\t\t// variableData[\"type\"] != null && (typeof variableData[\"type\"][\"maxCardinality\"] === 'undefined' || variableData[\"type\"][\"maxCardinality\"] > 1 || variableData[\"type\"][\"maxCardinality\"] == -1))))applyExistsToFilter = true;\n\t\t//??????????????????????????????????????\n\t\tif(generateNewName != null && generateNewName == true ){\n\t\t\t// console.log(\"2aaaa\", varName);\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined'){\n\t\t\t\tif(typeof variableNamesClass[varName]=== 'undefined'){\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined'){\n\t\t\t\t\t\t//console.log(\"1111\", attributesNames[varName][\"classes\"][classID][\"name\"])\n\t\t\t\t\t\t// console.log(\"1111\")\n\t\t\t\t\t\texpressionLevelNames[varName] = varNameRep;\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false};\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar classes = [];\n\t\t\t\t\t\tif(typeof variableNamesAll[varName] !== 'undefined' && typeof variableNamesAll[varName][\"classes\"] !== 'undefined') classes = variableNamesAll[varName][\"classes\"];\n\t\t\t\t\t\tclasses[classID] = varNameRep;\n\t\t\t\n\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varNameRep, \"nameIsTaken\" : true, \"counter\" : 0, \"isVar\" : false, \"classes\":classes};\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// console.log(\"2222\", attributesNames[varName][\"classes\"][classID][\"name\"])\n\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\texpressionLevelNames[varName] = varNameRep + \"_\" +count;\n\t\t\t\t\t\tvariableNamesAll[varName][\"counter\"] = count;\n\t\t\t\t\t\t\n\t\t\t\t\t\tvar classes = [];\n\t\t\t\t\t\tif(typeof variableNamesAll[varName] !== 'undefined' && typeof variableNamesAll[varName][\"classes\"] !== 'undefined') classes = variableNamesAll[varName][\"classes\"];\n\t\t\t\t\t\tclasses[classID] = varNameRep + \"_\" +count;\n\t\t\t\t\t\tvariableNamesAll[varName][\"classes\"] = classes;\n\t\t\t\t\t\t\n\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep + \"_\" +count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesAll[varName][\"isVar\"]};\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// console.log(\"3333\", attributesNames[varName][\"classes\"][classID][\"name\"])\n\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\texpressionLevelNames[varName] = varNameRep + \"_\" +count;\n\t\t\t\t\tvariableNamesClass[varName][\"counter\"] = count;\n\t\t\t\t\t\n\t\t\t\t\tvar classes = [];\n\t\t\t\t\tif(typeof variableNamesAll[varName] !== 'undefined' && typeof variableNamesAll[varName][\"classes\"] !== 'undefined') classes = variableNamesAll[varName][\"classes\"];\n\t\t\t\t\tclasses[classID] = varNameRep + \"_\" +count;\n\t\t\t\t\t\n\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varNameRep + \"_\" +count, \"nameIsTaken\" : variableNamesClass[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : variableNamesClass[varName][\"isVar\"], \"classes\":classes};\n\t\t\t\t\t// console.log(count, varName + \"_\" +count, variableNamesClass[varName][\"counter\"], variableNamesAll[varName][\"counter\"])\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}else{\n\t\t\t // console.log(\"2cccc\", varName, isSimpleVariableForNameDef);\n\t\t\t//if not used in given expression\n\t\t\tif(typeof expressionLevelNames[varName] === 'undefined' || typeof expressionLevelNames[varName] === 'function'){\n\t\t\t\t// console.log(\"2c 1\", varName);\n\t\t\t\t//if not used in class scope\n\t\t\t\tif(typeof variableNamesClass[varName] === 'undefined'|| typeof variableNamesClass[varName] === 'function'){\n\t\t\t\t\t// console.log(\"2c 11\", varName);\n\t\t\t\t\t//if not used in query scope\n\t\t\t\t\tif(typeof variableNamesAll[varName]=== 'undefined' || typeof variableNamesAll[varName]=== 'function'){\n\t\t\t\t\t\t//not used at all\n\t\t\t\t\t\t// console.log(\"2c 111\", varName, parseType);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\t// console.log(\"4444\", attributesNames[varName], symbolTable[classID][varName])\n\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\t// console.log(\"4a\")\n\t\t\t\t\t\t\t\tif(typeof attributesNames[varName][\"classes\"][classID] !== 'undefined')varNameRep = attributesNames[varName][\"classes\"][classID][\"name\"].replace(/-/g, '_');\n\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar nameIsTaken = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(typeof symbolTable[classID] !== 'undefined'){\n\t\t\t\t\t\t\t\tfor(var key in symbolTable[classID][varName]){\n\t\t\t\t\t\t\t\t\tif(symbolTable[classID][varName][key][\"context\"] == classID){\n\t\t\t\t\t\t\t\t\t\tif(typeof symbolTable[classID][varName][key][\"type\"] !== 'undefined' && symbolTable[classID][varName][key][\"type\"][\"parentType\"] == null){\n\t\t\t\t\t\t\t\t\t\t\tnameIsTaken = false;\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\" || parseType == \"class\") tempIsVar = true;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep, \"nameIsTaken\" : nameIsTaken, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// console.log(\"5555\", attributesNames[varName][\"classes\"][classID][\"name\"])\n\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcount = count+1;\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep+\"_\"+count, \"nameIsTaken\" : false, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\t // console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t\n\t\t\t\t\t//is used in query, but not in a given class (somewhere else)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t // console.log(\"2c 112\", varName);\n\t\t\t\t\t\t//if simple variable\n\t\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\t\tif(parseType == \"attribute\"|| parseType == \"class\") tempIsVar = true;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\t\tif(variableNamesAll[varName][\"nameIsTaken\"] != true){\n\n\t\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\t\tif(typeof attributesNames[varName][\"classes\"][classID] !== 'undefined')varNameRep = attributesNames[varName][\"classes\"][classID][\"name\"];\n\t\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(count<variableNamesAll[varName][\"counter\"])count = variableNamesAll[varName][\"counter\"]\n\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"] + 1;\n\t\t\t\t\t\t\t\tvar varN = varNameRep+\"_\"+count;\n\t\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\t\tif(typeof attributesNames[varName][\"classes\"][classID] !== 'undefined')varN = attributesNames[varName][\"classes\"][classID][\"name\"];\n\t\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(count<variableNamesAll[varName][\"counter\"])count = variableNamesAll[varName][\"counter\"];\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varN, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar classes = [];\n\t\t\t\t\t\t\t\tif(typeof variableNamesAll[varName] !== 'undefined' && typeof variableNamesAll[varName][\"classes\"] !== 'undefined') classes = variableNamesAll[varName][\"classes\"];\n\t\t\t\t\t\t\t\tclasses[classID] = varN;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvariableNamesAll[varName] = {\"alias\" : varN, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar, \"classes\":classes}; //????? vai vajag\t\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t//is expression\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tvar count = variableNamesAll[varName][\"counter\"];\n\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(count<variableNamesAll[varName][\"counter\"])count = variableNamesAll[varName][\"counter\"];\n\t\t\t\t\t\t\tcount = count + 1;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep+\"_\"+count, \"nameIsTaken\" : variableNamesAll[varName][\"nameIsTaken\"], \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t}\n\t\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\t}\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t//is used in a given class\n\t\t\t\t}else{\n\t\t\t\t\t // console.log(\"2c 12\", varName);\n\t\t\t\t\t//if simple variable\n\t\t\t\t\tif(isSimpleVariableForNameDef == true){\n\t\t\t\t\t\t // console.log(\"2c 121\", varName);\n\t\t\t\t\t\tvar tempIsVar = false;\n\t\t\t\t\t\tif(parseType == \"attribute\"|| parseType == \"class\") tempIsVar = true;\n\t\t\t\t\t\t\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvar count = 0;\n\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\tif(typeof attributesNames[varName][\"classes\"][classID] !== 'undefined')varNameRep = attributesNames[varName][\"classes\"][classID][\"name\"];\n\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(count<variableNamesClass[varName][\"counter\"])count = variableNamesClass[varName][\"counter\"]\n\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep, \"nameIsTaken\" : true, \"counter\" : variableNamesClass[varName][\"counter\"], \"isVar\" : tempIsVar};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t//if name is not defined as variable\n\t\t\t\t\t\t\tif(variableNamesClass[varName][\"isVar\"] != true) {\n\t\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"];\n\t\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif(count<variableNamesClass[varName][\"counter\"])count = variableNamesClass[varName][\"counter\"];\n\t\t\t\t\t\t\t\tcount = count + 1;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count, \"isVar\" : tempIsVar};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// console.log(\"variableNamesClass[varName]\", variableNamesClass[varName]);\n\t\t\t\t\t//is expression\n\t\t\t\t\t} else {\n\t\t\t\t\t\t // console.log(\"2c 122\", varName);\n\t\t\t\t\t\t//name is not taken\n\t\t\t\t\t\tif(variableNamesClass[varName][\"nameIsTaken\"] != true){\n\t\t\t\t\t\t\tvar count = variableNamesClass[varName][\"counter\"];\n\t\t\t\t\t\t\tif(typeof attributesNames[varName] !== 'undefined'){\n\t\t\t\t\t\t\t\tcount = attributesNames[varName][\"counter\"];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif(count<variableNamesClass[varName][\"counter\"])count = variableNamesClass[varName][\"counter\"];\n\t\t\t\t\t\t\tcount = count + 1;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvariableNamesClass[varName] = {\"alias\" : varNameRep+\"_\"+count, \"nameIsTaken\" : false, \"counter\" : count, \"isVar\" : false};\n\t\t\t\t\t\t//name is taken\n\t\t\t\t\t\t} //else {\n\t\t\t\t\t\t//\tvar count = variableNamesClass[varName][\"counter\"] + 1;\n\t\t\t\t\t\t//\tvariableNamesClass[varName] = {\"alias\" : varName+\"_\"+count, \"nameIsTaken\" : true, \"counter\" : count};\n\t\t\t\t\t\t//}\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\texpressionLevelNames[varName] = variableNamesClass[varName][\"alias\"];\n\t\t\t\t\treturn variableNamesClass[varName][\"alias\"];\n\t\t\t\t}\n\t\t\t//used in given expression\n\t\t\t} else {\n\t\t\t\t // console.log(\"2c 2\", varName);\n\t\t\t\treturn expressionLevelNames[varName];\n\t\t\t}\n\t\t}\n\t\treturn expressionLevelNames[varName];\n\t} else {\n\t\t // console.log(\"3333\", varName);\n\t\treturn varName;\n\t}\n}", "function variables(name, str) {\n var re = new RegExp(name + '\\\\.([a-zA-Z_][a-zA-Z_0-9]*)', 'g');\n var nameVar = {}, varname, vartype;\n var match = null;\n while (match = re.exec(str)) {\n if (!(match[1] in nameVar)) {\n varname = name + '_' + match[1] + '_' + (variables.count++);\n nameVar[match[1]] = varname;\n }\n }\n return nameVar; \n}", "getNamespacedVariableNameExpression() {\n let firstIdentifier = this.consume(DiagnosticMessages_1.DiagnosticMessages.expectedIdentifierAfterKeyword(this.previous().text), TokenKind_1.TokenKind.Identifier, ...this.allowedLocalIdentifiers);\n let expr;\n if (firstIdentifier) {\n // force it into an identifier so the AST makes some sense\n firstIdentifier.kind = TokenKind_1.TokenKind.Identifier;\n const varExpr = new Expression_1.VariableExpression(firstIdentifier);\n expr = varExpr;\n //consume multiple dot identifiers (i.e. `Name.Space.Can.Have.Many.Parts`)\n while (this.check(TokenKind_1.TokenKind.Dot)) {\n let dot = this.tryConsume(DiagnosticMessages_1.DiagnosticMessages.unexpectedToken(this.peek().text), TokenKind_1.TokenKind.Dot);\n if (!dot) {\n break;\n }\n let identifier = this.tryConsume(DiagnosticMessages_1.DiagnosticMessages.expectedIdentifier(), TokenKind_1.TokenKind.Identifier, ...this.allowedLocalIdentifiers, ...TokenKind_1.AllowedProperties);\n if (!identifier) {\n break;\n }\n // force it into an identifier so the AST makes some sense\n identifier.kind = TokenKind_1.TokenKind.Identifier;\n expr = new Expression_1.DottedGetExpression(expr, identifier, dot);\n }\n }\n return new Expression_1.NamespacedVariableNameExpression(expr);\n }", "function Type() {\n if (currentToken() == \"inteiro\" || currentToken() == \"real\" || currentToken() == \"texto\" || currentToken() == \"boleano\" || currentToken() == \"vazio\" || currentClass() == IDENTIFIER) {\n currentType = currentToken();\n return;\n } else {\n let errorMessage = \"Tipo de variável não reconhecido\";\n handleError(errorMessage);\n return;\n }\n }", "function isVar(node) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !node._let;\n\t}", "function isVar(node) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !node._let;\n\t}", "function parseVariable(lexer) {\n var start = lexer.token;\n expectToken(lexer, _lexer__WEBPACK_IMPORTED_MODULE_4__[\"TokenKind\"].DOLLAR);\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_5__[\"Kind\"].VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expectToken(lexer, _lexer__WEBPACK_IMPORTED_MODULE_4__[\"TokenKind\"].DOLLAR);\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_5__[\"Kind\"].VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function getVar(s, name, def) {\n\treturn JSON.parse(match(s, new RegExp(\"var \"+name+\" *= *([^;]+);\"),1,def));\n}", "function getUniformVarName(uniform, varName) {\n expectArg('uniform', uniform).toBeObject();\n expectArg('varName', varName).toBeString();\n return isDefined(uniform.name) ? expectArg('uniform.name', uniform.name).toBeString().value : varName;\n }", "getNameNode() {\r\n return this._getNodeFromCompilerNode(this.compilerNode.propertyName || this.compilerNode.name);\r\n }", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer__WEBPACK_IMPORTED_MODULE_3__[\"TokenKind\"].DOLLAR);\n return {\n kind: _kinds__WEBPACK_IMPORTED_MODULE_4__[\"Kind\"].VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function getTypeIdentifier(Repr){\n return Repr[$$type] || Repr.name || 'Anonymous';\n }", "function BaseVariable(key) {\n return {\n type: \"variable\",\n key: () => key\n }\n}", "function findVariableName(listobject,props){\n\t\tprops.variableName = listobject.qDef.qFieldDefs[0];\n\t\tif (typeof props.variableName == 'object'){\n\t\t\tif(debug) console.log('set from expr');\n\t\t\tif ((listobject.qDef.qFieldDefs[0].qStringExpression.qExpr)){\n\t\t\t\tprops.variableName = listobject.qDef.qFieldDefs[0].qStringExpression.qExpr;\n\t\t\t} else {\n\t\t\t\tprops.variableName ='';\n\t\t\t}\n\t\t}\n\t\tif (debug) console.log('Var type:'+ typeof props.variableName);\n\t\tif (typeof props.variableName == 'string' && props.variableName){\n\t\t\tprops.variableName = props.variableName.replace(\"=\",'');\n\t\t} else {\n\t\t\tprops.variableName = '';\n\t\t}\n\t\tif(debug){ console.log(listobject); console.log(props); console.log(listobject.qDef.qFieldDefs[0]);}\n\t\tif (props.hideFromSelectionRealField && props.hideFromSelectionRealField != ''){\n\t\t\tprops.variableName = props.hideFromSelectionRealField;\n\t\t}\n\t\t/*if (props.variableName == '' || !props.variableName){\n\t\t\tprops.variableName = listobject.qDef.qFieldDefs[0];\n\t\t\tif(debug){ console.log(typeof props.variableName); }\n\t\t\tif (typeof props.variableName !== 'undefined' && typeof props.variableName !== 'object'){\n\t\t\t\tprops.variableName = props.variableName.replace(\"=\",'');\n\t\t\t} else {\n\t\t\t\tprops.variableName = '';\n\t\t\t}\n\t\t}*/\n\t\tprops.variableName = props.variableName.trim();\n\t\tlistobject.qDef.qFieldDefs[0] = props.variableName; //set back\n\t}", "get termType() {\n return 'Variable';\n }", "get termType() {\n return 'Variable';\n }", "function isVar(node) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !node[_constants.BLOCK_SCOPED_SYMBOL];\n\t}", "function isVar(node) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !node[_constants.BLOCK_SCOPED_SYMBOL];\n\t}", "createVar(match, pathBasename, variables, line) {\n const rep = match.split(':')[0].replace(':', '');\n const namespace = `${pathBasename}/${rep}`;\n const item = {\n title: rep,\n insert: rep,\n detail: `(${rep.replace('$', '')}) - ${pathBasename} Variable.`,\n kind: vscode_1.CompletionItemKind.Variable\n };\n variables[namespace] = { item, type: 'Variable' };\n return { state: variables, current: { line, namespace } };\n }", "variableStorage(data, varType) {\n const type = parseInt(data.storage, 10);\n if (type !== varType) return;\n return [data.varName2, \"Text\"];\n }", "variable(variableName) {\n return this.variableExpression(variableName);\n }", "function isVar(node, parent) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !isLet(node, parent);\n\t}", "function isVar(node, parent) {\n\t return t.isVariableDeclaration(node, { kind: \"var\" }) && !isLet(node, parent);\n\t}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "get name() {}", "function myName() {\n return myName.josh\n}", "function getTypeName(yagoType) {\r\n\tvar typeName = yagoType.split(/:(.+)?/)[1];\r\n\tvar wordnetCode = typeName.substr(typeName.length - 9);\r\n\t\r\n\tif(!isNaN(wordnetCode))\r\n\t\ttypeName = typeName.substr(0, typeName.length - 9);\r\n\t\r\n\treturn typeName;\r\n}", "function getIndex(name)\n{\n // Split the variable name on the underscores and use the last part as the\n // array index\n var parts = name.split(\"_\");\n return parts[parts.length - 1];\n}", "function genTmp(isLbl) {\n var name = tmp_prefix + (tmpCount++);\n if(!isLbl)\n tmps[tmps.length] = new ast.VariableDeclarator(new ast.Identifier(name), null);\n return name;\n }", "function parseVariable(lexer) {\n var start = lexer.token;\n expectToken(lexer, TokenKind.DOLLAR);\n return {\n kind: Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function isVariableStart(input, index) {\n\treturn tryReadVariableName(input, index) !== null;\n}", "parseVariable() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.DOLLAR);\n return this.node(start, {\n kind: Kind.VARIABLE,\n name: this.parseName(),\n });\n }", "function variable(name, size, specifiers0) {\n var specifiers = set(specifiers0);\n var segment = {name: name};\n segment.type = type_in(specifiers);\n specs(segment, segment.type, specifiers);\n segment.size = size_of(segment, segment.type, size, segment.unit);\n return segment;\n}", "function isVar(node) {\n return t.isVariableDeclaration(node, { kind: \"var\" }) && !node._let;\n}", "function getMemberName(node, sourceCode) {\n switch (node.type) {\n case utils_1.AST_NODE_TYPES.TSPropertySignature:\n case utils_1.AST_NODE_TYPES.TSMethodSignature:\n case utils_1.AST_NODE_TYPES.TSAbstractPropertyDefinition:\n case utils_1.AST_NODE_TYPES.PropertyDefinition:\n return getMemberRawName(node, sourceCode);\n case utils_1.AST_NODE_TYPES.TSAbstractMethodDefinition:\n case utils_1.AST_NODE_TYPES.MethodDefinition:\n return node.kind === 'constructor'\n ? 'constructor'\n : getMemberRawName(node, sourceCode);\n case utils_1.AST_NODE_TYPES.TSConstructSignatureDeclaration:\n return 'new';\n case utils_1.AST_NODE_TYPES.TSCallSignatureDeclaration:\n return 'call';\n case utils_1.AST_NODE_TYPES.TSIndexSignature:\n return util.getNameFromIndexSignature(node);\n case utils_1.AST_NODE_TYPES.StaticBlock:\n return 'static block';\n default:\n return null;\n }\n}", "function printName() {\n console.log(\"vardas\", vardas);\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer.TokenKind.DOLLAR);\n return {\n kind: _kinds.Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer.TokenKind.DOLLAR);\n return {\n kind: _kinds.Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer.TokenKind.DOLLAR);\n return {\n kind: _kinds.Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer.TokenKind.DOLLAR);\n return {\n kind: _kinds.Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function parseVariable(lexer) {\n var start = lexer.token;\n expect(lexer, _lexer.TokenKind.DOLLAR);\n return {\n kind: _kinds.Kind.VARIABLE,\n name: parseName(lexer),\n loc: loc(lexer, start)\n };\n}", "function isVar(node, parent) {\n return t.isVariableDeclaration(node, { kind: \"var\" }) && !isLet(node, parent);\n}", "function getPropertyOfType(type, name) {\n type = getApparentType(type);\n if (type.flags & 2588672 /* ObjectType */) {\n var resolved = resolveStructuredTypeMembers(type);\n var symbol = resolved.members[name];\n if (symbol && symbolIsValue(symbol)) {\n return symbol;\n }\n if (resolved === anyFunctionType || resolved.callSignatures.length || resolved.constructSignatures.length) {\n var symbol_1 = getPropertyOfObjectType(globalFunctionType, name);\n if (symbol_1) {\n return symbol_1;\n }\n }\n return getPropertyOfObjectType(globalObjectType, name);\n }\n if (type.flags & 1572864 /* UnionOrIntersection */) {\n return getPropertyOfUnionOrIntersectionType(type, name);\n }\n return undefined;\n }", "function isVar(t) { return t[0] == '$'; }", "function parseVariableIdentifier(kind) {\n\t var token, node = new Node();\n\n\t token = lex();\n\n\t if (token.type === Token.Keyword && token.value === 'yield') {\n\t if (strict) {\n\t tolerateUnexpectedToken(token, Messages.StrictReservedWord);\n\t } if (!state.allowYield) {\n\t throwUnexpectedToken(token);\n\t }\n\t } else if (token.type !== Token.Identifier) {\n\t if (strict && token.type === Token.Keyword && isStrictModeReservedWord(token.value)) {\n\t tolerateUnexpectedToken(token, Messages.StrictReservedWord);\n\t } else {\n\t if (strict || token.value !== 'let' || kind !== 'var') {\n\t throwUnexpectedToken(token);\n\t }\n\t }\n\t } else if (state.sourceType === 'module' && token.type === Token.Identifier && token.value === 'await') {\n\t tolerateUnexpectedToken(token);\n\t }\n\n\t return node.finishIdentifier(token.value);\n\t }" ]
[ "0.65794396", "0.64713496", "0.6439784", "0.6422053", "0.6367675", "0.62648726", "0.6194098", "0.61603886", "0.6144756", "0.6092254", "0.6073717", "0.60338247", "0.5874464", "0.5859156", "0.5829449", "0.58287036", "0.5822598", "0.5789694", "0.5788306", "0.57396126", "0.5727899", "0.56808805", "0.5678923", "0.5662512", "0.56569666", "0.56537217", "0.56499", "0.56374824", "0.56372154", "0.5633786", "0.56302875", "0.56226027", "0.559634", "0.5590267", "0.5585986", "0.55741036", "0.55577636", "0.55577636", "0.55517715", "0.5542908", "0.5540807", "0.5517962", "0.55050623", "0.5474953", "0.5448855", "0.5442613", "0.54361206", "0.5428754", "0.54129994", "0.54052985", "0.5393892", "0.5390975", "0.53818977", "0.53818977", "0.5370498", "0.5370498", "0.5354598", "0.53493685", "0.5330773", "0.5327119", "0.53258806", "0.5325842", "0.5304241", "0.53033227", "0.53033227", "0.5302441", "0.5302441", "0.52942544", "0.5293261", "0.52926546", "0.52909225", "0.52909225", "0.5279678", "0.5279678", "0.5279678", "0.5279678", "0.5279678", "0.5279678", "0.5279678", "0.5279678", "0.5268502", "0.5264797", "0.52643996", "0.5255769", "0.5252831", "0.5252542", "0.5250063", "0.5238602", "0.5229392", "0.52199435", "0.5216004", "0.5210348", "0.5210348", "0.5210348", "0.5210348", "0.5210348", "0.51884514", "0.51729023", "0.5170758", "0.5167221" ]
0.7319142
0
add function inputs to the state manager object. The changing values of inputs needs to be tracked as well as the changing values of variables!
function addInputsToStateManager(node, fxnName) { const params = isAnonymizedFunction(node) ? node.init.params : node.params; for (let param of params) { stateManager[`${fxnName}:${param.name}`] = null; } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addInput(){\r\n //Here we need to change all the weights which use the input values.\r\n this.Wf = Matrix.addInput(this.Wf);\r\n this.Wi = Matrix.addInput(this.Wi);\r\n this.Wo = Matrix.addInput(this.Wo);\r\n this.Wg = Matrix.addInput(this.Wg);\r\n this.netconfig[0]++;\r\n }", "updateInputs (inputs) {\n this.updateMoves() // Actualizamos la posicion/accion del personaje\n this.inputs = inputs // Seteamos los inputs\n this.calculateAcceleration() // Calculamos la nueva aceleracion del personaje\n }", "function update_variables(state, input) {\n switch (state) {\n\n case 'digit':\n if (input == \".\" && decimal_clicked) {\n return;\n }\n if (input == \".\" && !decimal_clicked) {\n decimal_clicked = true;\n }\n\n new_operand += input;\n\n if (digit_click_num <= 1) {\n equation_array.push(new_operand);\n }\n else {\n equation_array[equation_array.length - 1] = new_operand;\n }\n break;\n\n case 'operator':\n new_operator = input;\n if (operator_click_num <= 1) {\n equation_array.push(new_operator);\n }\n else {\n equation_array.pop();\n equation_array.push(new_operator);\n }\n new_operand = '';\n new_operator = '';\n break;\n\n case 'parentheses':\n new_operator = input;\n equation_array.push(new_operator);\n new_operand = '';\n new_operator = '';\n break;\n\n\n }\n}", "function inputFunction(state, action) {\n switch (action.type) {\n case 'add_input': // adds an input\n let count = inputCount+1;\n return {...state,[`input${count}`]: [\n <TextField \n label='word'\n onChange={(event)=>{setInputs({\n type: 'edit_input', \n payload:{\n event: event.target.value, \n num:count\n }\n })}}\n className={classes.inputs}\n variant='filled'\n style={{backgroundColor: '#5F5B5B'}}\n />,\n <Tooltip title=\"Remove Field\" placement=\"top\">\n <Button \n variant='contained' \n onClick={()=>{\n setInputs({type: 'delete_input', payload: `input${count}`})\n }}\n className={classes.buttons}\n style={{backgroundColor: '#741400', color: 'white'}}\n >\n X\n </Button>\n </Tooltip>,\n ''\n ]};\n case 'delete_input': // Removes and input\n delete state[action.payload] ;\n setCurrentCount(currentCount-0.5);\n return state;\n case 'edit_input': // Edits the value of the input\n state[`input${action.payload.num}`][2] = action.payload.event;\n return state;\n default: \n return state;\n }\n }", "function input( v, state ){ \nvar newState = applsfn(v,state);\nreturn new State( applmfn(v,newState), newState ); \n}", "addToInputsLogic(input) {\n const lastIndex = (this.inputs.length - 1);\n\n\n // you can't add operation before digit\n if (\n this.operations.indexOf(this.inputs[lastIndex]) !== -1 &&\n this.operations.indexOf(input) !== -1\n ) {\n return;\n }\n\n if (this.operations.indexOf(input) !== -1) {\n // operation\n if (this.inputs[0] === '') {\n return;\n }\n this.addInput(input);\n } else if (this.operations.indexOf(this.inputs[lastIndex]) !== -1) {\n // first digit after operation\n this.floatNumber.resetInput();\n this.floatNumber.inputAction(input);\n this.addInput(this.floatNumber.getFloat());\n } else {\n // digits\n this.floatNumber.inputAction(input);\n this.inputs.splice(lastIndex, 1, this.floatNumber.getFloat());\n }\n }", "function multipleVarsSeenSetup(){\n if(numberToUse == 1){\n savedInput.firstSave = input;\n }\n else if(numberToUse == 2){\n savedInput.secondSave = input;\n }\n else if(numberToUse == 3){\n savedInput.thirdSave = input;\n }\n else if(numberToUse == 4){\n savedInput.fourthSave = input;\n }\n else if(numberToUse == 5){\n savedInput.fithSave = input;\n switchTheFunction += 1;\n }\n numberToUse +=1;\n update();\n}", "function addItemInputChanged() {\n setState({ addItemInput: event.target.value });\n}", "onInputChange(inputValue) {\r\n this.setState({\r\n operand1: inputValue,\r\n });\r\n }", "changeInput(e, input){\n const val = e.target.value;\n this.setState(prev => { // sets the state for that input to the value\n prev.inputs[input] = val;\n return prev;\n });\n }", "applyDelayedInputs() {\n if (!this.delayedInputs) {\n return;\n }\n let that = this;\n let delayed = this.delayedInputs.shift();\n if (delayed && delayed.length) {\n delayed.forEach(that.doInputLocal.bind(that));\n }\n this.delayedInputs.push([]);\n }", "function _add(...args) {\n\t\t\tsequences = addToSequence(sequences, (s) => cancellableTimeout(s, 1), ...args)\n\t\t\tinputSequence.push({type:'function', data:args})\n\t\t}", "function registerInputs() {\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_A] = myKeyboard.registerHandler(function() {\n\t\t\tmodel.moveSingleDown(Demo.assets['effect-1']);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_A, false\n\t\t);\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_Q] = myKeyboard.registerHandler(function() {\n\t\t\tmodel.moveSingleUp(Demo.assets['effect-1']);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_Q, false\n\t\t);\n\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_S] = myKeyboard.registerHandler(function(elapsedTime) {\n\t\t\tmodel.moveRepeatDown(Demo.assets['effect-2'], elapsedTime);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_S, true\n\t\t);\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_W] = myKeyboard.registerHandler(function(elapsedTime) {\n\t\t\tmodel.moveRepeatUp(Demo.assets['effect-2'], elapsedTime);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_W, true\n\t\t);\n\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_D] = myKeyboard.registerHandler(function() {\n\t\t\tmodel.moveRepeatTimedDown(Demo.assets['effect-3']);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_D, true, 250\n\t\t);\n\t\tinputLeftIds[input.KeyEvent.DOM_VK_E] = myKeyboard.registerHandler(function() {\n\t\t\tmodel.moveRepeatTimedUp(Demo.assets['effect-3']);\n\t\t},\n\t\tinput.KeyEvent.DOM_VK_E, true, 250\n\t\t);\n\t}", "function InputManager(){\n\tthis.actions = {};\n\tthis.bindings = {};\n}", "function gatherInputs() {\n\t // Nothing to do here!\n\t // The event handlers do everything we need for now.\n}", "function Operand2EnteringState() {\n onStateChange(\"Operand2Entering state entered .. \");\n \n this.equalsIsEntered = false;\n\n this.operandEntered = (operand) => {\n \n if(!this.equalsIsEntered)\n displayBuffer.insertChar(operand);\n else {\n \n state = new ReadyState();\n state.operandEntered(operand);\n } \n };\n\n this.operatorEntered = (operator) => {\n if(!this.equalsIsEntered) {\n tokens.push(displayBuffer.getValueAsFloat());\n doCalculate(tokens, currentOperator);\n }\n displayBuffer.insertString(tokens.first());\n state = new OperatorEnteredState(operator);\n //} else \n // alert(tokens.pop()); \n };\n this.first = 0;\n this.equalsEntered = (operator) => {\n if(!this.equalsIsEntered) {\n this.equalsIsEntered = true;\n this.last = tokens.last();\n \n tokens.push(displayBuffer.getValueAsFloat());\n this.first = tokens.first();\n doCalculate(tokens, currentOperator);\n displayBuffer.clear();\n displayBuffer.insertString(tokens.first());\n } else {\n //alert(this.first + \" \" + tokens.first() + \" \" + tokens.last());\n tokens.push(this.first);\n doCalculate(tokens, currentOperator);\n displayBuffer.clear();\n displayBuffer.insertString(tokens.first());\n }\n tokens.list();\n \n //displayBuffer.clear();\n //state = new ReadyState();\n //state = new Operand1EnteringState();\n }\n }", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "function gatherInputs() {\n // Nothing to do here!\n // The event handlers do everything we need for now.\n}", "add() {\n //So we are gonna\n const {num1, num2 } = this.state;\n this.setState({operation: 'add'})\n }", "function register_input(state){\n state[input_id] = input_flag_none;\n}", "internalOnInput(event) {\n const me = this; // Keep the value synced with the inputValue at all times.\n\n me.inputting = true;\n me.value = me.input.value;\n me.inputting = false;\n me.trigger('input', {\n value: me.value,\n event\n });\n me.changeOnKeyStroke && me.changeOnKeyStroke(event); // since Widget has Events mixed in configured with 'callOnFunctions' this will also call onInput\n }", "onInput(calc) {\n let elm = this.getState('dom');\n elm.addEventListener('input', event => {\n // when user types --> update state\n this.setState({ userInput: event.target.value });\n // when state is updated, recall method notifyObservers as render() in Reactjs\n let data = calc(this.getState('userInput')); // calc func always return a string as final result\n this.notifyObservers(data);\n });\n }", "function updateInputs() {\r\n Inputang.setAttribute('value', Inputang.value);\r\n Inputvel.setAttribute('value', Inputvel.value);\r\n }", "function _add() {\n\t\t\tfor (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n\t\t\t\targs[_key] = arguments[_key];\n\t\t\t}\n\n\t\t\tsequences = addToSequence.apply(undefined, [sequences, function (s) {\n\t\t\t\treturn cancellableTimeout(s, 1);\n\t\t\t}].concat(args));\n\t\t\tinputSequence.push({ type: 'function', data: args });\n\t\t}", "static SetInputs( inputs )\n {\n PlaybackInputs.INPUTS = inputs;\n }", "stateUpdate() {\n this.handlestateVariable();\n this.handlestateVariable2();\n this.handleCChange();\n this.handleAChange();\n this.handleidCapture();\n this.handleimgCapture();\n this.handleConfigChange();\n this.idcaptureVal();\n this.imgcaptureVal();\n }", "function addOperator(){\n console.log(inputValue); // puts console message that '+' was clicked\n memory =Number(inputValue.value); // stores Number into memory\n //console.log(memory);\n operator = add; // for 'add' call back function\n inputValue.value = \"\"; // for display\n}", "function addItem(input) {\n\tstate.items.push(input);\n\tconsole.log(input);\n\tconsole.log(state.items);\n}", "function addInput(input) {\n let inputs = getInputs();\n inputs.push(input);\n localStorage.setItem('inputList', JSON.stringify(inputs));\n}", "onInputChange( evt ) {\n\t\tconst inputFields = this.state.inputFields\n\t\tinputFields[evt.target.name] = evt.target.value\n\n\t\tthis.setState({ inputFields })\n\t}", "internalOnInput(event) {\n const me = this;\n\n // Keep the value synced with the inputValue at all times.\n me.inputting = true;\n me.value = me.input.value;\n me.inputting = false;\n\n me.trigger('input', { value: me.value, event });\n\n me.changeOnKeyStroke && me.changeOnKeyStroke(event);\n\n // since Widget has Events mixed in configured with 'callOnFunctions' this will also call onInput\n }", "input(states) {\n throw new Error('You have to implement the \"input\" method!');\n }", "function addInput(){\n\t// Getting the state\n\tvar state = wave.getState();\n\t\n\t// Retrieves topics from storage.\n\tvar jsonString = state.get('topics','[]');\n\t\n\t// Converts JSON to an array of topics\n\tvar topics = toObject(jsonString);\n\t\n\t// Push textbox value into the array and set the textbox to blank\n\ttopics.push(document.getElementById('textBox').value);\n\tdocument.getElementById('textBox').value = '';\n\t\n\t// Create an array for the topic and add it to the \"master\" array.\n\tvar votes = toObject(state.get('votes','[]'));\n\tvotes.push(new Array());\n\t\n\t// Submit everything to storage\n\tstate.submitDelta({'topics' : toJSON(topics), 'votes' : toJSON(votes)});\n}", "constructor(props) {\n super(props);\n this.state = {\n resultDisplay: \"0\",\n expressionDisplay: \"0\",\n currentEntry: \"0\"\n }\n \n this.handleInput = this.handleInput.bind(this);\n this.duplicateOperation = this.duplicateOperation.bind(this);\n this.clear = this.clear.bind(this);\n this.calculate = this.calculate.bind(this);\n }", "function setupFsm() {\n // when jumped to input mode, enter\n fsm.when(\"* -> input\", enterInputMode);\n // when exited, commit or exit depends on the exit reason\n fsm.when(\"input -> *\", function(exit, enter, reason) {\n switch (reason) {\n case \"input-cancel\":\n return exitInputMode();\n\n case \"input-commit\":\n default:\n return commitInputResult();\n }\n });\n // lost focus to commit\n receiver.onblur(function(e) {\n if (fsm.state() == \"input\") {\n fsm.jump(\"normal\", \"input-commit\");\n }\n });\n minder.on(\"beforemousedown\", function() {\n if (fsm.state() == \"input\") {\n fsm.jump(\"normal\", \"input-commit\");\n }\n });\n minder.on(\"dblclick\", function() {\n if (minder.getSelectedNode() && minder._status !== \"readonly\") {\n editText();\n }\n });\n }", "addInput() {\n this.setState({\n inputList: [\n ...this.state.inputList,\n { input_name: \"\", input_type: \"int\" }\n ],\n unit_tests: []\n });\n }", "function addInput(){\n\t// Getting the state\n\tvar state = wave.getState();\n\t\n\t// Retrieves topics from storage.\n\tvar jsonString = state.get('notes','[]');\n\t\n\t// Converts JSON to an array of topics\n\tvar notes = toObject(jsonString);\n\t\n\t// Push textbox value into the array and set the textbox to blank\n\tnotes.push(document.getElementById('textBox').value);\n\tdocument.getElementById('textBox').value = '';\n\t\n\t// Create an array for the topic and add it to the \"master\" array.\n\tvar imp = toObject(state.get('imp','[]'));\n\timp.push(new Array());\n\t\n\t// Submit everything to storage\n\tstate.submitDelta({'notes' : toJSON(notes), 'imp' : toJSON(imp)});\n}", "function updateStates () {\n var oldskip = myDiagram.skipsUndoManager\n myDiagram.skipsUndoManager = true\n // do all \"input\" nodes first\n myDiagram.nodes.each(function (node) {\n if (node.category === 'input') {\n doInput(node)\n }\n })\n // now we can do all other kinds of nodes\n myDiagram.nodes.each(function (node) {\n switch (node.category) {\n case 'and': doAnd(node); break\n case 'or': doOr(node); break\n case 'xor': doXor(node); break\n case 'not': doNot(node); break\n case 'nand': doNand(node); break\n case 'nor': doNor(node); break\n case 'xnor': doXnor(node); break\n case 'output': doOutput(node); break\n case 'input': break // doInput already called, above\n }\n })\n myDiagram.skipsUndoManager = oldskip\n }", "inp(register) {\n\t\tthis.steps.push({ ...this.registers });\n\t\tthis.registers[register] = this.input.shift();\n\t}", "clientInputSave(inputEvent) {\n\n // if no inputs have been stored for this step, create an array\n if (!this.recentInputs[inputEvent.input.step]) {\n this.recentInputs[inputEvent.input.step] = [];\n }\n this.recentInputs[inputEvent.input.step].push(inputEvent.input);\n }", "_onInputButtonPressed(input) {\n switch (typeof input) {\n case 'number':\n if (input==1) {\n this.state.freq[0][0]+=3\n }\n if (input==2) {\n this.state.freq[0][1]+=3\n }\n if (input==3) {\n this.state.freq[0][2]+=3\n }\n if (input==4) {\n this.state.freq[1][0]+=3\n }\n if (input==5) {\n this.state.freq[1][1]+=3\n }\n if (input==6) {\n this.state.freq[1][2]+=3\n }\n if (input==7) {\n this.state.freq[2][0]+=3\n }\n if (input==8) {\n this.state.freq[2][1]+=3\n }\n if (input==9) {\n this.state.freq[2][2]+=3\n }\n if (input==0) {\n this.state.freq[3][0]+=3\n }\n return this._handleNumberInput(input)\n case 'string':\n return this._handleStringInput(input)\n }\n }", "handleInput(e){\n // console.log(e.target.value, e.target.name); el valor, el name del input que se modifica\n const { value, name } = e.target;\n // Este evento nos permite alterar los valores de state\n this.setState({ // Cambiamos el dato del inicio\n [name]: value\n });\n console.log(this.state)\n }", "handleInput(input) {\n\t\t\n\t}", "function storeInput () {\n document.querySelectorAll('.operator').forEach(operand => {operand.onclick = function () {\n calculation[\"numbers\"].push(display);\n calculation[\"operators\"].push(operand.innerText);\n currentTotal(calculation[\"numbers\"], calculation[\"operators\"])\n reenterDisplay();\n }\n }\n )\n //getDisplayValue();\n }", "function f (input) {\n var state = 'f'\n\n function q (input) {\n /**\n * If an input is supplied, return the \n * current state plus input\n */\n if (input) {\n // Add input to current state\n state += input\n return state\n } else {\n /**\n * If no input, increment state and return q\n */\n state += 'o'\n return q\n }\n }\n\n return q(input)\n}", "function addChangeStateEventListeners(){\n addKeyCallback(Phaser.Keyboard.ZERO, changeState, 0)\n addKeyCallback(Phaser.Keyboard.ONE, changeState, 1)\n addKeyCallback(Phaser.Keyboard.TWO, changeState, 2)\n addKeyCallback(Phaser.Keyboard.THREE, changeState, 3)\n addKeyCallback(Phaser.Keyboard.FOUR, changeState, 4)\n addKeyCallback(Phaser.Keyboard.FIVE, changeState, 5)\n addKeyCallback(Phaser.Keyboard.SIX, changeState, 6)\n addKeyCallback(Phaser.Keyboard.SEVEN, changeState, 7)\n addKeyCallback(Phaser.Keyboard.EIGHT, changeState, 8)\n addKeyCallback(Phaser.Keyboard.NINE, changeState, 9)\n}", "function inputChange() {\r\n dofTable.forEach(dof => {\r\n var value = [dof.joystick.position.x, dof.joystick.position.y][dof.axis];\r\n if (dof.id < 2) { // controllerState.move\r\n controllerState.move[dof.id] = value;\r\n } else { // controllerState.servos\r\n controllerState.servos[dof.id - 2] = value;\r\n }\r\n });\r\n\r\n controllerStateSpan.innerHTML = JSON.stringify(controllerState);\r\n}", "function Input() {}", "getInputs(input){ \n return this.inputs[input];\n }", "call(inputs, kwargs) {\n return inputs;\n }", "function InputState() {\n this.prefixRepeat = [];\n this.motionRepeat = [];\n\n this.operator = null;\n this.operatorArgs = null;\n this.motion = null;\n this.motionArgs = null;\n this.keyBuffer = []; // For matching multi-key commands.\n this.registerName = null; // Defaults to the unnamed register.\n }", "function InputState() {\n this.prefixRepeat = [];\n this.motionRepeat = [];\n\n this.operator = null;\n this.operatorArgs = null;\n this.motion = null;\n this.motionArgs = null;\n this.keyBuffer = []; // For matching multi-key commands.\n this.registerName = null; // Defaults to the unnamed register.\n }", "addInputs() {\n for (let i = 0; i < inputList.length; i++) {\n for (let j = 0; j < this[inputList[i]].length; j++) {\n simulationArea.simulationQueue.add(this[inputList[i]][j], 0);\n }\n }\n\n for (let i = 0; i < this.SubCircuit.length; i++) { this.SubCircuit[i].addInputs(); }\n }", "processInput() {\n var newAnswer = 0;\n\n if (this.state.input.numbers.length == 0) {\n newAnswer = 'NAN';\n } else if (this.state.input.numbers.length == 1) {\n newAnswer = x.numbers[0];\n } else {\n // Remove dangling operators.\n if (this.state.input.numbers.length == this.state.input.operations.length) {\n this.state.input.operations.pop();\n }\n\n // Perform one round of calculations manually to set newAnswer.\n newAnswer = this.calculate(this.state.input.numbers[0], this.state.input.numbers[1], this.state.input.operations[0])\n\n // Loop through remaining numbers until there are none left.\n let count = 2;\n\n while (this.state.input.numbers[count] != null) {\n newAnswer = this.calculate(newAnswer, this.state.input.numbers[count], this.state.input.operations[count - 1]);\n count++;\n }\n }\n\n // display: prevState.display + \" = \" + newAnswer,\n this.setState((prevState) => {\n return {\n display: newAnswer,\n answer: newAnswer,\n doClear: true\n }\n });\n }", "handleInput(event) {\n\t\tconst name = event.target.name\n\t\tconst value = event.target.value\n\t\tthis.setState({ [name]: value })\n\t}", "function fieldManager(){\n\t\tvar _sent_by_me = false\n\n\t\treturn {\n\t\t\t\"input\": function inputManager(do_it){\n\t\t\t\t_sent_by_me = true\n\t\t\t\tdo_it()\n\t\t\t},\n\t\t\t\"output\": function outputManager(do_it){\n\t\t\t\t_sent_by_me ? _sent_by_me = false : do_it()\n\t\t\t}\n\t\t}\n\t}", "handleInputChange(event) {\n let newState = {};\n newState[event.target.id] = event.target.value;\n this.setState(newState);\n }", "function Add_Input(){\r\n\tAppend_Row('#input_list');\r\n\tAppend_Row('#input_state');\r\n\tAppend_Row('#input_rules');\r\n\tApp_Reset();\r\n}", "constructor(props) {\n super(props)\n this.state = {\n balance: 0,\n rate: 0.01,\n term: 15,\n output: 0,\n period: 12,\n };\n //update input\n this.handleBalance = this.handleBalance.bind(this);\n this.handleRate = this.handleRate.bind(this);\n this.handleTerm = this.handleTerm.bind(this);\n this.handlePeriod = this.handlePeriod.bind(this);\n\n this.handleSubmit = this.handleSubmit.bind(this);\n\n this.mortgageCalc = this.mortgageCalc.bind(this);\n console.log(this.state);\n }", "function inputHandling(e) {\n setInputFields((input) => ({ ...input, [e.target.name]: e.target.value }));\n console.log(inputFields);\n }", "set_state(intp, x, f, c, s){\n this.interpreter = intp;\n this.x = x;\n this.f = f;\n this.c = c;\n this.s = s;\n }", "handleInputChange() {\n this.setState({\n inputs: this._getInputs(),\n results: null,\n });\n }", "handleInputChange(event) {\n const target = event.target;\n const name = target.name;\n const value = target.value;\n this.setState(state => (\n { values: { ...state.values, [name]: value } }\n ), () => {\n if (this.props.onChange) {\n this.props.onChange(this.state.values)\n }\n }\n );\n }", "function onInputChange(e) {\n console.log(\"change\");\n const { name, value } = e.target;\n parameters = { ...parameters, [name]: value };\n}", "function Input()\n{\n\tmap.input();\n\tplayer1.input(input1);\n\tplayer2.input(input2);\n}", "onInputChange(evt){\t\n\t\tthis.setState({\n\t\t\tfields: {\n\t\t\t\t...this.state.fields,\n\t\t\t\t[evt.target.name]: evt.target.value\n\t\t\t}\n\t\t})\n\t}", "handleInput() {}", "function InputManager() {\n\t// the state of each key (up to 255)\n\tthis.mKeyStates = new Array();\n\tfor (var i = 0; i < 255; ++i) {\n\t\tthis.mKeyStates[i] = 0;\n\t}\n\t\n\t// the state of each mouse button (left, right and middle)\n\tthis.mButtonStates = new Array();\n\tfor (var i = 0; i < 3; ++i) {\n\t\tthis.mButtonStates[i] = 0;\n\t}\n\t\n\tthis.mMouseInCanvas = false; // is the mouse inside the canvas\n\tthis.mLocalMouseCoords = new Vec2(0, 0); // coordinates of the mouse in the canvas\n\tthis.mGlobalMouseCoords = new Vec2(0, 0); // coordinates of the mouse in the page\n\tthis.mWheelDelta = 0;\n\t\n\tthis.mTextInput = \"\"; // current text string that has been input since last frame\n\t\n\tthis.mDisableBackspace = true; // should backspace functionality be disabled (usually 'back')\n\tthis.mDisableMouseWheel = false; // should mouse wheel functionality be disabled (usually 'page scrolling')\n}", "_updateInput(inputVector, modification) {\n vec3.add(inputVector, inputVector, modification);\n vec3.min(inputVector, inputVector, vec3.fromValues(1, 1, 1));\n vec3.max(inputVector, inputVector, vec3.fromValues(-1, -1, -1));\n }", "handleCalculate(input) {\n this.props.calculateInput(input, this.getCoinObj());\n }", "function process (signal, state, input) {\n var newState = Object.assign({}, state)\n var n = state.n + 1\n newState.n = n\n newState.input[n] = input\n newState.ts[n] = Date.now()\n if (typeof signal.config.filter === 'function') {\n // If filter fails, then there are no changes made\n if (!signal.config.filter(n, newState)) return state\n }\n if (typeof signal.config.output === 'function') {\n newState.output[n] = signal.config.output(n, newState)\n } else {\n // Default to the identity func\n newState.output[n] = input\n }\n // delete old values to save memory\n var toDelete = String(n - (signal.config.memory + 1))\n if (newState.input.hasOwnProperty(toDelete)) delete newState.input[toDelete]\n if (newState.ts.hasOwnProperty(toDelete)) delete newState.ts[toDelete]\n if (newState.output.hasOwnProperty(toDelete)) delete newState.output[toDelete]\n return newState\n}", "onInputChange(evt) {\n\t\tthis.setState({\n\t\t\tfields: {\n\t\t\t\t...this.state.fields,\n\t\t\t\t[evt.target.name]: evt.target.value\n\t\t\t}\n\t\t})\n\t}", "integrateInput() {\n var positionInput = this.positionInputModule();\n this.fAudioInput = new ModuleClass(Utilitary.idX++, positionInput.x, positionInput.y, \"input\", this.sceneView.inputOutputModuleContainer, (module) => { this.removeModule(module); }, this.compileFaust);\n this.fAudioInput.patchID = \"input\";\n var scene = this;\n this.compileFaust({ isMidi: false, name: \"input\", sourceCode: \"process=_,_;\", x: positionInput.x, y: positionInput.y, callback: (factory) => { scene.integrateAudioInput(factory); } });\n }", "onInputChange(e){\n this.setState({[e.target.name]: e.target.value});//get user input\n }", "get numberOfInputs() {return 0}", "handleInputChanges(evt) {\n this.setState({[evt.target.name]:evt.target.value});\n }", "function inputStoreData() {\n console.log(\"inside original input storage\");\n inputs = $('input[type=\"text\"],input[type=\"password\"]').each(function() {\n $(this).data('original', this.value);\n });\n console.log(\"Inputs inside store function:\" + inputs);\n}", "function inputUpdater () {\n possibleInputs = {\n previous: [imgArray[previousFirst], imgArray[previousSecond], imgArray[previousThird]],\n current: [imgArray[firstImageNumber], imgArray[secondImageNumber], imgArray[thirdImageNumber]],\n blank: [{name: 'click', path: './assets/blank.jpg'}, {name: 'an', path: './assets/blank.jpg'}, {name: 'image', path: './assets/blank.jpg'}]\n };\n}", "handleInput(e) {\n e.preventDefault()\n let name = e.target.name\n let newState = {}\n newState[name] = e.target.value\n this.setState(newState)\n }", "handleInputChange(event) {\n\n let sWho = \"ObjectivesFilterForm::handleInputChange\"\n\n\t const target = event.target;\n //logajohn.info(`${sWho}(): target = `, customStringify(target) )\n\n\t const value = target.type === 'checkbox' ? target.checked : target.value;\n logajohn.info(`${sWho}(): value = `, customStringify(value) )\n\n\t const name = target.name;\n logajohn.info(`${sWho}(): name = `, customStringify(name) )\n\t\n let stateSetter = {\n\t [name]: value\n\t };\n\n logajohn.info(`${sWho}(): stateSetter = `, customStringify(stateSetter) )\n\n\t this.setState( stateSetter )\n }", "add () {\n }", "function userInputChanges(e) {\n setUserInput(e.target.value);\n }", "function handleInputs(event) {\n props.handleChangeInputs(event.target.value, event.target.name);\n }", "function initInputHandlers() {\n\tidealNumNodes = window.innerWidth / 20;\n\tmaxExtraEdges = Math.round(parseFloat(100) / 100 * idealNumNodes);\n\n\tradiiWeightPower = parseFloat(0.0);\n\n\tdriftSpeed = 0.03;\n\trepulsionForce = 500;\n}", "handleInput(e) {\n if (this.props.onUpdate) { this.props.onUpdate(e.currentTarget.value) }\n }", "handleSimpleInputChange(event) {\n const target = event.target;\n const value = target.value;\n const name = target.name;\n\n /* this.setState({\n minitask:{...minitask,[name]:value}\n });*/\n this.setState((state, props) => ({\n [name]: value\n }));\n }", "static get observers() {\n return [\n 'handle_input_data_changed(inputData)'\n ]\n }", "function addStateListeners(){\n\tif(DEBUG !== 1) return false;\n\n\tfor(var s in scenes.states){\n\t\taddKeyCallback(s, changeState, s);\n\t}\n}", "handleInput(villainInput) {\n this.setState({\n ...this.state.villains.push({name: villainInput.name.value, superpower: villainInput.superpower.value})\n });\n console.log(\"villain name input\", villainInput.name.value)\n console.log(\"villains: \", this.state.villains)\n }", "onInputChange(name, event) {\n\t\tvar change = {};\n\t\tchange[name] = event.target.value;\n\t\tthis.setState(change);\n\t}", "handleInput(e) {\n let value = e.target.value;\n let name = e.target.name;\n this.setState(\n prevState => ({\n newFacilitator: {\n ...prevState.newFacilitator,\n [name]: value\n }\n }),\n () => console.log(this.state.newFacilitator)\n );\n }", "handleInputChange(inName) {\n // console.dir(evt.target);\n // const elementName = evt.target;\n // this.setState({elementName: evt.target});\n // console.log('state on change = ' + this.state);\n return evt => {\n // console.log('wat', inName)\n // console.log(evt);\n this.setState({\n [inName]: evt.target.value\n });\n }\n }" ]
[ "0.63359284", "0.6324789", "0.61727697", "0.61650825", "0.61217165", "0.60111904", "0.58992976", "0.5634187", "0.56264096", "0.5595174", "0.55694485", "0.5562798", "0.55593246", "0.5555937", "0.5554165", "0.5543934", "0.5524958", "0.5524958", "0.5524958", "0.5524958", "0.5524958", "0.5524958", "0.5524958", "0.55219305", "0.55219305", "0.55219305", "0.55045044", "0.5483643", "0.5478319", "0.54663175", "0.5464573", "0.54632443", "0.5451821", "0.5446049", "0.54414487", "0.543226", "0.5428171", "0.54101974", "0.5403012", "0.53982204", "0.53807527", "0.5360796", "0.5350838", "0.53474504", "0.5346271", "0.53440917", "0.5335695", "0.5317621", "0.53124106", "0.5264299", "0.52469736", "0.52354556", "0.5219142", "0.5218673", "0.5203074", "0.5197885", "0.5193411", "0.51805437", "0.51757735", "0.51757735", "0.51542777", "0.5149417", "0.5144848", "0.51390946", "0.51372445", "0.513552", "0.51283336", "0.5126013", "0.5115912", "0.5114967", "0.5112354", "0.5111363", "0.51106316", "0.51104593", "0.50941396", "0.5092749", "0.5084132", "0.50822103", "0.5063676", "0.505114", "0.50361246", "0.5019591", "0.5017268", "0.50093716", "0.500018", "0.49927068", "0.498146", "0.49756476", "0.4973532", "0.49719605", "0.49697313", "0.4966686", "0.49656615", "0.49597192", "0.49593338", "0.49483606", "0.49438572", "0.4942261", "0.49413162", "0.49391145" ]
0.686743
0
below are functions that could be used as API return two neighbors's local information (object), different types of routes (arrays)
function getPair(NeighborName1, NeighborName2) { if (NeighborName2 < NeighborName1) { var temp = NeighborName1; NeighborName1 = NeighborName2; NeighborName2 = temp; } var N1 = getNeighborInfo(NeighborName1); var N2 = getNeighborInfo(NeighborName2); var pairRoutes = getPairRoutes(NeighborName1, NeighborName2); var result = {}; result[NeighborName1] = N1; result[NeighborName2] = N2; result["Routes"] = pairRoutes; return result; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getRouteInformaton(){\n if(markers.length==2){\n var route = {\n 'start_location':{\n 'latitude': markers[0].position.lat(),\n 'longitude': markers[0].position.lng()\n },\n 'end_location':{\n 'latitude': markers[1].position.lat(),\n 'longitude': markers[1].position.lng()\n }\n }\n return route;\n }\n}", "function findRoute(graph, from, to) {//the graph is from buildGraph function, so are from and to\n let work = [{at: from, route: []}];\n //a new variable is initialised called work to get key and value pairs\n for (let i = 0; i < work.length; i++) { //use for loop to get through all elements in work\n let {at, route} = work[i]; //use destructuring method to assign what work[i] is\n for (let place of graph[at]) { //define a new local variable called place to loop through graph[at], which is the location of the robot\n if (place == to) return route.concat(place); //if the location of robot and the destination ( pickup or drop-off) point are the same, return place using concat method. This is to tell the robot to remember the route by having the string pushed into the empty array\n if (!work.some(w => w.at == place)) {//use some function to \n //The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.\n work.push({at: place, route: route.concat(place)});//keep updating the start point before the pickup point and the drop-off point are the same, then push all the routes out to the array for the robot to remember.\n }\n }\n }\n }", "function getRoute(latlo, egal){\r\n //check if first stopover on route\r\n if(waypoints.length <= 1){\r\n if(egal){\r\n hereGetRouteSummary(homebase, latlo, homebase);\r\n /*waypoints.push([latlo,0,-1]); //push destination in\r\n waypoints.push([homebase,0,-1]); //push homebase for return */\r\n }\r\n } else { //not the first stopover\r\n for(let i=0;i<=waypoints.length-2;i++){ //for every stopover in waypoints (-2: ignor homebase at the end) \r\n hereGetRouteSummary(waypoints[i][0], latlo, waypoints[i+1][0]) //call function to call HERE API hereGetRouteSummary(origin, via, destination)\r\n }\r\n let min = 0; //index of shortest way\r\n setTimeout(function(){ //timeout to await callback from HERE API\r\n for(let i=0;i<(sectionViaTimes[1].length);i++){ //intariat through every entry in sectionViaTimes to find shortes route\r\n if(sectionViaTimes[1][i][0] + sectionViaTimes[1][i][1] < sectionViaTimes[1][min][0] + sectionViaTimes[1][min][1]){ //if time is shorter then current shortest time = overwrite shortest index\r\n min = i;\r\n }\r\n }\r\n // Put coordinates in waypoints array (acording to shortes travel time as calculated above)\r\n //for(let i=1;)*/\r\n let y;\r\n //indexOf() sorta, workaround to find position in waypoint araray of shortest offset\r\n for(y=0;y<waypoints.length;y++){\r\n if(sectionViaTimes[0][min] == waypoints[0][y]) break; \r\n }\r\n //calculate the eta from departure point to arrival point + stoovertime\r\n let eta = waypoints[y][1] + sectionViaTimes[1][min][0] + stopovertime;\r\n //put coordinates and eta in waypoints array at the correct position\r\n waypoints.splice(y+1,0,[latlo,waypoints[y][1] + eta, egal ? -1 : 0]); \r\n //calculate the eta offset for all the following waypoints\r\n let etaoffset = eta + sectionViaTimes[1][min][1];\r\n //put them eta offsets in\r\n for(let i=y+2;i<waypoints.length;i++){\r\n waypoints[i][1] += etaoffset; \r\n }\r\n console.log(waypoints);\r\n }, 300); \r\n }\r\n}", "route (curPt, pois, options = {}) {\n const includedNearbys = [];\n\n\n // NEW - once we've created the graph, snap the current and nearby panos to the nearest junction within 5m, if there is one\n const snappedNodes = [ curPt, null ];\n if(options.snapToJunction) {\n snappedNodes[0] = this.jMgr.snapToJunction(curPt, 0.005);\n }\n pois.forEach(p => {\n p.lon = parseFloat(p.lon);\n p.lat = parseFloat(p.lat);\n //nearby.poseheadingdegrees = parseFloat(nearby.poseheadingdegrees);\n p.bearing = 720;\n snappedNodes[1] = options.snapToJunction ? this.jMgr.snapToJunction([p.lon, p.lat], this.distThreshold) : [p.lon, p.lat];\n \n const route = this.calcPath(snappedNodes);\n\n if(route!=null && route.path.length>=2) {\n // Initial bearing of the route (for OTV arrows, Hikar signposts, etc)\n let bearing = turfBearing(turfPoint(route.path[0]), turfPoint(route.path[1]));\n\n if(bearing < 0) bearing += 360;\n p.bearing = bearing;\n p.weight = route.weight;\n\n // save the path so we can do something with it \n p.path = route.path;\n }\n });\n // Sort routes to each POI based on bearing\n const sorted = pois.filter( p => p.bearing<=360).sort((p1,p2)=>(p1.bearing-p2.bearing)); \n let lastBearing = 720;\n let curPOIsForThisBearing = [];\n const poisGroupedByBearing = [];\n \n for(let i=0; i<sorted.length; i++) {\n if(Math.abs(sorted[i].bearing-lastBearing) >= 5) {\n // new bearing\n curPOIsForThisBearing = { bearing: sorted[i].bearing, pois: [] };\n poisGroupedByBearing.push(curPOIsForThisBearing);\n }\n curPOIsForThisBearing.pois.push(sorted[i]);\n lastBearing = sorted[i].bearing;\n }\n\n // Return value: an array of pois grouped by bearing and\n // sorted by distance within each bearing group.\n // This could be used to generate a virtual signpost (Hikar) or\n // select the immediately linked panorama (OTV)\n const poisGroupedByBearingSortedByDistance = poisGroupedByBearing.map ( forThisBearing =>{ return { bearing: Math.round(forThisBearing.bearing), pois: forThisBearing.pois.sort((n1, n2) => n1.weight - n2.weight)} });\n return poisGroupedByBearingSortedByDistance; \n }", "function showRoute(ecoFound){\r\n\r\n let routingParameters = {\r\n // el modo de ir por la ruta:\r\n 'mode': 'fastest;pedestrian',//'fastest;car',\r\n // punto de inicio de la ruta:\r\n 'waypoint0': 'geo!' + markerUser.getPosition().lat + ',' + markerUser.getPosition().lng,\r\n // punto final de la ruta:\r\n 'waypoint1': 'geo!' + ecoFound.position.lat + ',' + ecoFound.position.lng,\r\n 'representation': 'display'\r\n };\r\n\r\n var onResult = function (result) {\r\n var route,\r\n routeShape,\r\n startPoint,\r\n endPoint,\r\n linestring;\r\n if (result.response.route) {\r\n // Pick the first route from the response:\r\n route = result.response.route[0];\r\n // Pick the route's shape:\r\n routeShape = route.shape;\r\n\r\n // Create a linestring to use as a point source for the route line\r\n linestring = new H.geo.LineString();\r\n\r\n // Push all the points in the shape into the linestring:\r\n routeShape.forEach(function (point) {\r\n var parts = point.split(',');\r\n linestring.pushLatLngAlt(parts[0], parts[1]);\r\n });\r\n\r\n var routeLine = new H.map.Polyline(linestring, {\r\n style: { strokeColor: 'green', lineWidth: 5 }\r\n });\r\n // Add the route polyline and the two markers to the map:\r\n map.addObjects([routeLine]);\r\n // Set the map's viewport to make the whole route visible:\r\n map.setViewBounds(routeLine.getBounds());\r\n watchId = navigator.geolocation.watchPosition(updaeteLocation, errorLocation, optionsGPS);\r\n }\r\n };\r\n\r\n var router = platform.getRoutingService();\r\n\r\n // Call calculateRoute() with the routing parameters,\r\n // the callback and an error callback function (called if a\r\n // communication error occurs):\r\n router.calculateRoute(routingParameters, onResult,\r\n function (error) {\r\n console.log(error.message);\r\n });\r\n\r\n\r\n}", "function routesNearCoordinate(request, response) {\n\n var lat = request.params.lat;\n var lon = request.params.lon;\n var precision = request.params.precision;\n\n var geoHash = geohash.encodeGeoHash(lat, lon);\n var geoHashTruncate = geoHash.substring(0, precision);\n\n console.log(\"routesNearCoordinate:Looking for geohash:\" + geoHash + ' short:' + geoHashTruncate);\n\n var top = geohash.calculateAdjacent(geoHash, 'top');\n var bottom = geohash.calculateAdjacent(geoHash, 'bottom');\n \tvar right = geohash.calculateAdjacent(geoHash, 'right');\n \tvar left = geohash.calculateAdjacent(geoHash, 'left');\n var topleft = geohash.calculateAdjacent(left, 'top');\n \tvar topright = geohash.calculateAdjacent(right, 'top');\n \tvar bottomright = geohash.calculateAdjacent(right, 'bottom');\n \tvar bottomleft = geohash.calculateAdjacent(left, 'bottom');\n\n console.log('routesNearCoordinate:top=' + top + ',' + bottom + ',' + left+ ',' + right+ ',' + topleft + ',' + topright + ',' + bottomleft+ ',' + bottomright+ ',')\n\n top = top.substring(0, precision);\n bottom = bottom.substring(0, precision);\n right = right.substring(0, precision);\n left = left.substring(0, precision);\n topleft = topleft.substring(0, precision);\n topright = topright.substring(0, precision);\n bottomleft = bottomleft.substring(0, precision);\n bottomright = bottomright.substring(0, precision);\n\n // Find all routes whose geohashes begin with one of the 9 prefixes (are close by)\n var geoHashList = [\n {\"route.geohash\": new RegExp('^' + geoHashTruncate + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + top + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + bottom + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + right + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + left + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + topleft + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + topright + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + bottomright + '(.*)$')},\n {\"route.geohash\": new RegExp('^' + bottomleft + '(.*)$')}];\n\n console.log(\"routesNearCoordinate:Hash:\" + geoHashTruncate + ',' + top + ',' + bottom + ',' + right + ',' + left + ',' + topleft + ',' + topright + ',' + bottomleft + ',' + bottomright);\n\n db.find({$or: geoHashList}, function (err, docs) {\n\n console.log('routesNearCoordinate:' + JSON.stringify(docs));\n\n docs.sort(function(routeA, routeB) {\n\n if(routeA.route.title < routeB.route.title )\n return -1;\n else if (routeA.route.title > routeB.route.title)\n return 1;\n else\n return 0;\n });\n\n response.send(JSON.stringify(docs))\n\n });\n\n}", "function buildRouteObject(busNr,stops,times,routesObject){\n var coordinatesContainer=[];\n for (var i=0; i<busNr.length;i++){\n \n if(i==0){ \n var filteredStop= filterDistricts(stops[i]);\n var townNames = getTownNames(filteredStop); //Mögliche TownNamen für Overpass-Query\n var stopNames = getStopNames(filteredStop,townNames); //Mögliche StopNamen für Overpass-Query\n coordinatesContainer[1] = getLongLat(stopNames,townNames);\n }\n\n coordinatesContainer[0] = coordinatesContainer[1]; //verschiebe nach alte Daten\n var filteredStop= filterDistricts(stops[i+1]);\n var townNames = getTownNames(filteredStop); //Mögliche TownNamen für Overpass-Query\n var stopNames = getStopNames(filteredStop,townNames); \n\n coordinatesContainer[1] = getLongLat(stopNames,townNames); // <---- müssen wahrscheinlich auch noch gefiltert werden sonst z.B Winninger Str. = 3 Koordinaten\n\n if(i==0){\n routesObject.route.push(buildJsonSection(busNr[0],stops[0],stops[1],times[0],times[1],coordinatesContainer[0],coordinatesContainer[1]));\n } else{\n routesObject.route.push(buildJsonSection(busNr[i],stops[i],stops[i+1],times[2*i],times[2*i+1],coordinatesContainer[0],coordinatesContainer[1]));\n }\n \n }\n}", "function findRoute(graph, from, to){\n //work array adds an object for every update in which at is the location at that specific moment and route is the path followed to get to that place\n let work = [{at: from, route: []}];\n //the inner for is run for every destination of the \"at location\", then the outer array starts again on its next iteration having those locations returns by the graph[at] object key as the \"at\" destination\n for (let i = 0; i < work.length; i++){\n let {at, route} = work[i];\n //graph[at] is the array containing all the destinations possible from the \"at\" location\n for (let place of graph[at]){\n //in case the final destination has been reached, the final destination is added on the route array, which is returns afterwards\n if (place == to) return route.concat(place);\n //in case the current location has been visited before the work array is not updated\n if (!work.some(w => w.at == place)){\n //the work array is updated with an object containing the current location, being the current location added to the route array\n work.push({at: place, route: route.concat(place)});\n }\n }\n }\n}", "function findRoute(graph, from, to){\n //work array adds an object for every update in which at is the location at that specific moment and route is the path followed to get to that place\n let work = [{at: from, route: []}];\n //the inner for is run for every destination of the \"at location\", then the outer array starts again on its next iteration having those locations returns by the graph[at] object key as the \"at\" destination\n for (let i = 0; i < work.length; i++){\n let {at, route} = work[i];\n //graph[at] is the array containing all the destinations possible from the \"at\" location\n for (let place of graph[at]){\n //in case the final destination has been reached, the final destination is added on the route array, which is returns afterwards\n if (place == to) return route.concat(place);\n //in case the current location has been visited before the work array is not updated\n if (!work.some(w => w.at == place)){\n //the work array is updated with an object containing the current location, being the current location added to the route array\n work.push({at: place, route: route.concat(place)});\n }\n }\n }\n}", "function getDirections(start, end, map) {\r\n //let url = `${osrm_server}${start.lng},${start.lat};${end.lng},${end.lat}?geometries=geojson`;\r\n let url = `${gh_server}point=${start.lat},${start.lng}&point=${end.lat},${end.lng}&points_encoded=false&vehicle=car&key=${gh_key}`;\r\n\r\n let oReq = new XMLHttpRequest();\r\n oReq.addEventListener(\"load\", e => {\r\n //let coords = JSON.parse(oReq.responseText)[\"routes\"][0][\"geometry\"][\"coordinates\"];\r\n let parsed = JSON.parse(oReq.responseText)\r\n let coords = parsed[\"paths\"][0][\"points\"][\"coordinates\"];\r\n let distance = parsed[\"paths\"][0][\"distance\"]\r\n distance = Math.round(distance / 100) / 10\r\n\r\n let maps_points = []\r\n coords.forEach(e => maps_points.push({lat: e[1], lng: e[0]}));\r\n\r\n // Remove existing routes\r\n if (g_directions_path !== null)\r\n g_directions_path.setMap(null);\r\n\r\n // Create a new polyline for the new route\r\n g_directions_path = new google.maps.Polyline({\r\n path: maps_points,\r\n strokeColor: \"#0000FF\",\r\n strokeOpacity: 1.0,\r\n strokeWeight: 4\r\n });\r\n\r\n // Get start and end location address\r\n let geocoder = new google.maps.Geocoder;\r\n let startAddr = \"Unknown\";\r\n let endAddr = \"Unknown\";\r\n geocoder.geocode({location: start}, (res, status) => {\r\n if (status === \"OK\")\r\n startAddr = res[0].formatted_address;\r\n })\r\n geocoder.geocode({location: end}, (res, status) => {\r\n if (status === \"OK\")\r\n endAddr = res[0].formatted_address;\r\n })\r\n\r\n // Click handler for the route\r\n g_directions_path.addListener(\"click\", e => {\r\n let pathWindow\r\n\r\n // Create a new div and add the template content to it\r\n let t_directionsDiv = document.querySelector(\"#infoWindowDirectionsTemplate\");\r\n let directionsDiv = document.createElement('div');\r\n directionsDiv.appendChild(document.importNode(t_directionsDiv.content, true));\r\n\r\n // Set addresses\r\n directionsDiv.querySelector(\".routeFrom\").innerHTML += startAddr;\r\n directionsDiv.querySelector(\".routeTo\").innerHTML += endAddr;\r\n directionsDiv.querySelector(\".routeDist\").innerHTML += distance + \" km\";\r\n\r\n // Click handler for the remove button\r\n directionsDiv.querySelector(\".removeDirButton\").addEventListener(\"click\", e => {\r\n g_directions_path.setMap(null);\r\n pathWindow.close();\r\n });\r\n\r\n // Create the infoWindow and add it to the map\r\n pathWindow = new google.maps.InfoWindow({\r\n content: directionsDiv,\r\n position: e.latLng\r\n });\r\n pathWindow.setMap(map);\r\n });\r\n\r\n g_directions_path.setMap(map);\r\n });\r\n oReq.open(\"GET\", url, true);\r\n oReq.send();\r\n}", "function getRoute(latInit,lonInit,latFinal,lonFinal){\n\nvar myHeaders = new Headers();\nvar port = 8080;\nvar myInit = {\n method: 'GET',\n headers: myHeaders,\n mode: 'cors',\n cache: 'default'\n};\n\nvar url = 'http://localhost:' + port + '/route/'+latInit+\"/\"+lonInit+\"/\"+latFinal+\"/\"+lonFinal;\nconst myResponse = fetch(url, myInit)\n .then(function (response) {\n return response.json();\n })\n .then((data) => {\n return data ;\n\n })\n .catch((err) => {\n console.log(\" not get Route Info\");\n });\n\nreturn myResponse;\n\n}", "async function hereGetRoutePolyline(origin, destination){\r\n let routingParameters = {\r\n routingMode: 'fast',\r\n 'transportMode': 'car',\r\n 'origin': origin,\r\n 'destination': destination,\r\n 'return': 'polyline,travelSummary'\r\n }\r\n router.calculateRoute(routingParameters, onResult, function(error){ console.log(error.message); });\r\n}", "function createRoute() {\n\n var start = new google.maps.LatLng(markers[0].position.lat(), markers[0].position.lng());\n var end = new google.maps.LatLng(markers[1].position.lat(), markers[1].position.lng());\n calculateRoute(start, end);\n\n}", "drawRoute(start, finish) {\n let params = {\n \"mode\": \"fastest;car\",\n \"waypoint0\": \"geo!\" + start.Latitude + \",\" + start.Longitude,\n \"waypoint1\": \"geo!\" + finish.Latitude + \",\" + finish.Longitude,\n \"representation\": \"display\"\n }\n this.router.calculateRoute(params, data => {\n if(data.response) {\n data = data.response.route[0];\n let lineString = new H.geo.LineString();\n data.shape.forEach(point => {\n let parts = point.split(\",\");\n lineString.pushLatLngAlt(parts[0], parts[1]);\n });\n let routeLine = new H.map.Polyline(lineString, {\n style: { strokeColor: \"blue\", lineWidth: 5 }\n });\n this.map.addObjects([routeLine]);\n }\n }, error => {\n console.error(error);\n });\n }", "getRouteInformation() {\n const route = this.props.route;\n const data = {\n startingStop: this.getStartingStop(route),\n endingStop: this.getEndingStop(route),\n departTime: this.calculateDepartArive(route),\n arrivalTime: this.calculateArrivalTime(route),\n busInfo: this.routeType(route)\n }\n return data;\n }", "async function returnRoute(startLatLng, endLatLng, originName, destName){\n let route;\n directionsService.route({\n origin: startLatLng.lat+','+startLatLng.lng,\n destination: endLatLng.lat+','+endLatLng.lng,\n travelMode: 'DRIVING'\n }, function(response, status){\n if(status === 'OK'){\n console.log(originName);\n console.log(destName);\n let routes = response.routes[0].legs[0].steps;\n console.log(routes);\n let instructions = routes.map(route =>{\n return route.instructions\n });\n console.log(instructions);\n initializeGameBoard(originName, destName, instructions);\n }\n else{\n console.log(status);\n }\n })\n}", "function findRoute(graph, from , to) {\n let work = [{at: from, route: []}];\n for (let i=0;i<work.length; i++) {\n let {at, route} = work[i];\n for (let place of graph[at]) {\n if (place === to) {\n return route.concat(place);\n }\n if (!work.some(w=>w.at === place)) {\n work.push({at: place, route: route.concat(place)})\n }\n }\n }\n }", "function send_route_map(stops) {\n //create routes include many stop\n if(stops.length==1) return\n var mode = stops[1].mode\n route_mode[\"route1\"]=mode;\n //console.log(mode)\n var start = 1,\n route_index = 1;\n if(stops.length==2){\n routeArray[\"route1\"]=[]\n routeArray[\"route1\"].push(stops[1])\n stops[1][\"route_index\"]=1\n }\n while (start < stops.length) {\n routeArray[\"route\" + route_index]=[]\n for (var i = start; i < stops.length; i++) {\n //add stop to route\n if (stops[i].mode != mode) {\n start = i\n mode = stops[i].mode\n route_mode[\"route\"+(route_index+1)]=mode;\n\n //next route\n break\n }\n stops[i][\"route_index\"]=route_index\n routeArray[\"route\" + route_index].push({\n \"lat\": stops[i].lat,\n \"lng\": stops[i].lng\n });\n\n //increase start route\n start = i + 1\n //console.log(start)\n\n }\n \n route_index++ \n \n\n }\n //console.log(route_index);\n console.log(route_mode);\n //add route mode last\n //route_mode[\"route\"+(route_index-1)]\n // console.log()\n stops[0][\"route_index\"]=1\n routeArray[\"route1\"].unshift({\n \"lat\": stops[0].lat,\n \"lng\": stops[0].lng\n }); \n console.log(routeArray); \n }", "function getViaWaypoints() {\n return directionsDisplay.directions.routes[0].legs[0].via_waypoints;\n }", "function calculateRoute(data) {\n // get boat position\n var lat2 = boatPos[0];\n var lon2 = boatPos[1];\n\n // push the boat to the route array as starting point\n route.push([\"boat\", 0, lat2, lon2])\n\n // push the points from the json file to a new array\n // this format is easier to use later on in the code\n for(let point of data.points){\n let location = new Array();\n location[0] = point.title;\n // leave location[1] clear for the distance\n location[2] = point.lat;\n location[3] = point.lon;\n points.push(location);\n }\n \n // 2. & 3. loop through points and calculate distance between last route item\n while(points.length > 0){\n var lastRouteItem = route.length - 1; \n var nextPoint = calcPoint(route[lastRouteItem]);\n // 2.1 add the nearest point to the previous point to the route array\n route.push(nextPoint);\n }\n\n // log the final route\n console.log(\"Route: \");\n console.log(route);\n\n return route;\n}", "function findRoute(graph, from, to) {\n let work = [{ at: from, route: [] }]; // start point and route\n for (let i = 0; i < work.length; i++) {\n let { at, route } = work[i]; // for each work item\n for (let place of graph[at]) {\n // for each place that `at` is connected to\n if (place == to) return route.concat(place); // if destination found, return list of routes\n if (!work.some(w => w.at == place)) {\n work.push({ at: place, route: route.concat(place) });\n }\n }\n }\n}", "function calculateRoute() {\n var request = {\n origin: startingLocation1.googlePosition,\n destination: startingLocation2.googlePosition,\n provideRouteAlternatives: true,\n //valid travel modes DRIVING, BICYCLING, TRANSIT, WALKING\n travelMode: google.maps.TravelMode[displayInfo.travelMode]\n };\n var bounds;\n console.log(\"calculateRoute called\");\n hmenu_instance.popupMenuHide();\n if (searchFlag === true && displayInfo.touristMode===false)\n clearVenues();\n searchFlag = false;//turn off search flag\n if (platform === 2)\n bounds = new plugin.google.maps.LatLngBounds();\n else\n bounds = new google.maps.LatLngBounds();\n if (navigateFlag === false) {\n if (startingLocation1.googlePosition !== null && startingLocation2.googlePosition !== null) {\n console.log('Navigation not set, setting bounds');\n bounds.extend(startingLocation1.position);\n bounds.extend(startingLocation2.position);\n if (platform !== 2)\n map.fitBounds(bounds);\n else\n map.moveCamera({\n 'target': bounds\n }, function () {\n });\n } else if (startingLocation1.googlePosition !== null){\n zoomMarker(startingLocation1.googlePosition);\n //map.setCenter(startingLocation1.position);\n }else {//(startingLocation2.googlePosition !== null)\n zoomMarker(startingLocation2.googlePosition);\n //map.setCenter(startingLocation2.position);\n }\n return;\n }\n\n\n console.log('calculating route ' + startingLocation1.position + ':' + startingLocation2.position);\n if (startingLocation1.position === null || startingLocation2.position === null)\n return;\n displayInfo.resetMapDisplay=true;\n startingLocation1.marker.setIcon(marker.markerA());//markera);\n if(startingLocation2.customMarker===false)\n startingLocation2.marker.setIcon(marker.markerB());\n if(startingLocation2.place_id && startingLocation2.customMarker===false){\n var iconAddress = VenueObject.prototype.getMarkerUrl(startingLocation2.place.types,false,startingLocation2);\n if(iconAddress)\n startingLocation2.marker.setIcon(iconAddress);\n }\n $('#route-text').text('');\n //closeWindowsReset();\n //closeWindows();\n //this google function gets the actual route\n\n console.log('calculateRoute calling directions service');\n searchWait();\n directionsService.route(request, function (response, status) {\n searchDone();\n console.log('calculateRoute directionServices returned:' + status);\n if (status === google.maps.DirectionsStatus.OK) {\n $('#distance ').text('routes ' + response.routes.length + ': ' + response.routes[0].legs[0].distance.value + ' feet ');\n /*note that a route was found... if this is in the find venue at the end\n * mode, then there is no need to find subroutes\n *\n */\n //this routine does the heavy lifting, and more than just the distance.\n if (navigateFlag === 1) {\n _removeRoutes();\n midCircle.clearCircle();\n routeDetails1 = drawLeg(request, routeDetails1, polylineRoute1, 'red', 'A');\n\n //default will not search for venues, but directly navigate\n //searchForVenues(startingLocation2.googlePosition);\n console.log('A route picked:' + routeDetails1.routeIndex);\n bounds.extend(startingLocation1.position);\n bounds.extend(startingLocation2.position);\n if (platform !== 2)\n map.fitBounds(bounds);\n else\n map.moveCamera({\n 'target': bounds\n }, function () {\n });\n\n } else {\n displayInfo.midlocation = calculateStepDistance(response.routes[0].legs[0].steps, response.routes[0].legs[0].distance.value / 2);\n midCircle.drawSearchCircle(displayInfo.midlocation, false, true);\n console.log('calculating subroutes');\n findSubRoutes();\n }\n } else {\n console.log('Error directionServices' + status);\n switch (status) {\n case \"ZERO_RESULTS\":\n popupMessage(\"Problem retrieving route, no route found.\");\n break;\n case \"NOT_FOUND\":\n popupMessage(\"Problem retrieving direction information, network appears to be down.\");\n break;\n case \"UNKNOWN_ERROR\":\n popupMessage(\"direction information, server error.\");\n break;\n }\n }\n });\n console.log('setting bounds');\n}//end calculateRoute()", "function getRouteMultiplesCoods(arrayX){ //arrayX is array in format[ [lat,lon], [lat,lon], [lat,lon] ]\n \n var coordsHolder = ''; //holds a string of all coord separated by \";\", ie 'lat1,lon1;lat2,lon2', e.g. '-84.5186,39.134;-84.51,39.102'\n for(i = 0; i < arrayX.length; i++){\n\t coordsHolder = coordsHolder + arrayX[i][0] + \",\" + arrayX[i][1] + \";\";\n }\n \n //cut the last symbol \";\" in string that causes Api crash\n coordsHolder = coordsHolder.substring(0, coordsHolder.length - 1);\n\n console.log(coordsHolder);\n \n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + coordsHolder + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken; // //mapboxgl.accessToken is from Credentials/api-access_token.js\n\n console.log(url); \n \n // make an XHR request https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\n var req = new XMLHttpRequest();\n req.responseType = 'json';\n req.open('GET', url, true);\n req.onload = function() {\n\t console.log(req.response);\n var data = req.response.routes[0];\n var route = data.geometry.coordinates;\n\talert(route); //COORDINATES!!!\n\t\n\n\t\n\t //removes prev marker pop-up if it was set by click + removes prev marker if it was set by click //function from js/mapbox_store_location.js\n\t removeMarker_and_Popup();\n\t \n\n\t\n\t//Draw LineString, 2020**************************\n\tmap.addSource('route', {\n'type': 'geojson',\n'data': {\n'type': 'Feature',\n'properties': {},\n'geometry': {\n'type': 'LineString',\n'coordinates':route\n}\n}\n});\nmap.addLayer({\n'id': 'route',\n'type': 'line',\n'source': 'route',\n'layout': {\n'line-join': 'round',\n'line-cap': 'round'\n},\n'paint': {\n'line-color': '#888',\n'line-width': 8\n}\n});\n\t//\n//Draw LineString, 2020**************************\n\t\n };\n \n \n req.send();\n \n\n}", "function findNeighborTiles(map,xCoOrd, yCoOrd){\n var north = yCoOrd - 1;\n var south = yCoOrd + 1;\n var east = xCoOrd + 1;\n var west = xCoOrd - 1;\n\n \n if(isValidNeighbor(map.tiles[xCoOrd][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"south\"] = map.tiles[xCoOrd][south];\n if(isValidNeighbor(map.tiles[xCoOrd][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"north\"] = map.tiles[xCoOrd][north];\n if(isValidNeighbor(map.tiles[east][yCoOrd]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"east\"] = map.tiles[east][yCoOrd];\n if(isValidNeighbor(map.tiles[west][yCoOrd]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"west\"] = map.tiles[west][yCoOrd];\n if(isValidNeighbor(map.tiles[east][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"southeast\"] = map.tiles[east][south];\n if(isValidNeighbor(map.tiles[west][south]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"southwest\"] = map.tiles[west][south];\n if(isValidNeighbor(map.tiles[east][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"northeast\"] = map.tiles[east][north];\n if(isValidNeighbor(map.tiles[west][north]))\n map.tiles[xCoOrd][yCoOrd].neighborTiles[\"northwest\"] = map.tiles[west][north];\n //return whether current tile is a valid neighbor\n function isValidNeighbor(currentTile){\n if(currentTile !== undefined){\n if(currentTile.isPassable){\n return true;\n } else return false;\n }else return false;\n }\n}", "function hereGetRouteSummary(origin, via, destination){\r\n let routingParameters = {\r\n routingMode: 'fast',\r\n 'transportMode': 'car',\r\n 'origin': origin,\r\n 'destination': destination,\r\n 'via': via,\r\n 'return': 'travelSummary'\r\n }\r\n // fill SectionViaTimes Array with origin coordinates\r\n sectionViaTimes[0].push(origin);\r\n //call HERE API\r\n router.calculateRoute(routingParameters, onResultSummary, function(error){ console.log(error.message); }); //console.log(error.message); });\r\n}", "function findRoute(graph, from, to){\n\tlet work = [{reached: from, route: []}];\n\tfor (let i=0; i<work.length; i++){\n\t\tlet {reached, route} = work[i];\n\t\tfor (let place of graph[reached]){\n\t\t\tif (place == to) return route.concat(place);\n\t\t\tif (!work.some(w => w.reached == place)){\t\n\t\t\t\twork.push({reached: place, route: route.concat(place)});\n\t\t\t\t// console.log(`i = ${i}, ${work[work.length-1].route}`);\n\t\t\t}\n\t\t}\n\t}\n}", "getNeighbors(){\n\n var offSetDir = [\n [[-1,-1], [-1, 0], [0,1], [1, 0], [1,-1], [0, -1]],\n [[-1, 0], [-1, 1], [0,1], [1,1], [1, 0], [0, -1]]\n ]\n var parity = this.index.row % 2;\n var neighbors = []\n for(var i = 0; i<6; i++){\n var assocNeighbor = {row: this.index.row + offSetDir[parity][i][0], col: this.index.col + offSetDir[parity][i][1]}\n if(assocNeighbor.row>=0 && assocNeighbor.row < this.board.numRows){\n if(assocNeighbor.col>=0 && assocNeighbor.col< this.board.numColumns){\n if(this.board.getHex(assocNeighbor.row, assocNeighbor.col)!=undefined && this.board.getHex(assocNeighbor.row, assocNeighbor.col).identifier.name== this.identifier.name){\n neighbors.push(this.board.getHex(assocNeighbor.row, assocNeighbor.col));\n\n }\n }\n }\n }\n return neighbors;\n }", "function getRelatedNeighbors(NeighborName) {\n\tvar result = relatedPairs[NeighborName];\n\tif (result != null) {\n\t\treturn result;\n\t}\n\telse{\n\t\twindow.alert(\"wrong name\");\n\t}\n}", "function getNeighborLookupFunction(lyr, arcs) {\n var classifier = getArcClassifier(lyr.shapes, arcs, {reusable: true});\n var classify = classifier(onShapes);\n var currShapeId;\n var neighbors;\n var callback;\n\n function onShapes(a, b) {\n if (b == -1) return -1; // outer edges are b == -1\n return a == currShapeId ? b : a;\n }\n\n function onArc(arcId) {\n var nabeId = classify(arcId);\n if (nabeId == -1) return;\n if (callback) {\n callback(nabeId, arcId);\n } else if (neighbors.indexOf(nabeId) == -1) {\n neighbors.push(nabeId);\n }\n }\n\n return function(shpId, cb) {\n currShapeId = shpId;\n if (cb) {\n callback = cb;\n forEachArcId(lyr.shapes[shpId], onArc);\n callback = null;\n } else {\n neighbors = [];\n forEachArcId(lyr.shapes[shpId], onArc);\n return neighbors;\n }\n };\n }", "function getRoute(item, nonMembers, visited, maxRoutingIterations, morphBuffer) {\n var optimalNeighbor = pickBestNeighbor(item, visited, nonMembers);\n\n if (optimalNeighbor === null) {\n return [];\n } // merge the consecutive lines\n\n\n var mergeLines = function mergeLines(checkedLines) {\n var finalRoute = [];\n\n while (checkedLines.length > 0) {\n var line1 = checkedLines.pop();\n\n if (checkedLines.length === 0) {\n finalRoute.push(line1);\n break;\n }\n\n var line2 = checkedLines.pop();\n var mergeLine = new Line$1(line1.x1, line1.y1, line2.x2, line2.y2);\n var closestItem = getIntersectItem(nonMembers, mergeLine); // merge most recent line and previous line\n\n if (!closestItem) {\n checkedLines.push(mergeLine);\n } else {\n finalRoute.push(line1);\n checkedLines.push(line2);\n }\n }\n\n return finalRoute;\n };\n\n var directLine = new Line$1(item.getModel().x, item.getModel().y, optimalNeighbor.getModel().x, optimalNeighbor.getModel().y);\n var checkedLines = computeRoute(directLine, nonMembers, maxRoutingIterations, morphBuffer);\n var finalRoute = mergeLines(checkedLines);\n return finalRoute;\n}", "getNeighbors(node) {\n const neighbors = [];\n Object.values(node.walls).forEach((side) => {\n if (side instanceof Cell) {\n neighbors.push(side);\n }\n })\n return neighbors; \n }", "async function getRoute(start, end, vid, partofroute, col, mapname) {\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving-traffic/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;\n let result = await makeRequest('GET', url);\n var json = JSON.parse(result);\n var data = json.routes[0];\n if (partofroute == 'driven'){\n trucks[vid].distanceDriven = data.distance;\n }\n else{\n trucks[vid].distanceLeft = data.distance;\n }\n var route = data.geometry.coordinates;\n var geojson = {\n type: 'Feature',\n properties: {},\n geometry: {\n type: 'LineString',\n coordinates: route\n }\n };\n // if the route already exists on the map, reset it using setData\n if (eval(mapname).getSource(vid + partofroute + 'route')) {\n eval(mapname).getSource(vid + partofroute + 'route').setData(geojson);\n } else { // otherwise, make a new request\n eval(mapname).addLayer({\n id: vid + partofroute + 'route',\n type: 'line',\n source: {\n type: 'geojson',\n data: {\n type: 'Feature',\n properties: {\n 'distance': ['get', 'distance'],\n 'duration': ['get', 'duration']\n },\n geometry: {\n type: 'LineString',\n coordinates: geojson\n }\n }\n },\n paint: {\n 'line-color': col,\n 'line-width': 5,\n 'line-opacity': 0.75\n },\n layout: {\n 'visibility': 'none',\n 'line-join': 'round',\n 'line-cap': 'round'\n }\n });\n }\n}", "async function updateRouting (currentLocation, staticDestination, routingMode){\n let response = await fetch (oneMapURL + new URLSearchParams({\n start: currentLocation,\n end: staticDestination,\n routeType: routingMode,\n token: apiKeyRefreshed,\n }\n )\n )\n let data = await response.json()\n // console.log(data)\n // Destructuring thew messy data for what we want/need\n return {\n summary: data.route_summary,\n geo: data.route_geometry\n }\n}", "function declareNeighbors() {\n positions[0].neighbors = [positions[2].resourceRarityScore, positions[9].resourceRarityScore, positions[4].resourceRarityScore]\n positions[1].neighbors = [positions[3].resourceRarityScore, positions[10].resourceRarityScore, positions[5].resourceRarityScore]\n positions[2].neighbors = [positions[0].resourceRarityScore, positions[7].resourceRarityScore, positions[9].resourceRarityScore, positions[14].resourceRarityScore]\n positions[3].neighbors = [positions[1].resourceRarityScore, positions[8].resourceRarityScore, positions[10].resourceRarityScore, positions[15].resourceRarityScore]\n positions[4].neighbors = [positions[0].resourceRarityScore, positions[9].resourceRarityScore, positions[16].resourceRarityScore, positions[11].resourceRarityScore]\n positions[5].neighbors = [positions[1].resourceRarityScore, positions[10].resourceRarityScore, positions[12].resourceRarityScore, positions[17].resourceRarityScore]\n positions[6].neighbors = [positions[8].resourceRarityScore, positions[19].resourceRarityScore, positions[24].resourceRarityScore]\n positions[7].neighbors = [positions[2].resourceRarityScore, positions[14].resourceRarityScore, positions[18].resourceRarityScore]\n positions[8].neighbors = [positions[3].resourceRarityScore, positions[6].resourceRarityScore, positions[15].resourceRarityScore, positions[19].resourceRarityScore]\n positions[9].neighbors = [positions[0].resourceRarityScore, positions[2].resourceRarityScore, positions[4].resourceRarityScore, positions[14].resourceRarityScore, positions[16].resourceRarityScore, positions[20].resourceRarityScore]\n positions[10].neighbors = [positions[1].resourceRarityScore, positions[3].resourceRarityScore, positions[5].resourceRarityScore, positions[15].resourceRarityScore, positions[17].resourceRarityScore, positions[21].resourceRarityScore]\n positions[11].neighbors = [positions[4].resourceRarityScore, positions[13].resourceRarityScore, positions[16].resourceRarityScore, positions[22].resourceRarityScore]\n positions[12].neighbors = [positions[5].resourceRarityScore, positions[17].resourceRarityScore, positions[23].resourceRarityScore]\n positions[13].neighbors = [positions[11].resourceRarityScore, positions[22].resourceRarityScore, positions[29].resourceRarityScore]\n positions[14].neighbors = [positions[2].resourceRarityScore, positions[7].resourceRarityScore, positions[9].resourceRarityScore, positions[18].resourceRarityScore, positions[20].resourceRarityScore, positions[25].resourceRarityScore]\n positions[15].neighbors = [positions[3].resourceRarityScore, positions[8].resourceRarityScore, positions[10].resourceRarityScore, positions[19].resourceRarityScore, positions[21].resourceRarityScore, positions[26].resourceRarityScore]\n positions[16].neighbors = [positions[4].resourceRarityScore, positions[9].resourceRarityScore, positions[11].resourceRarityScore, positions[20].resourceRarityScore, positions[22].resourceRarityScore, positions[27].resourceRarityScore]\n positions[17].neighbors = [positions[5].resourceRarityScore, positions[10].resourceRarityScore, positions[12].resourceRarityScore, positions[21].resourceRarityScore, positions[23].resourceRarityScore, positions[28].resourceRarityScore]\n positions[18].neighbors = [positions[7].resourceRarityScore, positions[14].resourceRarityScore, positions[25].resourceRarityScore, positions[30].resourceRarityScore]\n positions[19].neighbors = [positions[6].resourceRarityScore, positions[8].resourceRarityScore, positions[15].resourceRarityScore, positions[24].resourceRarityScore, positions[26].resourceRarityScore, positions[31].resourceRarityScore]\n positions[20].neighbors = [positions[9].resourceRarityScore, positions[14].resourceRarityScore, positions[16].resourceRarityScore, positions[25].resourceRarityScore, positions[27].resourceRarityScore, positions[32].resourceRarityScore]\n positions[21].neighbors = [positions[10].resourceRarityScore, positions[15].resourceRarityScore, positions[17].resourceRarityScore, positions[26].resourceRarityScore, positions[28].resourceRarityScore, positions[33].resourceRarityScore]\n positions[22].neighbors = [positions[11].resourceRarityScore, positions[13].resourceRarityScore, positions[16].resourceRarityScore, positions[22].resourceRarityScore, positions[29].resourceRarityScore, positions[34].resourceRarityScore]\n positions[23].neighbors = [positions[12].resourceRarityScore, positions[17].resourceRarityScore, positions[28].resourceRarityScore, positions[35].resourceRarityScore]\n positions[24].neighbors = [positions[6].resourceRarityScore, positions[19].resourceRarityScore, positions[31].resourceRarityScore, positions[37].resourceRarityScore]\n positions[25].neighbors = [positions[14].resourceRarityScore, positions[18].resourceRarityScore, positions[20].resourceRarityScore, positions[30].resourceRarityScore, positions[32].resourceRarityScore, positions[38].resourceRarityScore]\n positions[26].neighbors = [positions[15].resourceRarityScore, positions[19].resourceRarityScore, positions[21].resourceRarityScore, positions[31].resourceRarityScore, positions[33].resourceRarityScore, positions[39].resourceRarityScore]\n positions[27].neighbors = [positions[16].resourceRarityScore, positions[20].resourceRarityScore, positions[22].resourceRarityScore, positions[32].resourceRarityScore, positions[34].resourceRarityScore, positions[40].resourceRarityScore]\n positions[28].neighbors = [positions[17].resourceRarityScore, positions[21].resourceRarityScore, positions[23].resourceRarityScore, positions[33].resourceRarityScore, positions[35].resourceRarityScore, positions[41].resourceRarityScore]\n positions[29].neighbors = [positions[13].resourceRarityScore, positions[22].resourceRarityScore, positions[34].resourceRarityScore, positions[42].resourceRarityScore]\n positions[30].neighbors = [positions[18].resourceRarityScore, positions[25].resourceRarityScore, positions[38].resourceRarityScore, positions[36].resourceRarityScore]\n positions[31].neighbors = [positions[19].resourceRarityScore, positions[24].resourceRarityScore, positions[26].resourceRarityScore, positions[37].resourceRarityScore, positions[39].resourceRarityScore, positions[44].resourceRarityScore]\n positions[32].neighbors = [positions[20].resourceRarityScore, positions[25].resourceRarityScore, positions[27].resourceRarityScore, positions[38].resourceRarityScore, positions[40].resourceRarityScore, positions[45].resourceRarityScore]\n positions[33].neighbors = [positions[21].resourceRarityScore, positions[26].resourceRarityScore, positions[28].resourceRarityScore, positions[39].resourceRarityScore, positions[41].resourceRarityScore, positions[46].resourceRarityScore]\n positions[34].neighbors = [positions[22].resourceRarityScore, positions[27].resourceRarityScore, positions[29].resourceRarityScore, positions[40].resourceRarityScore, positions[42].resourceRarityScore, positions[47].resourceRarityScore]\n positions[35].neighbors = [positions[23].resourceRarityScore, positions[28].resourceRarityScore, positions[41].resourceRarityScore, positions[43].resourceRarityScore]\n positions[36].neighbors = [positions[30].resourceRarityScore, positions[38].resourceRarityScore, positions[48].resourceRarityScore]\n positions[37].neighbors = [positions[24].resourceRarityScore, positions[31].resourceRarityScore, positions[44].resourceRarityScore]\n positions[38].neighbors = [positions[25].resourceRarityScore, positions[30].resourceRarityScore, positions[32].resourceRarityScore, positions[36].resourceRarityScore, positions[45].resourceRarityScore, positions[48].resourceRarityScore]\n positions[39].neighbors = [positions[26].resourceRarityScore, positions[31].resourceRarityScore, positions[33].resourceRarityScore, positions[44].resourceRarityScore, positions[46].resourceRarityScore, positions[49].resourceRarityScore]\n positions[40].neighbors = [positions[27].resourceRarityScore, positions[32].resourceRarityScore, positions[34].resourceRarityScore, positions[45].resourceRarityScore, positions[47].resourceRarityScore, positions[50].resourceRarityScore]\n positions[41].neighbors = [positions[28].resourceRarityScore, positions[33].resourceRarityScore, positions[35].resourceRarityScore, positions[43].resourceRarityScore, positions[46].resourceRarityScore, positions[51].resourceRarityScore]\n positions[42].neighbors = [positions[29].resourceRarityScore, positions[34].resourceRarityScore, positions[47].resourceRarityScore]\n positions[43].neighbors = [positions[35].resourceRarityScore, positions[41].resourceRarityScore, positions[51].resourceRarityScore]\n positions[44].neighbors = [positions[31].resourceRarityScore, positions[37].resourceRarityScore, positions[39].resourceRarityScore]\n positions[45].neighbors = [positions[32].resourceRarityScore, positions[38].resourceRarityScore, positions[40].resourceRarityScore, positions[48].resourceRarityScore, positions[50].resourceRarityScore, positions[53].resourceRarityScore]\n positions[46].neighbors = [positions[33].resourceRarityScore, positions[39].resourceRarityScore, positions[41].resourceRarityScore, positions[49].resourceRarityScore, positions[51].resourceRarityScore, positions[52].resourceRarityScore]\n positions[47].neighbors = [positions[34].resourceRarityScore, positions[40].resourceRarityScore, positions[42].resourceRarityScore, positions[50].resourceRarityScore]\n positions[48].neighbors = [positions[38].resourceRarityScore, positions[36].resourceRarityScore, positions[45].resourceRarityScore, positions[53].resourceRarityScore]\n positions[49].neighbors = [positions[39].resourceRarityScore, positions[44].resourceRarityScore, positions[46].resourceRarityScore, positions[52].resourceRarityScore]\n positions[50].neighbors = [positions[40].resourceRarityScore, positions[45].resourceRarityScore, positions[47].resourceRarityScore, positions[53].resourceRarityScore]\n positions[51].neighbors = [positions[41].resourceRarityScore, positions[43].resourceRarityScore, positions[46].resourceRarityScore, positions[52].resourceRarityScore]\n positions[52].neighbors = [positions[46].resourceRarityScore, positions[49].resourceRarityScore, positions[51].resourceRarityScore]\n positions[53].neighbors = [positions[45].resourceRarityScore, positions[48].resourceRarityScore, positions[50].resourceRarityScore]\n}", "function findRoute(graph, from, to) {\n let work = [{at: from, route: []}];\n for (let i = 0; i < work.length; i++) {\n let {at, route} = work[i];\n for (let place of graph[at]) {\n if (place == to) return route.concat(place);\n if (!work.some(w => w.at == place)) {\n work.push({at: place, route: route.concat(place)});\n }\n }\n }\n}", "function laneToLanes(lane){return lane;}", "function laneToLanes(lane){return lane;}", "function constructNeighborInfo(linkNodes) {\n var links = [];\n _.each(linkNodes, function (linkNode) {\n\n var linkNodeLabel = linkNode.attr[scope.mapprSettings.labelAttr] || linkNode.label || 'missing label';\n var linkNodeImage = linkNode.attr[scope.mapprSettings.nodeImageAttr] || linkNode.attr[scope.mapprSettings.nodePopImageAttr] || linkNode.image || '';\n links.push({\n isIncoming: true,\n isOutgoing: false,\n sourceId: linkNode.id,\n targetId: 0,\n linkNode: linkNode,\n linkNodeLabel: linkNodeLabel,\n linkNodeImage: linkNodeImage,\n edgeInfo: null,\n id: null\n });\n });\n return links;\n }", "neighbours(){\n var neighbours = []\n neighbours.push(this.neighbour(0,1))\n //neighbours.push(this.neighbour(1,1))\n neighbours.push(this.neighbour(1,0))\n //neighbours.push(this.neighbour(1,-1))\n neighbours.push(this.neighbour(0,-1))\n //neighbours.push(this.neighbour(-1,-1))\n neighbours.push(this.neighbour(-1,0))\n //neighbours.push(this.neighbour(-1,1))\n return neighbours\n }", "function bestRoutes(from, to) {\n let directions = [];\n let dx = to.x - from.x;\n let dy = to.y - from.y;\n\n // console.dir({ what: \"bestRoutes\", from, to });\n\n if (Math.abs(dx) >= Math.abs(dy)) { // horizontal movement preferred\n directions.push( (dx > 0) ? 'right' : 'left');\n if (dy)\n directions.push( (dy > 0) ? 'down' : 'up'); // 2nd choice\n }\n else { // vertical movement\n directions.push( (dy > 0) ? 'down' : 'up');\n if (dx)\n directions.push( (dx > 0) ? 'right' : 'left'); // 2nd choice\n }\n\n // console.dir(directions);\n\n return directions;\n }", "function findRoute(from, to, connections) {\n let work = [{ at: from, via: null }];\n for (let i = 0; i < work.length; i++) {\n const { at, via } = work[i];\n for (const next of connections.get(at) || []) {\n // Eventually, one node will have the destination as its neighbor.\n // Then it will return the first value way back from the first step we take.\n // It assures us if we choose that route, it will take us to the destination.\n if (next === to) return via;\n if (!work.some(w => w.at === next)) {\n // \"via\" will stay the same as the first value it assigned to be.\n work.push({ at: next, via: via || next });\n }\n }\n }\n return null;\n}", "function use_route(r_name, params2) {\n if (dr[r_name]) {\n const data = {}, path = dr[r_name].path, params1 = dr[r_name].params;\n params1.forEach(param => data[param] = db[path][param]);\n params2.forEach(param => data[param] = db[path][param]);\n return data\n }\n else return undefined\n }", "function findRoute(graph, from, to) {\n console.log(\"Origin: \", from, \"Destination: \", to);\n // This is the work list:\n let work = [{at: from, route: []}];\n for (let i = 0; i < work.length; i++) {\n let {at, route} = work[i]; \n // Loop through all possible destinations from work[i][at]\n for (let place of graph[at]) {\n console.log(\"Checking: \", route.concat(place));\n // If the place is the destination, return the route, with this place added to the end\n if (place == to) return route.concat(place);\n // If this place is not yet in the work list, add the place and this route to work list\n // It will be added to the end of the work list, so as i continues to iterate, it will eventually reach this item if needed\n if (!work.some(w => w.at == place)) {\n work.push({at: place, route: route.concat(place)});\n }\n // If place has been reached before throw this route away, because the easlier one is less than or equally as short\n }\n console.log(\"Routes in work: \", work.map(w => w.route));\n }\n}", "calculateRoute(startFeature, endFeature) {\n const getId = feature => {\n const payload = JSON.parse(feature.properties.althurayyaData)\n return payload.URI;\n }\n\n const start = getId(startFeature);\n const end = getId(endFeature);\n\n // Note that this returns the IDs of the *NODES* along the road, i.e.\n // we now need to look up the segments which connect these nodes\n const path = this._graph.findShortestPath(start, end);\n\n if (path) {\n // Sliding window across path, pairwise\n const segments = [];\n for (var i=1; i<path.length; i++) {\n segments.push(this.findSegment(path[i - 1], path[i]));\n }\n\n return segments;\n }\n }", "function handleGraphHopperRouting (path: Path, individualLegs: boolean = false): any {\n const {instructions, points} = path\n // Decode polyline and reverse coordinates.\n const decodedPolyline = decodePolyline(points).map(c => ([c[1], c[0]]))\n if (individualLegs) {\n // Reconstruct individual legs from the instructions. NOTE: we do not simply\n // use the waypoints found in the response because for lines that share\n // street segments, slicing on these points results in unpredictable splits.\n // Slicing the line along distances is much more reliable.\n const segments = []\n const waypointDistances = [0]\n let distance = 0\n // Iterate over the instructions, accumulating distance and storing the\n // distance at each waypoint encountered. Distances are used to slice the\n // line geometry if individual legs are needed. NOTE: Waypoint === routing\n // point provided in the request.\n instructions.forEach(instruction => {\n if (instruction.text.match(/Waypoint (\\d+)/)) {\n // Add distance value to list\n waypointDistances.push(distance)\n } else {\n distance += instruction.distance\n }\n })\n // Add last distance measure.\n // FIXME: Should this just be the length of the entire line?\n // console.log(waypointDistances, json.paths[0].distance)\n waypointDistances.push(distance)\n const decodedLineString = lineString(decodedPolyline)\n if (waypointDistances.length > 2) {\n for (var i = 1; i < waypointDistances.length; i++) {\n const slicedSegment = lineSliceAlong(\n decodedLineString,\n waypointDistances[i - 1] / 1000,\n waypointDistances[i] / 1000\n )\n segments.push(slicedSegment.geometry.coordinates)\n }\n // console.log('individual legs', segments)\n return segments\n } else {\n // FIXME does this work for two input points?\n return [decodedPolyline]\n }\n } else {\n return decodedPolyline\n }\n}", "async function GpsPointsForAroute() {\n let routingService = new routing.RoutingService(process.env.MICRO_API_TOKEN);\n let rsp = await routingService.route({\n destination: {\n latitude: 52.529407,\n longitude: 13.397634,\n },\n origin: {\n latitude: 52.517037,\n longitude: 13.38886,\n },\n });\n console.log(rsp);\n}", "function poly(best) {\n directionsService = new google.maps.DirectionsService();\n directionsDisplay = new google.maps.DirectionsRenderer();\n directionsDisplay.setMap(map);\n var waypts = [];\n if (travelType == \"GR\") {\n for (var i = 1; i < best.length-1; i++) {\n waypts.push({\n location: nodes[best[i]],\n stopover: true\n });\n }\n // Pridedamas marsrutas i zemelapi\n var request = {\n origin: nodes[0],\n destination: nodes[0],\n waypoints: waypts,\n travelMode: 'DRIVING',\n };\n directionsService.route(request, function (response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n clearMapMarkers();\n });\n }\n else if (travelType == \"NGR\") {\n for (var i = 1; i < best.length-1; i++) {\n waypts.push({\n location: nodes[best[i]],\n stopover: true\n });\n }\n // Pridedamas marsrutas i zemelapi\n var request = {\n origin: nodes[0],\n destination: nodes[nodes.length - 1],\n waypoints: waypts,\n travelMode: 'DRIVING',\n };\n directionsService.route(request, function (response, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n directionsDisplay.setDirections(response);\n }\n clearMapMarkers();\n });\n }\n best.shift();\n best.splice(best.length - 1, 1);\n }", "function getNeighborObjects(neighbors) {\n let nodeObjects = []\n neighbors.forEach((neighbor) => {\n let nodeId = neighbor[0] + '-' + neighbor[1]\n nodeObjects.push(getObject(nodeId))\n });\n return nodeObjects\n }", "function getVehicles(routeGiven) {\n\t\tvar query = \"http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=\" + routeGiven + \"&t=\" + routes[routeGiven][\"lastTime\"];\n\t\td3.xml(query, function(error, xml) {\n\t\t\tif(error){\n\t\t\t\tconsole.log(\"Error Fetching Data Try Refreshing Page\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tjson = $.xml2json(xml);\n\t\t\troutes[routeGiven][\"lastTime\"] = json[\"lastTime\"][\"time\"];\n\t\t\tif (typeof routes[routeGiven][\"vehicles\"] == \"undefined\") {\n\t\t\t\troutes[routeGiven][\"vehicles\"] = [];\n\t\t\t}\n\t\t\tvar vehicles = routes[routeGiven][\"vehicles\"];\n\t\t\tif (typeof json.vehicle !== \"undefined\") {\n\t\t\t\tfor (var i = 0; i < json.vehicle.length; i++) {\n\t\t\t\t\tvar newVehicle = true;\n\t\t\t\t\tfor (var j = 0; j < vehicles.length; j++) {\n\t\t\t\t\t\tif (vehicles[j][\"id\"] == json.vehicle[i][\"id\"]) {\n\t\t\t\t\t\t\tjson.vehicle[i].lat_init = vehicles[j].lat_init;\n\t\t\t\t\t\t\tjson.vehicle[i].lon_init = vehicles[j].lon_init;\n\t\t\t\t\t\t\tvehicles[j] = json.vehicle[i];\n\t\t\t\t\t\t\tnewVehicle = false;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (newVehicle) {\n\t\t\t\t\t\tjson.vehicle[i].lat_init = json.vehicle[i].lat;\n\t\t\t\t\t\tjson.vehicle[i].lon_init = json.vehicle[i].lon;\n\t\t\t\t\t\troutes[routeGiven][\"vehicles\"].push(json.vehicle[i]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}", "function __showRoutePath(code, major, data) {\n function retMajorStyle() {\n switch(major) {\n case 1:\n return {\n //className: __getRouteClass(),\n color: systemEffect[\"routingTip\"][\"color\"],\n weight: systemEffect[\"routingTip\"][\"weight\"],\n opacity: systemEffect[\"routingTip\"][\"opacity\"],\n smoothFactor: systemEffect[\"routingTip\"][\"smoothFactor\"]\n };\n case 2:\n return {\n //className: __getRouteClass(),\n color: systemEffect[\"routingTip2\"][\"color\"],\n weight: systemEffect[\"routingTip2\"][\"weight\"],\n opacity: systemEffect[\"routingTip2\"][\"opacity\"],\n smoothFactor: systemEffect[\"routingTip2\"][\"smoothFactor\"]\n };\n case 11:\n return {\n //className: __getRouteClass(),\n color: systemEffect[\"routingTip11\"][\"color\"],\n weight: systemEffect[\"routingTip11\"][\"weight\"],\n opacity: systemEffect[\"routingTip11\"][\"opacity\"],\n smoothFactor: systemEffect[\"routingTip11\"][\"smoothFactor\"]\n };\n case 12:\n return {\n //className: __getRouteClass(),\n color: systemEffect[\"routingTip12\"][\"color\"],\n weight: systemEffect[\"routingTip12\"][\"weight\"],\n opacity: systemEffect[\"routingTip12\"][\"opacity\"],\n smoothFactor: systemEffect[\"routingTip12\"][\"smoothFactor\"]\n };\n }\n }\n\n // add the information\n __sumName = data[\"routes\"][0][\"legs\"][0][\"summary\"];\n __allLine = [];\n\n // add to the geojson collection\n __geoLine = [];\n \n // add each part of route\n var allPoints = data[\"routes\"][0][\"legs\"][0][\"steps\"];\n \n // for prepare a line\n var prepareLineFlag = 0;\n var startPoint = null;\n var endPoint = null;\n var lineRange = null;\n var locInfo = [\"\",\"\"];\n \n for(var i = 0 ; i < allPoints.length ; i++) { \n for(var j = 0 ; j < allPoints[i][\"intersections\"].length ; j++) {\n switch(prepareLineFlag) {\n case 0:\n // start point\n startPoint = new L.LatLng(allPoints[i][\"intersections\"][j][\"location\"][1], allPoints[i][\"intersections\"][j][\"location\"][0]);\n if(getDictionaryKeyList(allPoints[j]).indexOf(\"name\") > -1) {\n locInfo[0] = allPoints[j][\"name\"];\n } else {\n locInfo[0] = \"\";\n }\n \n // set the flag to the end point\n prepareLineFlag = 1;\n break;\n case 1:\n // end point\n endPoint = new L.LatLng(allPoints[i][\"intersections\"][j][\"location\"][1], allPoints[i][\"intersections\"][j][\"location\"][0]);\n if(getDictionaryKeyList(allPoints[j]).indexOf(\"name\") > -1) {\n locInfo[1] = allPoints[j][\"name\"];\n } else {\n locInfo[1] = \"\";\n }\n \n // draw the line\n lineRange = [startPoint, endPoint];\n var routePolyline = new L.Polyline(lineRange, retMajorStyle());\n //__locList.push(routePolyline);\n all_path_list[code].push(routePolyline);\n routePolyline.addTo(mymap);\n \n // the current end point is the next start point\n startPoint = endPoint;\n endPoint = null;\n locInfo[0] = locInfo[1];\n break;\n }\n } // inner for-loop\n } // outer for-loop\n}", "function getDirections(){\n\tvar waypts = [];\n\tfor(landmark in itinerary){\n\t\tvar point = itinerary[landmark].mapData.geometry.location\n\t\tvar loc = new google.maps.LatLng(point.lat, point.lng);\n\t\twaypts.push({location: loc, stopover: true});\n\t\tconsole.log(itinerary[landmark].yelpData);\n\t}\n\n\tvar request = {\n\t\torigin: origin,\n\t\tdestination: waypts[waypts.length - 1].location,\n\t\twaypoints: waypts.slice(0, waypts.length - 1),\n\t\ttravelMode: google.maps.TravelMode.WALKING\n\t};\n\n\tdirectionsService.route(request, function(response, status) {\n\t\tif (status == google.maps.DirectionsStatus.OK) {\n\t\t\tdirectionsDisplay.setDirections(response);\n\t\t\tvar route = response.routes[0];\n\t\t\trenderDirections(route);\n\t\t}\n\t});\n}", "function getRoute (lat, lng) {\n //console.log(\"image coordinates\", lat, lng);\n $.ajax({\n 'url': 'http://free.rome2rio.com/api/1.2/json/Search?key=API KEY&oName=Helsinki&dPos=' + lat + ',' + lng + '&oKind=city&dKind=city',\n 'success': processRoute\n });\n}", "function planReroute(destination) {\n var currentPosition;\n Navigation.getCurrentPosition().then(function(position) {\n currentPosition = [position.coords.longitude, position.coords.latitude];\n Directions.get(currentPosition,\n [destination.lng, destination.lat]).then(success, failure);\n });\n function success(response) {\n angular.extend(Map.geojson, {\n data: response\n });\n $state.go('navigate');\n }\n function failure(error) {\n var msg = error.msg ? error.msg : 'Unable to load route. Please try a different destination.';\n Notifications.show({\n text: msg\n });\n }\n }", "function PlanRoad (start, end)\n{\n //Check if road is already known\n var roadIsKnown = false;\n var knownRoads = start.room.memory.roomInfo.knownRoads;\n\n if ( knownRoads && knownRoads.length > 0)\n {\n for ( let n in knownRoads )\n {\n var knownRoad = knownRoads[n];\n if ( knownRoad.start.x == start.pos.x && knownRoad.start.y == start.pos.y && knownRoad.end.x == end.pos.x && knownRoad.end.y == end.pos.y )\n {\n roadIsKnown = true;\n }\n }\n }\n // If not a known road, plan it.\n if ( !roadIsKnown )\n {\n var road = {};\n\n // Special case, if start and end are the same, build a road around the object\n // otherwise plan one from start to end\n if (start == end )\n {\n console.log('control.Construction.PlanRoad: Around Position: ' + start.pos );\n\n road = getSurroundingPositions(start) ;\n\n }\n else\n {\n console.log('control.Construction.PlanRoad: start: ' + start + ' - position: ' + start.pos );\n console.log('control.Construction.PlanRoad: end: ' + end + ' - position: ' + end.pos );\n\n road = PathFinder.search(start.pos, { pos: end.pos, range: 1 }) ;\n }\n for ( let n in road.path )\n {\n var buildPosition = road.path[n];\n start.room.memory.roomInfo.futureConstructionSites.push({position: buildPosition, structure: STRUCTURE_ROAD})\n }\n\n start.room.memory.roomInfo.knownRoads.push({start: start.pos, end: end.pos });\n }\n\n // Set a return value, so the caller knows if we did anything\n return (!roadIsKnown);\n}", "function getRoutes(){\n\t\tvar query = \"http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a=sf-muni\";\n\t\tvar retry = 0;\n\t\tvar trains = [\"L\", \"M\", \"N\", \"S\", \"F\", \"J\", \"KT\"];\n\t\td3.xml(query, function(error, xml) {\n\t\t\tif(error){\n\t\t\t\tconsole.log(\"Error Fetching Data Try Refreshing Page\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tvar json = $.xml2json(xml);\n\t\t\t$.each(json[\"route\"], function(i,m) {\n\t\t\t\tvar queryIn = \"http://webservices.nextbus.com/service/publicXMLFeed?command=routeConfig&a=sf-muni&r=\" + m.tag;\n\t\t\t\td3.xml(queryIn, function(error, xml) {\n\t\t\t\t\tvar json = $.xml2json(xml);\n\t\t\t\t\troutes[m.tag] = json.route;\n\t\t\t\t\troutes[m.tag][\"vRefresh\"] = false;\n\t\t\t\t\tvar routeButton= \"<div id=\" + m.tag + \" class='button'>\" + m.tag + \"</div>\";\n\t\t\t\t\tif ($.inArray(m.tag, trains) == -1) {\n\t\t\t\t\t\t$(\"#buses\").append(routeButton);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t$(\"#trains\").append(routeButton);\n\t\t\t\t\t}\n\t\t\t\t\tgetVehicles(m.tag);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t}", "function createRoute(data, route_type){\n //set title div text\n var fromText = data[\"data\"][\"from\"];\n var toText = data[\"data\"][\"to\"];\n document.getElementById(\"title\").innerText = \"From \" + fromText + \" to \" + toText + \"\\n Route Type: \" + route_type;\n\n var routeData = data[\"data\"][\"route\"][route_type];\n\n //get start and end coords\n var routeDataCoords = routeData[\"coords\"];\n var mainCoords = routeDataCoords.replace(/,/g, ' ').split(' '); \n var l = mainCoords.length;\n start = [parseFloat(mainCoords[1]), parseFloat(mainCoords[0])];\n end = [parseFloat(mainCoords[l-1]), parseFloat(mainCoords[l-2])];\n\n //create new routeObject with start and end variables\n var route = new routeObject(start, end);\n\n //for each turn in object\n $.each(routeData[\"turns\"], function (key, val) {\n\n //distance of step\n var dist = val[\"dist\"];\n\n //instruction issued at each turn\n var instr = val[\"move\"] + \" \" + val[\"onto\"];\n\n //parse string into floating point numbers\n var turnCoordsStringArray = val[\"coords\"].replace(/,/g, ' ').split(' ');\n\n //get coordinates along the path\n var pathCoords = [];\n for (i = 0; i < turnCoordsStringArray.length; i += 2) {\n pathCoords.push(\n [parseFloat(turnCoordsStringArray[i + 1]), parseFloat(turnCoordsStringArray[i])]\n )\n }\n\n //get start and end of path\n stepStart = pathCoords[0];\n stepEnd = pathCoords[pathCoords.length - 1];\n\n route.steps.push(\n new stepObject(stepStart, stepEnd, dist, instr, pathCoords)\n );\n\n });\n showSteps(route);\n}", "function mapDirections(route) {\n var waypts = [];\n\n //Add the origin to the end to finish loop\n route.push(route[0]);\n\n //number to track the route index we are at (needed if route length > 8)\n var tracking = 0;\n for (var i = 0; i < Math.ceil(route.length / 8); i++) {\n //Slice route into size-8 lists (due to GMaps constraints on waypoints)\n waypts = [];\n var sliced = route.slice(tracking, ((i+1) * 8));\n\n //construct waypoints\n for (var j = tracking; j < ((i+1) * 8); j++) {\n if (route[j]) {\n waypts.push({\n location: route[j],\n stopover: true\n });\n }\n else {\n break;\n }\n }\n\n //construct request\n var request = {\n origin: sliced[0],\n destination: sliced[sliced.length - 1],\n waypoints: waypts,\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n //execute request\n directionsService.route(request, function (result, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n renderDirections(result);\n }\n else {\n console.log(status);\n }\n });\n //update the tracking integer\n tracking = ((i+1) * 8) - 1;\n }\n}", "function buildRouteObject(origin, destination, waypoints) {\n if (waypoints === 'undefined') {\n routeObject = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING\n }\n return routeObject;\n } else {\n routeObject = {\n origin: origin,\n destination: destination,\n travelMode: google.maps.TravelMode.DRIVING,\n waypoints: waypoints\n }\n return routeObject;\n }\n }", "function init() {\n\n var mapOptions = {\n // center: locations[0],\n zoom: 4,\n mapTypeId: google.maps.MapTypeId.ROADMAP\n };\n map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);\n // calcRoute(msg);\n // calcRoute(m);\n // calcRoute(ms);\n\n\n for(i = 0; i < to_loc.length; i++) {\n \tvar lol = new Array();\n \tlol[0] = from_loc[i];\n \tlol[1] = to_loc[i];\n \tcalcRoute(lol);\n }\n\n}", "function getJpidBestRoute(map, srcLat, srcLon, destLat, destLon) {\n\n\tvar temp = new Date();\n\tvar dateTime = [temp.toString(), temp.getDay(), temp.getHours(), temp.getMinutes(), temp.getSeconds()]\n\t\n\t$.ajax({\n\t dataType: \"json\",\n\t url: $SCRIPT_ROOT + \"/best_route/\" + srcLat + \"/\" + srcLon + \"/\" + destLat + \"/\" + destLon + \"/\" + searchPreference + \"/\" + dateTime,\n\t async: true, \n\t success: function(data) {\n\t\t \n\t\t if (data == 'No Journey Found') {\n\t\t\t errorHandleNoRoutes(); \n\t\t } else {\n\t\tfor (var i = 0; i < data.length; i++) {\n\t\t\tinformation = data[i][0];\n\t\t\tjpid = data[i][1];\n\t\t\tvar srcStop = data[i][2];\n\t\t\tvar destStop = data[i][3];\n\t\t\tdrawMapRoute(map, srcStop, destStop);\n\t\t}\t\n\t\t setTimeout(function(){formatInfoWindow(data);}, 1000);\n\t\t}\n\t }\n\t});\n}", "computeRoute(){\n if (this.startLocation && this.endLocation){\n if (this.mode === \"MILES\"){\n this.plotMiles();\n } else {\n this.plotDirection();\n }\n }\n }", "neighbors(index1, index2) {\n const tile1 = this.getTilePosition(index1);\n const tile2 = this.getTilePosition(index2);\n\n const tile1pos = {x: tile1.x / this.tileWidth, y: tile1.y / this.tileHeight};\n const tile2pos = {x: tile2.x / this.tileWidth, y: tile2.y / this.tileHeight};\n\n if((tile1pos.x == tile2pos.x && Math.abs(tile2pos.y - tile1pos.y) == 1) ||\n (tile1pos.y == tile2pos.y && Math.abs(tile2pos.x - tile1pos.x) == 1) ) {\n return true;\n }\n\n return false;\n if((emptyTile.x == clickedTile.x || emptyTile.y == clickedTile.y) && (clickedTile.x != emptyTile.x || clickedTile.y != emptyTile.y)\n && (Math.abs(emptyTile.x - clickedTile.x) == 1 || Math.abs(emptyTile.y - clickedTile.y) == 1)) {\n\n }\n }", "function getFlightsWithAirports(input, originAirport, destinationAirport) {\n\n\n var res = {\n \"outgoingFlights\": []\n };\n\n var resRT = {\n \"outgoingFlights\": [],\n \"returnFlights\": []\n };\n\n if (Object.keys(input).length === 1) {\n\n for (var i = 0; i < input.outgoingFlights.length; i++) {\n\n var flight = input.outgoingFlights[i];\n\n if (flight.origin === originAirport && flight.destination === destinationAirport)\n res.outgoingFlights.push(flight);\n }\n\n return res;\n\n }\n\n\n if (Object.keys(input).length === 2) {\n\n\n\n for (i = 0; i < input.outgoingFlights.length; i++) {\n var outFlight = input.outgoingFlights[i];\n if (outFlight.origin === originAirport && outFlight.destination === destinationAirport)\n resRT.outgoingFlights.push(outFlight);\n\n }\n for (var j = 0; j < input.returnFlights.length; j++) {\n var returnFlight = input.returnFlights[j];\n if (returnFlight.origin === destinationAirport && returnFlight.destination === originAirport) {\n resRT.returnFlights.push(returnFlight);\n }\n\n }\n return resRT;\n\n }\n\n}", "function findDistances(matrix, route)\r\n{\r\n\t// [i][0] - city number\r\n\t// [i][1] - distance\r\n\t//console.log(route);\r\n\tvar previous = route[0][0];\r\n\tvar current = route[0][0];\r\n\tvar newRoute = [];\r\n\tnewRoute.push([current,0]);\r\n\tfor (var i = 1; i<route.length; i++)\r\n\t{\r\n\t\tcurrent = route[i][0]\r\n\t\t//push current city index and distance from current to previous\r\n\t\tnewRoute.push([current, matrix[current][previous]]);\r\n\t\tprevious = current;\r\n\t}\r\n\t//console.log(\"fd nr: \",newRoute);\r\n\treturn newRoute;\r\n}", "function findPaths_1X(from, to, costBound) {\n if (from == to || from.isNeighborOf(to)) {\n return [];\n }\n //console.log(\"1X finder from \" + from.getName() + \" to \" + to.getName())\n var results = Array();\n var allLinesCount = HK18_ALL_LINES.length;\n for (var i = 0; i < allLinesCount; i++) {\n var L1 = HK18_ALL_LINES[i];\n var L1_stops = L1.stops;\n var L1_startIndex = -1;\n for (var j = 0; j < L1_stops.length; j++) {\n if (L1_stops[j] == from || L1_stops[j].isNeighborOf(from)) {\n L1_startIndex = j;\n break;\n }\n }\n if (L1_startIndex == -1) {\n // User cannot depart from FROM using L1. Next line!\n continue;\n }\n for (var j = 0; j < allLinesCount; j++) {\n if (j == i) {\n // Same line. Should have used the 0X version.\n continue;\n }\n var L2 = HK18_ALL_LINES[j];\n var L2_stops = L2.stops;\n var L2_endIndex = -1;\n for (var k = 0; k < L2_stops.length; k++) {\n if (L2_stops[k] == to || L2_stops[k].isNeighborOf(to)) {\n L2_endIndex = k;\n break;\n }\n }\n if (L2_endIndex == -1) {\n // Users cannot reach To using L2. Next line!\n continue;\n }\n // Now we are going to find the intersection, if any.\n var L1_interIndex = -1;\n var L2_interIndex = -1;\n for (var k = 0; k < L2_stops.length; k++) {\n var currentStop = L2_stops[k];\n if (currentStop.isInternal()) {\n // Internal stations are excluded.\n // Never interchange at internal stops. They are for counting only.\n continue;\n }\n var tempIndex = L1.getIndexOfWaypoint(currentStop);\n if (tempIndex != -1 && L1_interIndex == -1) {\n // L1 contains the current stop, which is a member of L2\n // Both line intersects.\n L1_interIndex = tempIndex;\n L2_interIndex = k;\n }\n }\n if (L1_interIndex == -1) {\n // No intersection found. Next!\n continue;\n }\n // Both intersects!\n // Check if intersection is meaningful:\n // 1. L1 intersection should be strictly after FROM\n // 2. L2 intersection should be strictly before TO\n // Note that we have already excluded internal stations some lines above.\n if (L1_interIndex > L1_startIndex && L2_interIndex < L2_endIndex) {\n // Valid! Pack it into a nice Path object.\n var path = new Path();\n path.addConnection(new Connection(L1, L1_startIndex, L1_interIndex));\n path.addConnection(new Connection(L2, L2_interIndex, L2_endIndex));\n if (path.getTotalAdjustedCost() < costBound) {\n console.log(\"Path of \" + L1.getName() + \" -> \" + L2.getName() + \" = \" + path.getTotalAdjustedCost());\n // Further restrict the cost, to make these lines viable compared to direct lines (if exists)\n //console.log(path);\n results.push(path);\n }\n }\n }\n }\n // We still aim to minimize the travel cost, since having to interchange is in itself a huge drawback of 1X lines.\n var minCost = Infinity;\n for (var i = 0; i < results.length; i++) {\n var calcCost = results[i].getTotalAdjustedCost();\n if (calcCost < minCost) {\n minCost = calcCost;\n }\n }\n for (var i = results.length - 1; i >= 0; i--) {\n if (results[i].getTotalAdjustedCost() > minCost) {\n results.splice(i, 1);\n }\n }\n // All is done. Return the results.\n return results;\n}", "function getRoute(origin_latitude,origin_longitude,destination_latitude,destination_longitude, map) {\n // make a directions request using cycling profile\n // an arbitrary start will always be the same\n // only the end or destination will change\n var start = [origin_latitude, origin_longitude];\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving/' + origin_longitude + ',' + origin_latitude + ';' + destination_longitude + ',' + destination_latitude + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;\n console.log(url)\n // make an XHR request https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\n var req = new XMLHttpRequest();\n req.responseType = 'json';\n req.open('GET', url, true);\n req.onload = function() {\n\n var data = req.response.routes[0];\n var route = data.geometry.coordinates;\n var geojson = {\n type: 'Feature',\n properties: {},\n geometry: {\n type: 'LineString',\n coordinates: route\n }\n };\n map.addLayer({\n id: 'route',\n type: 'line',\n source: {\n type: 'geojson',\n data: {\n type: 'Feature',\n properties: {},\n geometry: {\n type: 'LineString',\n coordinates: geojson.geometry.coordinates\n }\n }\n },\n layout: {\n 'line-join': 'round',\n 'line-cap': 'round'\n },\n paint: {\n 'line-color': '#3887be',\n 'line-width': 5,\n 'line-opacity': 0.75\n }\n });\n };\n req.send();\n}", "function pols_get_entrance(){\r\n\tvar links = this.geo_links_get_incoming();\r\n\t\r\n\tfor (var id in links){\r\n\t\tif (links[id].source_type == 'door'){\r\n\t\t\treturn {\r\n\t\t\t\ttsid: links[id].street_tsid,\r\n\t\t\t\tx: links[id].x,\r\n\t\t\t\ty: links[id].y\r\n\t\t\t};\r\n\t\t}\r\n\t}\r\n\t\r\n\treturn {};\r\n}", "function Neighbours(x, y)\n\n{\n\nvar\n\nN = y - 1,\n\nS = y + 1,\n\nE = x + 1,\n\nW = x - 1,\n\nmyN = N > -1 && canWalkHere(x, N),\n\nmyS = S < worldHeight && canWalkHere(x, S),\n\nmyE = E < worldWidth && canWalkHere(E, y),\n\nmyW = W > -1 && canWalkHere(W, y),\n\nresult = [];\n\nif(myN)\n\nresult.push({x:x, y:N});\n\nif(myE)\n\nresult.push({x:E, y:y});\n\nif(myS)\n\nresult.push({x:x, y:S});\n\nif(myW)\n\nresult.push({x:W, y:y});\n\nfindNeighbours(myN, myS, myE, myW, N, S, E, W, result);\n\nreturn result;\n\n}", "function shapes() {\n shape = [];\n tor = -1;\n fetch('http://www-devl.bu.edu/nisdev/php5/bu-mobile-backend-demo/bu-mobile-backend/rpc/bus/shapes.json.php')\n .then(function(response) {\n return response.json();\n })\n .then(function(myJson) {\n if (myJson['ResultSet']['Result']['day_route']['active'] == true) {\n tor = 0;\n for (var i = 0; i < myJson['ResultSet']['Result']['day_route']['coords'].length; i++) {\n stops = {};\n stops[\"lat\"] = parseFloat(myJson['ResultSet']['Result']['day_route']['coords'][i]['lat']);\n stops[\"lng\"] = parseFloat(myJson['ResultSet']['Result']['day_route']['coords'][i]['lng']);\n shape.push(stops);\n // console.log(stops)\n }\n } else if (myJson['ResultSet']['Result']['night_route']['active'] == true) {\n tor = 1;\n for (var i = 0; i < myJson['ResultSet']['Result']['night_route']['coords'].length; i++) {\n stops = {};\n stops[\"lat\"] = parseFloat(myJson['ResultSet']['Result']['night_route']['coords'][i]['lat']);\n stops[\"lng\"] = parseFloat(myJson['ResultSet']['Result']['night_route']['coords'][i]['lng']);\n shape.push(stops);\n // console.log(stops)\n }\n } else if (myJson['ResultSet']['Result']['express_route']['active'] == true) {\n tor = 2;\n for (var i = 0; i < myJson['ResultSet']['Result']['express_route']['coords'].length; i++) {\n stops = {};\n stops[\"lat\"] = parseFloat(myJson['ResultSet']['Result']['express_route']['coords'][i]['lat']);\n stops[\"lng\"] = parseFloat(myJson['ResultSet']['Result']['express_route']['coords'][i]['lng']);\n shape.push(stops);\n // console.log(stops)\n }\n } else {\n tor = -1;\n }\n // console.log(tor);\n // console.log(myJson['ResultSet']['Result']['day_route']['coords'].length);\n // var test = myJson['ResultSet']['Result']['day_route'][0][0]['lat'];\n // console.log(test)\n\n // console.log(shape)\n// if (myJson['totalResultsAvailable'] > 0) {\n// console.log('ryep');\n// for (var i = 0; i < myJson['totalResultsAvailable']; i++) {\n// console.log('fyep');\n// console.log(i)\n// if (myJson['ResultSet']['Result'][i]['active'] == true) {\n// result = [];\n// console.log('yep');\n// stops.push(myJson['ResultSet']['Result'][i]['lat']);\n// stops.push(myJson['ResultSet']['Result'][i]['lng']);\n// shape.push(result);\n// }\n// }\n// }\n busPosition();\n reloadBusPosition();\n }\n );\n}", "async getDirections(startLoc, destinationLoc) {\n try {\n let resp = await fetch(`https://maps.googleapis.com/maps/api/directions/json?origin=${ startLoc }&destination=${ destinationLoc }&key=AIzaSyD8rFXA6KM_9OCzNcErc4d9Vsr1KeTPIxk`)\n let respJson = await resp.json();\n let points = Polyline.decode(respJson.routes[0].overview_polyline.points);\n let coords = points.map((point, index) => {\n return {\n latitude : point[0],\n longitude : point[1]\n }\n })\n await this.setState({coords: coords})\n return coords\n }\n catch(error) {\n alert(error)\n return error\n }\n }", "function dinamicRoutes() {\n var otherRoutes = routes.filter(function (item) { return item.path.includes(':'); });\n var getRouteCurrent = location.pathname.split('/');\n var request = {};\n otherRoutes.map(function (route) { return request = getRouteCurrent[1] == (route.path.split('/'))[1] ? { 'status': true, 'route': route } : { 'status': false }; });\n return request;\n}", "function dinamicRoutes() {\n var otherRoutes = routes.filter(function (item) { return item.path.includes(':'); });\n var getRouteCurrent = location.pathname.split('/');\n var request = {};\n otherRoutes.map(function (route) { return request = getRouteCurrent[1] == (route.path.split('/'))[1] ? { 'status': true, 'route': route } : { 'status': false }; });\n return request;\n}", "function goalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\tlet parcel = parcels[0];\n\tif (place == parcel.place) {\n\t\troute = findRoute(roadGraph, place, parcel.address);\n\t} else {\n\t\troute = findRoute(roadGraph, place, parcel.place);\n\t}\n\treturn [route[0], route.slice(1)];\n}", "getData () {\n let data = []\n // console.log(this.objects)\n for (let key in this.objects) {\n if (key === 'indexDBId') continue\n for(let key2 in this.objects[key]) {\n if (key2 === 'indexDBId') continue\n data.push(this.objects[key][key2])\n } \n }\n\n let ComponentParts = []\n // let routes = []\n let ComponentToParts = []\n let PartToPart = []\n let PartToPartNames = []\n for (let i = 0; i < data.length; i++) {\n ComponentParts.push(data[i].name, data[i].name2d)\n }\n for (let i = 0; i < this.nets.length; i++) {\n PartToPartNames.push(this.nets[i].name)\n PartToPart.push([])\n for (let j = 0; j < this.nets[i].pins.length; j++) {\n if (this.nets[i].pins[j][0] === -1) {\n ComponentToParts.push([])\n\n let local = null\n for (let k = 0; k < this.nets[i].pins.length; k++) {\n if (this.nets[i].pins[k][0] !== -1) {\n local = this.nets[i].pins[k]\n break\n }\n }\n if (local !== null) {\n ComponentToParts[ComponentToParts.length - 1].push(this.nets[i].pins[j][1], local[0], local[1])\n }\n }\n else {\n PartToPart[PartToPart.length - 1].push(this.nets[i].pins[j][0], this.nets[i].pins[j][1])\n }\n }\n\n if (PartToPart.length !== 0 && PartToPart[PartToPart.length - 1].length === 0) {\n PartToPart.splice(PartToPart.length - 1, 1)\n }\n\n if (ComponentToParts.length !== 0 && ComponentToParts[ComponentToParts.length - 1].length === 0) {\n ComponentToParts.splice(ComponentToParts.length - 1, 1)\n }\n }\n\n // console.log(PartToPart, PartToPartNames, ComponentToParts)\n // console.log(routes, this.completlyLoaded, data)\n\n if (this.completlyLoaded) {\n this.data.assets = data\n this.data.nets = this.nets\n this.electData.ComponentParts = ComponentParts\n this.electData.ComponentToParts = ComponentToParts\n this.electData.PartToPart = PartToPart\n this.electData.PartToPartNames = PartToPartNames\n }\n\n /*console.log(JSON.stringify({\n nets: this.data.nets,\n routing_data: this.data.routing_data,\n assets: this.data.assets,\n compSize: this.data.compSize,\n electData: this.electData\n }))*/\n return {\n nets: this.data.nets,\n routing_data: this.data.routing_data,\n assets: this.data.assets,\n compSize: this.data.compSize,\n electData: this.electData\n }\n }", "function process_road_route(road_route){\r\n\r\n var road_indices = [];\r\n\r\n for (var i=0; i<road_route.length; i++)\r\n {\r\n var point_array = [];\r\n // Get the numerical index value from the alphabetical input\r\n point_array.push(row_translate.indexOf(road_route[i][0]));\r\n // Game board starts at 1 - 30, grab Int version of input and\r\n // subtract 1 to start at 0.\r\n point_array.push(parseInt(road_route[i][1]) - 1);\r\n // Simnply add the 3rd road param which deterimes if a 90 degree pixel\r\n point_array.push(road_route[i][2]);\r\n // Add new road index onto return array\r\n road_indices.push(point_array);\r\n }\r\n return road_indices;\r\n}", "function genMap(arr) {\n \n var platform = new H.service.Platform({\n 'app_id': 'qsjcw6LHc3cHp6JS1KOz',\n 'app_code': '82KosHvdwFKePLOYSUC1xA',\n 'useHTTPS': true\n });\n \n var targetElement = document.getElementById('mapContainer');\n var defaultLayers = platform.createDefaultLayers();\n var distance = 0.0;\n\n\n var map = new H.Map(\n document.getElementById('mapContainer'),\n defaultLayers.normal.map,\n {}\n );\n \n var routingParameters = {\n 'mode': 'fastest;car',\n 'representation': 'display'\n };\n \n for(i = 0; i < arr.length; i++) {\n routingParameters[\"waypoint\" + i] = \"geo!\" + arr[i].lat + \",\" + arr[i].long;\n if(i != 0) {\n distance = distance + distanceCalc(arr[i-1].lat, arr[i-1].long, arr[i].lat, arr[i].long)\n }\n };\n \n distance = Math.round(distance * 10) / 10;\n document.getElementById('distance').innerHTML = distance;\n\n var onResult = function(result) {\n \n var route,\n routeShape,\n linestring;\n\n if(result.response.route) {\n \n route = result.response.route[0];\n routeShape = route.shape;\n linestring = new H.geo.LineString();\n\n \n routeShape.forEach(function(point) {\n var parts = point.split(',');\n linestring.pushLatLngAlt(parts[0], parts[1]);\n });\n\n \n var routeLine = new H.map.Polyline(linestring, {\n style: { strokeColor: '#000', lineWidth: 8 } // style of route line\n });\n \n // Create an icon object, an object with geographic coordinates and a marker:\n var icon = new H.map.Icon('./dot.png');\n startPoint = route.waypoint[0].mappedPosition;\n endPoint = route.waypoint[route.waypoint.length - 1].mappedPosition;\n\n var start = new H.map.Marker({\n lat: startPoint.latitude,\n lng: startPoint.longitude\n },{icon: icon});\n\n var end = new H.map.Marker({\n lat: endPoint.latitude,\n lng: endPoint.longitude\n },{icon: icon});\n \n map.addObjects([routeLine, start, end]);\n map.setViewBounds(routeLine.getBounds());\n }\n };\n\n var router = platform.getRoutingService();\n router.calculateRoute(routingParameters, onResult,\n function(error) {\n alert(error.message); // on error\n }\n );\n \n window.addEventListener('resize', function () {\n map.getViewPort().resize();\n \n });\n}", "getNeighbors(solution, neighborMap) {\n let solutionNeighborhood = []\n\n for(let i=1; i<solution.length-1; i++) {\n let n = solution[i]\n for(let j=1; j<solution.length-1; j++) {\n let kn = solution[j]\n\n if(JSON.stringify(n) == JSON.stringify(kn)) {\n continue;\n }\n\n let tempArray = Array.from(solution)\n tempArray[i] = kn \n tempArray[j] = n\n\n let distance = 0\n for(let k=0; k<tempArray.length-1; k++) {\n let nextNode = tempArray[k + 1]\n\n let mapIndex = 0\n neighborMap.get(tempArray[k]).forEach((value, key) => {\n if (JSON.stringify(key) == JSON.stringify(nextNode)) {\n distance = distance + value;\n } \n });\n }\n tempArray.push(distance);\n solutionNeighborhood.push(tempArray);\n\n }\n }\n\n // Remove duplicates\n solutionNeighborhood = Array.from(new Set(solutionNeighborhood.map(JSON.stringify)), JSON.parse)\n\n solutionNeighborhood = solutionNeighborhood.sort(function(a, b) {\n return a[a.length-1] > b[b.length-1] ? 1:-1;\n });\n \n return solutionNeighborhood;\n }", "function getneighbors(x,y) {\n let neighbors = [];\n //e\n neighbors.push((x + 1) + \",\" + y);\n //se\n neighbors.push((y%2 === 0 ? x + 1 : x) + \",\" + (y+1));\n //sw\n neighbors.push((y%2 !== 0 ? x - 1 : x) + \",\" + (y+1));\n //w\n neighbors.push((x - 1) + \",\" + y);\n //nw\n neighbors.push((y%2 !== 0 ? x - 1 : x) + \",\" + (y-1));\n //ne\n neighbors.push((y%2 === 0 ? x + 1 : x) + \",\" + (y-1));\n return neighbors;\n}", "function getPredictRouteLine() {//get predicted route line of a singleBus. Which is the core algorithm\n var routeLine = \n L.polyline([[40.68510, -73.94136], [40.68576, -73.94149], [40.68649, -73.94165], [40.68722, -73.94178], [40.68795, -73.94193], [40.68869, -73.94207], [40.68942, -73.94223], [40.69016, -73.94236], [40.69089, -73.94251], [40.69162, -73.94266], [40.69234, -73.94281], [40.69309, -73.94295], [40.69337, -73.94301], [40.69382, -73.94310], [40.69455, -73.94324], [40.69527, -73.94339], [40.69603, -73.94353], [40.69822, -73.94394], [40.69897, -73.94409], [40.69968, -73.94424], [40.70042, -73.94438], [40.70053, -73.94440], [40.70109, -73.94501], [40.70165, -73.94564], [40.70221, -73.94627], [40.70277, -73.94690], [40.70335, -73.94753], [40.70388, -73.94814], [40.70407, -73.94779], [40.70436, -73.94781], [40.70544, -73.94798], [40.70685, -73.94819], [40.70759, -73.94830], [40.70830, -73.94842], [40.70901, -73.94854], [40.70879, -73.95076], [40.70914, -73.95083], [40.70971, -73.95236], [40.71026, -73.95385], [40.71059, -73.95473], [40.71055, -73.95509], [40.71058, -73.95551], [40.71065, -73.95625], [40.71065, -73.95647], [40.71051, -73.95709], [40.71044, -73.95736], [40.71035, -73.95833], [40.71032, -73.95875], [40.71078, -73.95994], [40.71103, -73.96058], [40.71047, -73.96094], [40.71041, -73.96113], [40.71061, -73.96176], [40.71115, -73.96354], [40.71162, -73.96508], [40.71217, -73.96703], [40.71215, -73.96730], [40.71549, -73.97831], [40.71544, -73.97834], [40.71757, -73.98535], [40.71770, -73.98579], [40.71783, -73.98572], [40.71908, -73.98507], [40.71933, -73.98591], [40.71958, -73.98675], [40.71983, -73.98754], [40.72007, -73.98835], [40.72030, -73.98911], [40.72046, -73.98962], [40.72052, -73.98985], [40.72076, -73.99063], [40.72102, -73.99150], [40.72115, -73.99195], [40.72124, -73.99224], [40.72139, -73.99273], [40.72161, -73.99346], [40.72234, -73.99320], [40.72238, -73.99332], [40.72272, -73.99416], [40.72303, -73.99490], [40.72336, -73.99570], [40.72368, -73.99647], [40.72388, -73.99695], [40.72423, -73.99779], [40.72462, -73.99858], [40.72500, -73.99934], [40.72538, -74.00010], [40.72576, -74.00089], [40.72611, -74.00159], [40.72649, -74.00236], [40.72687, -74.00312], [40.72690, -74.00321], [40.72694, -74.00327], [40.72695, -74.00337], [40.72695, -74.00344], [40.72766, -74.00316], [40.72831, -74.00308], [40.72838, -74.00309], [40.72871, -74.00330], [40.72934, -74.00365], [40.72987, -74.00397], [40.73044, -74.00430], [40.73071, -74.00446], [40.73100, -74.00462], [40.73154, -74.00493], [40.73135, -74.00553], [40.73162, -74.00570], [40.73158, -74.00578], [40.73163, -74.00632]]);\n \n return routeLine;\n}", "function showRoutes(result) {\n \n routes = [];\n coords = [];\n let startCoords = [];\n let endCoords = [];\n for (let i = 0; i < result.length; i++) { \n let routeId = i;\n let route = new Route(routeId)\n route._airline = result[i].airline;\n route._equipment = result[i].equipment;\n \n \n for (let j = 0; j < airports.length; j++)\n {\n\n if (result[i].sourceAirportId == airports[j].airportId)\n {\n startCoords = [airports[j].longitude, airports[j].latitude];\n startAirport = airports[j];\n route._start = startAirport;\n }\n if (result[i].destinationAirportId == airports[j].airportId)\n {\n endCoords = [airports[j].longitude, airports[j].latitude];\n endAirport = airports[j];\n route._end = endAirport;\n routeDetails = result[i];\n let marker = new mapboxgl.Marker({ \"color\": \"rgb(255,193,7)\" })\n markers.push(marker);\n let latitude = airports[j].latitude;;\n let longitude = airports[j].longitude;;\n let coordinates = [longitude, latitude];\n marker.setLngLat(coordinates);\n marker.addTo(map);\n let description = `<h3>Airport: ${airports[j].name}<br></h3>\n <h3>City: ${airports[j].city} <h3>`;\n let popup = new mapboxgl.Popup({offset: 45});\n popup.setHTML(description);\n marker.setPopup(popup);\n\n routes.push(route)\n \n } \n }\n \n //condition to check if it's international or domestic\n if (startCoords.length != 0 && endCoords.length != 0) {\n coords.push(startCoords)\n coords.push(endCoords);\n }\n }\n \n removeLayerWithId(\"routes\")\n showPath()\n let routeList = document.getElementById(\"routes\");\n let routeOutput = `<option value=\"0\"></option>`;\n for (let k = 0; k < routes.length; k++) {\n routeOutput += `<option value=\"${k}\">${routes[k].airline}, ${routes[k]._end.name}</option>`\n }\n routeList.innerHTML = routeOutput; \n}", "GetRouteStatusByGPSid(GPSid) {\n //1, determine RouteID by GPSid\n // \n //2, Read Whole Route info from DB\n //\n //3, do comparison and put into a JSON\n let routeData = this.GetRouteData(GPSid);\n let currentLegStatus = this.GetLegStatusByGPSid(GPSid);\n let status = {};\n //\n }", "async function getRouteDist(start, end, vid, partofroute){\n var url = 'https://api.mapbox.com/directions/v5/mapbox/driving-traffic/' + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;\n let result = await makeRequest('GET', url);\n var json = JSON.parse(result);\n var data = json.routes[0];\n if (partofroute == 'driven'){\n trucks[vid].distanceDriven = data.distance;\n }\n else{\n trucks[vid].distanceLeft = data.distance;\n }\n var route = data.geometry.coordinates;\n return route;\n}", "function trip(src, dst, network) {\n let ls = []\n ls.push(src.geometry.coordinates)\n const ps = geojson.findClosest(src, network)\n const pe = geojson.findClosest(dst, network)\n let trip = geojson.route(ps, pe, airport.serviceroads)\n trip.coordinates.forEach(function(p, idx) {\n ls.push(p)\n })\n ls.push(dst.geometry.coordinates)\n return geojson.Feature(geojson.LineString(ls))\n}", "function evenEvenBetterGoalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\n\tlet routes = [];\n\tfor (let parcel of parcels){\n\t\tif (place == parcel.place) {\n\t\t\troutes.push({type: 'delivery', route: findRoute(roadGraph, place, parcel.address)});\n\t\t} else {\n\t\t\troutes.push({type: 'pickup', route: findRoute(roadGraph, place, parcel.place)});\n\t\t}\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => {\n\t\tif (r1.route.length < r2.route.length) {\n\t\t\treturn r1;\n\t\t} else if (r1.route.length == r2.route.length) {\n\t\t\treturn r1.type == 'pickup' ? r1 : r2;\n\t\t} else {\n\t\t\treturn r2;\n\t\t}\n\t}).route;\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "function goalOrientedRobot({place, parcels}, route = []) {\n if (route.length == 0) {\n let parcel = parcels[0];\n if (parcel.place != place) {\n route = findRoute(roadGraph, place, parcel.place);\n } else {\n route = findRoute(roadGraph, place, parcel.address);\n }\n }\n return {direction: route[0], memory: route.slice(1)}\n }", "getPointsOfRoute(points, version, options, url_, version_, srsOrigin, timeOut_, cb) {\n let pointsTransform = [];\n // for (var i = 0; i < points.length; i = i +1) {\n // let pointAux = points[i];\n // let pointTransform = new ol.geom.Point(ol.proj.transform([pointAux[0], pointAux[1]], srsOrigin, 'EPSG:4326'));\n // pointsTransform.push(pointTransform);\n // }\n points.forEach(p => {\n let pointAux = p;\n let pointTransform = new ol.geom.Point(ol.proj.transform([pointAux[0], pointAux[1]], srsOrigin, 'EPSG:4326'));\n pointsTransform.push(pointTransform);\n });\n\n let waypoints4326 = [];\n\n // for (let j = 0; j < pointsTransform.length; j = j +1) {\n // let pointsTransformAux = pointsTransform[j];\n // let aux = {\n // \t\t\tx : pointsTransformAux.getCoordinates()[1],\n // \t\t\ty : pointsTransformAux.getCoordinates()[0]\n // \t\t};\n // waypoints4326.push(aux);\n // }\n pointsTransform.forEach(pt => {\n let pointsTransformAux = pt;\n let x = pointsTransformAux.getCoordinates()[1],\n y = pointsTransformAux.getCoordinates()[0];\n let aux = {\n x,\n y\n };\n waypoints4326.push(aux);\n });\n\n const url = this.buildRouteURL(waypoints4326, version, version_, options, url_);\n\n let promesa = M.remote.get(url);\n const timeout = timeOut_;\n this.timeOut = setTimeout(function() { M.dialog.error(\"No se ha podido calcular la ruta en este momento, por favor, intentelo mas tarde.\", \"Error\"); }, timeout);\n let decodeResponseBind = this.decodeResponse.bind(this);\n promesa.then(function(data) {\n clearTimeout(this.timeOut);\n const jsonResponse = JSON.parse(data.text);\n if (data.code != 200) {\n // M.dialog.error(\"error realizando la petición entre dos puntos: \" + url, \"Error\");\n M.dialog.error(`error realizando la petición entre dos puntos: ${url}`, \"Error\");\n } else {\n let routeEncode = jsonResponse.routes;\n if (routeEncode && routeEncode.length === 0) {\n // M.dialog.error(\"No se han encontrado ruta entre los dos puntos\" + url, \"Error\")\n M.dialog.error(`error realizando la petición entre dos puntos: ${url}`, \"Error\");\n } else {\n let route = decodeResponseBind(\n routeEncode[0].geometry, 5, srsOrigin);\n if (!route || (typeof route === 'object' && route.length && route.length === 0)) {\n M.dialog.error(\"No se ha podido calcular la ruta en este momento, por favor, intentelo mas tarde.\", \"Error\");\n } else if (route && route.length && route.length > 0) {\n jsonResponse[\"routeDecodified\"] = route;\n cb.call(this, jsonResponse);\n return false;\n }\n }\n }\n cb.call(this, []);\n }.bind(this));\n\n promesa.catch((error) => {\n clearTimeout(this.timeOut);\n // M.dialog.error(\"error realizando la petición entre dos puntos\" + url, \"Error\");\n M.dialog.error(`error realizando la petición entre dos puntos ${url}`, \"Error\");\n });\n\n }", "function getRoute(end) {\n var url = `https://api.mapbox.com/directions/v5/mapbox/${prevoz}/` + start[0] + ',' + start[1] + ';' + end[0] + ',' + end[1] + '?steps=true&geometries=geojson&access_token=' + mapboxgl.accessToken;\n var req = new XMLHttpRequest();\n req.open('GET', url, true);\n req.onload = function () {\n var json = JSON.parse(req.response);\n var data = json.routes[0];\n var route = data.geometry.coordinates;\n var geojson = {\n type: 'Feature',\n properties: {},\n geometry: {\n type: 'LineString',\n coordinates: route\n }\n };\n if (map.getSource('route')) {\n map.getSource('route').setData(geojson);\n } else {\n map.addLayer({\n id: 'route',\n type: 'line',\n source: {\n type: 'geojson',\n data: {\n type: 'Feature',\n properties: {},\n geometry: {\n type: 'LineString',\n coordinates: geojson\n }\n }\n },\n layout: {\n 'line-join': 'round',\n 'line-cap': 'round'\n },\n paint: {\n 'line-color': '#3887be',\n 'line-width': 5,\n 'line-opacity': 0.75\n }\n });\n }\n var instructions = document.getElementById('instructions');\n var steps = data.legs[0].steps;\n\n var tripInstructions = [];\n for (var i = 0; i < steps.length; i++) {\n tripInstructions.push('<br><li>' + steps[i].maneuver.instruction) + '</li>';\n instructions.innerHTML = '<br><span class=\"duration\">Trip duration: ' + Math.floor(data.duration / 60) + ' min 🚴 </span>' + tripInstructions;\n }\n\n };\n req.send();\n }", "function evenBetterGoalOrientedRobot({place, parcels}, route){\n\tif (route.length > 0) return [route[0], route.slice(1)];\n\n\tlet routes = [];\n\tfor (let parcel of parcels){\n\t\tif (place == parcel.place) {\n\t\t\troutes.push(findRoute(roadGraph, place, parcel.address));\n\t\t} else {\n\t\t\troutes.push(findRoute(roadGraph, place, parcel.place));\n\t\t}\n\t}\n\n\tlet shortestRoute = routes.reduce((r1, r2) => r1.length > r2.length ? r2 : r1);\n\treturn [shortestRoute[0], shortestRoute.slice(1)];\n}", "function getNeighboringItems(area) {\n for (let key in areas) {\n for (let key2 in area.neighbors) {\n if (areas[key].ID === area.neighbors[key2]) return areas[key]\n }\n }\n}", "function getRelevantNeighbors(tile) {\n var neighborIndexX = tile.indexX > originXIndex ? tile.indexX - 1 : tile.indexX + 1,\n neighborIndexY = tile.indexY > originYIndex ? tile.indexY - 1 : tile.indexY + 1;\n\n/* if(tile.indexX === originXIndex) neighborIndexX = null;\n if(tile.indexY === originYIndex) neighborIndexY = null;*/\n\n var neighbors = {\n diagonal: {},\n vertical: {},\n horizontal: {}\n };\n\n for(var j=0; j<tiles.length; j++) {\n var current = tiles[j];\n if(current.indexX === neighborIndexX && current.indexY === tile.indexY)\n neighbors.horizontal = current;\n if(current.indexY === neighborIndexY && current.indexX === tile.indexX)\n neighbors.vertical = current;\n if(current.indexX === neighborIndexX && current.indexY === neighborIndexY)\n neighbors.diagonal = current;\n }\n\n return neighbors;\n}", "function getRoute(routenum) { \n clearOverlays();\n $(document).ready(function() {\n\tvar lat;var lon;var name;var abbr;\n\tif(routenum=='') { return false; }\n\t$.getJSON('getroute.php',{route:routenum},function(data) {\n $.each(data,function(key,value) {\n\t\tif(key=='route') { \n\t\t $.each(this,function(k,v) {\n\t\t\tif(k=='name'){Rt=v;}\n\t\t\tif(k=='color'){Clr=v;}\n\t\t }); \n\t\t}\n\t\tif(key=='station') { \n\t\t $.each(this,function(k,v) {\n\t\t\tabbr=k;\n//\t\t\tconsole.log(\"Key:- \"+abbr);\n\t\t\t$.each(this,function(k2,v2) {\n\t\t\t if(k2=='name'){ name=v2; }\n\t\t\t if(k2=='slat'){ lat=v2; }\n\t\t\t if(k2=='slong'){ lon=v2; }\n\t\t\t});\n\t\t\tdraw(lat,lon,abbr,name);\n//\t\t\tconsole.log(\"Lat:- \"+lat+\", Lon:- \"+lon+\", Name:- \"+name);\n\t\t });\n\t\t}\n }); //$.each\n// console.log(\"Route Name: \"+Rt+\" ,Route Color: \"+Clr);\n\t}); //$.getJSON()\n });//$(document)\n}", "function findNeighboring (thing, i , j) {\n var coords = {};\n\n if (A.world[i-1]) {\n // the row above exists....\n if (A.world[i-1][j-1] && A.world[i-1][j-1] === thing) { coords.row = i - 1; coords.col = j - 1; };\n if (A.world[i-1][j] === thing) { coords.row = i - 1; coords.col = j; };\n if (A.world[i-1][j+1] && A.world[i-1][j+1] === thing) { coords.row = i - 1; coords.col = j + 1; };\n }\n if (A.world[i][j-1] && A.world[i][j-1] === thing) { coords.row = i; coords.col = j - 1; }; // the 'current' row\n if (A.world[i][j+1] && A.world[i][j+1] === thing) { coords.row = i; coords.col = j + 1; };\n if (A.world[i+1]) {\n // the row below exists...\n if (A.world[i+1][j-1] && A.world[i+1][j-1] === thing) { coords.row = i + 1; coords.col = j - 1; };\n if (A.world[i+1][j] === thing) { coords.row = i + 1; coords.col = j; };\n if (A.world[i+1][j+1] && A.world[i+1][j+1] === thing) { coords.row = i + 1; coords.col = j + 1; };\n }\n return coords;\n}", "function calcRoutee(){\r\n\t\t\r\n\t\tvar half= document.getElementById(\"half\").value;\r\n\t\tvar end = document.getElementById(\"end\").value;\r\n\t\tvar request = { origin: half, destination: end,\r\n\t\t\ttravelMode: google.maps.DirectionsTravelMode.DRIVING\r\n\t\t};\r\n\t\tdirectionsService.route(request, function(directionsResults, status){\r\n\t\t\tif(status==google.maps.DirectionsStatus.OK){\r\n\t\t\t\thandleDirectionsResponse1(\r\n\t\t\t\t\t\t half,end, directionsResults);\r\n\t\t\t}\r\n\t\t});\r\n\t\t\r\n\t }", "requestOptimalRouteByMatrix(waypoints) {\n const dest = waypoints.slice(1);\n waypoints.pop();\n let wayPointChuncks = [];\n let distlen = 1;\n let j = 0;\n let c = 0;\n let chunk = {\n origins: [],\n destinations: [],\n travelMode: google.maps.TravelMode.DRIVING\n };\n for (let i = 1; i < waypoints.length; i++, j++) {\n // @ts-ignore\n chunk.origins.push(waypoints[j]);\n // @ts-ignore\n chunk.destinations.push(waypoints[i]);\n c++;\n if (c >= distlen) {\n wayPointChuncks.push(chunk);\n chunk = {\n origins: [],\n destinations: [],\n travelMode: google.maps.TravelMode.DRIVING\n };\n c = 0;\n }\n }\n if (chunk.origins.length > 0) {\n wayPointChuncks.push(chunk);\n }\n let reqD = {\n req: this.distService.matInstance.getDistanceMatrix,\n statuses: google.maps.DistanceMatrixStatus,\n calcDistance: function (response) {\n let distance = 0;\n for (const r of response.rows) {\n let elems = r.elements;\n for (const elem of elems) {\n if (elem.status === 'OK') {\n distance += elem.distance.value;\n }\n else {\n return null;\n }\n }\n }\n return distance;\n }\n };\n this.processWayPointChunks(wayPointChuncks, reqD);\n }", "function neighboring(a, b) {\n //From https://stackoverflow.com/questions/8739072\n return edge_by_id[a.id + ',' + b.id] || edge_by_id[b.id + ',' + a.id];\n } //function neighboring", "function neighboring(a, b) {\n //From https://stackoverflow.com/questions/8739072\n return edge_by_id[a.id + ',' + b.id] || edge_by_id[b.id + ',' + a.id];\n } //function neighboring", "packageRoutes(nodes) {\n var map = {};\n var routes = [];\n\n // Compute a map from name to node.\n nodes.forEach(function(d) {\n map[d.data.name] = d;\n });\n\n // For each route, construct a link from the source to target node.\n nodes.forEach(function(d) {\n if (d.data.routes) d.data.routes.forEach(function(i) {\n routes.push(map[d.data.name].path(map[i]));\n });\n });\n return routes;\n }", "function calcRoute() {\n //Hardcoded the Goodwill HQ as the start and end location for all routes\n var start = \"1580 Mission Street, San Francisco, CA 94103\";\n var end = start;//\"20 Descanso Dr, San Jose CA 95134\";//start;\n\n var items = $('#routes .item');\n var wayPoints = items.map(function (idx, item) {\n var data = $(item).data('originData').address;\n $(item).data('marker').setMap(null);\n\n return {\n location: data.address + \" \"/* + data.addr2 */+ \" , \" + data.city + \" , \" + data.zip,\n stopover: true\n }\n\n\n });\n\n var optimize = $(\"#optimize\").is(\":checked\");\n\n var request = {\n origin: start,\n destination: end,\n waypoints: wayPoints,\n optimizeWaypoints: optimize,\n travelMode: google.maps.TravelMode.DRIVING\n };\n\n //\n directionsService.route(request, function (result, status) {\n if (status == google.maps.DirectionsStatus.OK) {\n\n //Render the solution on the map\n directionsDisplay.setDirections(result);\n\n //Tally up the total time / distance for this route\n var totals = computeTotalDistance(result);\n $(\"#routeSpecs\").text(\" \" + wayPoints.length + \" stops, \" + totals.distance + \" miles, \" + totals.time + \" hours\");\n\n //Rejjiger the list if set to optimize route\n if (optimize) {\n var optimizedWaypoints = result.routes[0].waypoint_order;\n var oldItems = $(\"#routes li\");\n var newRoute = [];\n for (var i in optimizedWaypoints) {\n newRoute.push(oldItems[optimizedWaypoints[i]]);\n }\n $(\"#routes\").append(newRoute);\n }\n }\n });\n}", "function mergeNeighboor(neighbours, locals) {\n\t\t//merge locals into neighbours\n\n\t\tvar out = neighbours.slice(); //out is a copy\n\t\tvar ids = out.map(function (n) { \n\t\t\tn.isLocalOnly = true; //in order to not be removed by storage.merge\n\t\t\treturn n.id; //for ids list\n\t\t});\n\n\t\tlocals.forEach(function (l) {\n\t\t\tvar idx;\n\n\t\t\tidx = ids.indexOf(l.id);\n\t\t\tif (idx !== -1) //it exists in neighbour, erase with local version\n\t\t\t\tout[idx] = l;\n\t\t\telse\n\t\t\t\tout.push(l); //because we push at the end, it doesn't infere with ids[];\n\t\t});\n\t\treturn out;\n\t}", "function goalOrientedRobot({ place, parcels }, route) {\n if (route.length == 0) {\n let parcel = parcels[0];\n if (parcel.place != place) {\n route = findRoute(roadGraph, place, parcel.place);\n } else {\n route = findRoute(roadGraph, place, parcel.address);\n }\n }\n return { direction: route[0], memory: route.slice(1) };\n}" ]
[ "0.6435899", "0.63308686", "0.61995417", "0.61898124", "0.6103493", "0.60339445", "0.59863466", "0.5973437", "0.5973437", "0.59344316", "0.58836067", "0.58820087", "0.58784443", "0.5858686", "0.58528525", "0.58197165", "0.5819709", "0.57978207", "0.579557", "0.5728887", "0.57273924", "0.57238114", "0.5713489", "0.57044053", "0.56955785", "0.5687192", "0.5676115", "0.5667193", "0.5666759", "0.56453216", "0.5644377", "0.56405324", "0.5627503", "0.5627056", "0.56169647", "0.5601842", "0.5601842", "0.55951476", "0.559016", "0.5589907", "0.55857784", "0.5585724", "0.5579438", "0.55775034", "0.55620694", "0.55558515", "0.55537444", "0.5546483", "0.554611", "0.5545398", "0.5535069", "0.5513661", "0.55091476", "0.5504958", "0.5488847", "0.54841924", "0.54806066", "0.5478432", "0.54775923", "0.5474244", "0.54673207", "0.54658616", "0.5455353", "0.5453497", "0.5432244", "0.543223", "0.54316825", "0.54301876", "0.5427177", "0.54157454", "0.5406505", "0.5406505", "0.5401887", "0.54017144", "0.53925604", "0.53907776", "0.53866315", "0.53856003", "0.5382602", "0.5378272", "0.5377561", "0.5376239", "0.5370205", "0.5370179", "0.53695846", "0.5368739", "0.5365241", "0.5364126", "0.53576094", "0.5357197", "0.53558415", "0.53556824", "0.5348267", "0.5346843", "0.53458834", "0.53458834", "0.5344995", "0.533217", "0.53314644", "0.53295994" ]
0.64997625
0
return related neighbors to one particular neighbor
function getRelatedNeighbors(NeighborName) { var result = relatedPairs[NeighborName]; if (result != null) { return result; } else{ window.alert("wrong name"); } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "neighbors (row, column) {\n let leftColumn = column - 1\n let rightColumn = column + 1\n let upRow = row - 1\n let downRow = row + 1\n \n // Wrap around edges\n if (leftColumn < 1) leftColumn = this.cols\n if (rightColumn > this.cols) rightColumn = 1\n if (upRow < 1) upRow = this.rows\n if (downRow > this.rows) downRow = 1\n \n // neighbors\n return [\n this.cell(upRow, leftColumn),\n this.cell(upRow, column),\n this.cell(upRow, rightColumn),\n this.cell(row, leftColumn),\n this.cell(row, rightColumn),\n this.cell(downRow, leftColumn),\n this.cell(downRow, column),\n this.cell(downRow, rightColumn)\n ]\n }", "getNeighbors(){\n\n var offSetDir = [\n [[-1,-1], [-1, 0], [0,1], [1, 0], [1,-1], [0, -1]],\n [[-1, 0], [-1, 1], [0,1], [1,1], [1, 0], [0, -1]]\n ]\n var parity = this.index.row % 2;\n var neighbors = []\n for(var i = 0; i<6; i++){\n var assocNeighbor = {row: this.index.row + offSetDir[parity][i][0], col: this.index.col + offSetDir[parity][i][1]}\n if(assocNeighbor.row>=0 && assocNeighbor.row < this.board.numRows){\n if(assocNeighbor.col>=0 && assocNeighbor.col< this.board.numColumns){\n if(this.board.getHex(assocNeighbor.row, assocNeighbor.col)!=undefined && this.board.getHex(assocNeighbor.row, assocNeighbor.col).identifier.name== this.identifier.name){\n neighbors.push(this.board.getHex(assocNeighbor.row, assocNeighbor.col));\n\n }\n }\n }\n }\n return neighbors;\n }", "fetchNeighborhoods() {\n return this._getIndexRange('neighborhood');\n }", "getNeighbors(node) {\n const neighbors = [];\n Object.values(node.walls).forEach((side) => {\n if (side instanceof Cell) {\n neighbors.push(side);\n }\n })\n return neighbors; \n }", "function getNeighboringItems(area) {\n for (let key in areas) {\n for (let key2 in area.neighbors) {\n if (areas[key].ID === area.neighbors[key2]) return areas[key]\n }\n }\n}", "getNeighbors(node){\n if(!this.nodes[node]){ return null;} \n else{\n return this.nodes[node].connections; \n }\n }", "function getNeighborhood(node){\n\n // Look for an existing neighborhood\n for (neighborhood of village){\n if (neighborhood.has(node)){\n return neighborhood\n }\n }\n\n // Didn't find a neighorhood, so make a new one\n var neighborhood = new Set()\n neighborhood.add(node)\n village.add(neighborhood)\n return neighborhood\n }", "function neighboring(a, b) {\n //From https://stackoverflow.com/questions/8739072\n return edge_by_id[a.id + ',' + b.id] || edge_by_id[b.id + ',' + a.id];\n } //function neighboring", "function neighboring(a, b) {\n //From https://stackoverflow.com/questions/8739072\n return edge_by_id[a.id + ',' + b.id] || edge_by_id[b.id + ',' + a.id];\n } //function neighboring", "neighborhood() {\n return store.neighborhoods.find(\n function(neighborhood) {\n return neighborhood.id === this.neighborhoodId\n }.bind(this)\n )\n }", "neighbours(){\n var neighbours = []\n neighbours.push(this.neighbour(0,1))\n //neighbours.push(this.neighbour(1,1))\n neighbours.push(this.neighbour(1,0))\n //neighbours.push(this.neighbour(1,-1))\n neighbours.push(this.neighbour(0,-1))\n //neighbours.push(this.neighbour(-1,-1))\n neighbours.push(this.neighbour(-1,0))\n //neighbours.push(this.neighbour(-1,1))\n return neighbours\n }", "function getNeighbors( i, j )\n{\n var neighbors = [];\n //top, bottom, left, right\n var limit = 4;\n //top, bottom, left, right, top-left, top-right, bottom-left, bottom-right\n if( diagnolSelected )\n limit=8;\n \n for( var k = 0; k < limit; k++ )\n {\n var newRow = i + dirX[k];\n var newCol = j + dirY[k];\n //If neighbour exists, add it into the neighbours list\n if( newRow >= 0 && newRow < totalRows && newCol >= 0 && newCol < totalCols)\n neighbors.push( [newRow, newCol] );\n }\n \n return neighbors;\n}", "function getNeighbor(cell_jdom){\n\t var position = cell_jdom.attr('id').substring(1,cell_jdom.attr('id').length).split('_');\n\t//position[0] and position[1] are the matrix location of the element\n\t var row_id = parseInt(position[0]);\n \t var col_id = parseInt(position[1]); \n \t\n \t var up_id = \"b\" + (row_id-1) +\"_\" + col_id;\n \t var down_id = \"b\" + (row_id+1) +\"_\" + col_id;\n \t var left_id = \"b\" + row_id +\"_\" + (col_id-1);\n\t var right_id = \"b\" + row_id +\"_\" + (col_id+1);\n\n\t var neighbor_id = [];\n\t //verify if all the neighbor exists;\n\t if( document.getElementById(up_id)){neighbor_id.push(up_id)}\n\t if( document.getElementById(down_id)){neighbor_id.push(down_id)}\n\t if( document.getElementById(left_id)){neighbor_id.push(left_id)}\n\t if( document.getElementById(right_id)){neighbor_id.push(right_id)}\n\t return neighbor_id;\n}", "function neighboring(a, b) {\n\t\t\t\t return linkedByIndex[a + \",\" + b];\n\t\t\t\t}", "findNeighbors(cell, filterVisited = false) {\n let neighbors = [];\n for (let i = 0; i < 4; i++) {\n switch (i) {\n case TOP : {\n let neighbor = this.cells[this.index(cell.x + 0, cell.y - 1)];\n if (neighbor && (!filterVisited || (filterVisited && !neighbor.visited))) neighbors.push(neighbor);\n break;\n }\n case RIGHT : {\n let neighbor = this.cells[this.index(cell.x + 1, cell.y + 0)];\n if (neighbor && (!filterVisited || (filterVisited && !neighbor.visited))) neighbors.push(neighbor);\n break;\n }\n case BOTTOM : {\n let neighbor = this.cells[this.index(cell.x + 0, cell.y + 1)];\n if (neighbor && (!filterVisited || (filterVisited && !neighbor.visited))) neighbors.push(neighbor);\n break;\n }\n case LEFT : {\n let neighbor = this.cells[this.index(cell.x - 1, cell.y + 0)];\n if (neighbor && (!filterVisited || (filterVisited && !neighbor.visited))) neighbors.push(neighbor);\n break;\n }\n }\n }\n return neighbors;\n }", "getNeig()\n {\n return this.neighbours;\n }", "function getneighbors(x,y) {\n let neighbors = [];\n //e\n neighbors.push((x + 1) + \",\" + y);\n //se\n neighbors.push((y%2 === 0 ? x + 1 : x) + \",\" + (y+1));\n //sw\n neighbors.push((y%2 !== 0 ? x - 1 : x) + \",\" + (y+1));\n //w\n neighbors.push((x - 1) + \",\" + y);\n //nw\n neighbors.push((y%2 !== 0 ? x - 1 : x) + \",\" + (y-1));\n //ne\n neighbors.push((y%2 === 0 ? x + 1 : x) + \",\" + (y-1));\n return neighbors;\n}", "hunt(cells) {\n if (cells.length > 0) {\n for (let i = 0; i < cells.length; i++) {\n let cell = cells[i];\n if (!cell.visited) {\n let neighbors = this.findNeighbors(cell);\n for (let j = 0; j < neighbors.length; j++) {\n let neighbor = neighbors[j];\n if (neighbor.visited) return { cell: cell, neighbor: neighbor };\n }\n }\n }\n } else {\n return null;\n }\n }", "findAllNeighbors() {\r\n for (let i = 0; i < this.items.length; i++) {\r\n const row = this.items[i];\r\n for (let j = 0; j < row.length; j++) {\r\n const item = this.items[i][j];\r\n item.neighbors = [];\r\n item.findNeighbors(this);\r\n item.checkShouldChangeColor();\r\n // console.log(item.neighbors);\r\n // console.log('----------------------------');\r\n }\r\n }\r\n }", "findNeighbors(i, j) {\n this.Neighbors.enumerate().forEach(neighbor => {\n let yOffset;\n let xOffset;\n let piece = this.pieces[i][j];\n let point = new Point(piece.point.x + this.Neighbors[neighbor].x, piece.point.y + this.Neighbors[neighbor].y);\n let check = this.hashmap.getPointFromMap(point, this.pieces);\n if (check !== null) {\n this.pieces[i][j].neighbors.push(\n () => this.hashmap.getPointFromMap(point, this.pieces)\n //check\n );\n }\n });\n }", "getNeighbors(i, j, rows, cols) {\n let neighbors = [];\n if (i > 1) { \n neighbors.push([i - 1, j]); \n }\n if (i < rows - 1) { \n neighbors.push([i + 1, j]); \n }\n if (j > 1){ \n neighbors.push([i, j - 1]); \n }\n if (j < cols - 1) { \n neighbors.push([i, j + 1]); \n }\n return neighbors;\n }", "getNeighborhood (elements, n) {\n\t\tif (n == 1) {\n\t\t\treturn elements;\n\t\t} else {\n\t\t\treturn this.getNeighborhood(elements.union(elements.neighborhood()), n-1);\n\t\t}\n\t}", "function neighboring(a, b) {\n return linkedByIndex[a + ',' + b];\n }", "function getNeighbors(i, j){\n\tvar neighbors = [];\n\tif ( i > 0 ){ neighbors.push( [i - 1, j] );}\n\tif ( j > 0 ){ neighbors.push( [i, j - 1] );}\n\tif ( i < (totalRows - 1) ){ neighbors.push( [i + 1, j] );}\n\tif ( j < (totalCols - 1) ){ neighbors.push( [i, j + 1] );}\n\treturn neighbors;\n}", "function getNeighbors(i, j){\n\tvar neighbors = [];\n\tif ( i > 0 ){ neighbors.push( [i - 1, j] );}\n\tif ( j > 0 ){ neighbors.push( [i, j - 1] );}\n\tif ( i < (totalRows - 1) ){ neighbors.push( [i + 1, j] );}\n\tif ( j < (totalCols - 1) ){ neighbors.push( [i, j + 1] );}\n\treturn neighbors;\n}", "getNeighbors(solution, neighborMap) {\n let solutionNeighborhood = []\n\n for(let i=1; i<solution.length-1; i++) {\n let n = solution[i]\n for(let j=1; j<solution.length-1; j++) {\n let kn = solution[j]\n\n if(JSON.stringify(n) == JSON.stringify(kn)) {\n continue;\n }\n\n let tempArray = Array.from(solution)\n tempArray[i] = kn \n tempArray[j] = n\n\n let distance = 0\n for(let k=0; k<tempArray.length-1; k++) {\n let nextNode = tempArray[k + 1]\n\n let mapIndex = 0\n neighborMap.get(tempArray[k]).forEach((value, key) => {\n if (JSON.stringify(key) == JSON.stringify(nextNode)) {\n distance = distance + value;\n } \n });\n }\n tempArray.push(distance);\n solutionNeighborhood.push(tempArray);\n\n }\n }\n\n // Remove duplicates\n solutionNeighborhood = Array.from(new Set(solutionNeighborhood.map(JSON.stringify)), JSON.parse)\n\n solutionNeighborhood = solutionNeighborhood.sort(function(a, b) {\n return a[a.length-1] > b[b.length-1] ? 1:-1;\n });\n \n return solutionNeighborhood;\n }", "function neighboring(a, b) {\n\t\t\t return linkedByIndex[a.index + \",\" + b.index];\n\t\t\t }", "function getAllNodesNeighborhood(){\n\t\tglobalData.nodes.map(function(node){\n\t\t\tnode.neighbors = getNeighborhoodLabels(node.index)\n\t\t\tneighborhoodLengths.push(node.neighbors.length)\n\t\t\td3.select('#' + node.label)\n\t\t\t\t.attr('neighborhood', node.neighbors.toString())\n\t\t})\n\t}", "getNeighbors() {\n const neighbors = new Array();\n for (const direction of TILE_DIRECTIONS) {\n const neighbor = this.getNeighbor(direction);\n if (neighbor) {\n neighbors.push(neighbor);\n }\n }\n return neighbors;\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n\t return linkedByIndex[a.index + ',' + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function getNeighbors() {\n\tvar neighbors = [];\n\tfor (var i = 0; i < squares.length; i++) {\n\t\tif (squares[i].canMove()) neighbors.push(squares[i]);\n\t}\n\treturn neighbors;\n}", "function neighbors(x) {\n var n = [\n {i: x.i - 1, j: x.j - 1}, // upleft\n {i: x.i - 1, j: x.j}, // upmiddle\n {i: x.i - 1, j: x.j + 1}, // upright\n {i: x.i, j: x.j - 1}, // left\n {i: x.i, j: x.j + 1}, // right\n {i: x.i + 1, j: x.j - 1}, // downleft\n {i: x.i + 1, j: x.j}, // downmiddle\n {i: x.i + 1, j: x.j + 1} // downright\n ];\n\n return n.filter(function (e){\n return isInGrid(e);\n });\n }", "getNeighbors(agents,dist) {\n var neighbors = agents.filter(a => {\n let distance = getDistance(this.pos.x,a.pos.x,this.pos.y,a.pos.y);\n return a.elementID != this.elementID && distance < dist;\n });\n return neighbors;\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + ',' + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n}", "FindNeighbours()\n {\n var AllPlayers = ListMembers.GetAllMembers();\n\n for (var curPlyr = 0; curPlyr != AllPlayers.length; curPlyr++)\n {\n //first clear any current tag\n AllPlayers[curPlyr].Steering().UnTag();\n\n //work in distance squared to avoid sqrts\n var to = new Phaser.Point(AllPlayers[curPlyr].Pos().x - this.m_pPlayer.Pos().x,\n AllPlayers[curPlyr].Pos().y - this.m_pPlayer.Pos().y);\n\n if (to.getMagnitudeSq() < (this.m_dViewDistance * this.m_dViewDistance))\n {\n AllPlayers[curPlyr].Steering().Tag();\n }\n }//next\n }", "FindNeighbours()\n {\n var AllPlayers = ListMembers.GetAllMembers();\n\n for (var curPlyr = 0; curPlyr != AllPlayers.length; curPlyr++)\n {\n //first clear any current tag\n AllPlayers[curPlyr].Steering().UnTag();\n\n //work in distance squared to avoid sqrts\n var to = new Phaser.Point(AllPlayers[curPlyr].Pos().x - this.m_pPlayer.Pos().x,\n AllPlayers[curPlyr].Pos().y - this.m_pPlayer.Pos().y);\n\n if (to.getMagnitudeSq() < (this.m_dViewDistance * this.m_dViewDistance))\n {\n AllPlayers[curPlyr].Steering().Tag();\n }\n }//next\n }", "neighborhood(){\n return store.neighborhoods.find(neighborhood => neighborhood.id === this.neighborhoodId);\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + ',' + b.index];\n}", "function getRelevantNeighbors(tile) {\n var neighborIndexX = tile.indexX > originXIndex ? tile.indexX - 1 : tile.indexX + 1,\n neighborIndexY = tile.indexY > originYIndex ? tile.indexY - 1 : tile.indexY + 1;\n\n/* if(tile.indexX === originXIndex) neighborIndexX = null;\n if(tile.indexY === originYIndex) neighborIndexY = null;*/\n\n var neighbors = {\n diagonal: {},\n vertical: {},\n horizontal: {}\n };\n\n for(var j=0; j<tiles.length; j++) {\n var current = tiles[j];\n if(current.indexX === neighborIndexX && current.indexY === tile.indexY)\n neighbors.horizontal = current;\n if(current.indexY === neighborIndexY && current.indexX === tile.indexX)\n neighbors.vertical = current;\n if(current.indexX === neighborIndexX && current.indexY === neighborIndexY)\n neighbors.diagonal = current;\n }\n\n return neighbors;\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function getNeighbors(req, res) {\n // variables defined in the Swagger document can be referenced using req.swagger.params.{parameter_name}\n var setId = req.swagger.params.setId.value || '';\n var treeId = req.swagger.params.treeId.value || '';\n var filter = req.swagger.params.filter.value || '';\n\n // get the url for the solr instance with setId trees\n var url = 'http://localhost:8983/solr/'+setId+'/query?rows=20000';\n url += '&fl=treeId,nodeType,gene*';\n // build a query for the given tree\n var solrQuery = '&q={!graph from=geneNeighbors to=geneRank maxDepth=1}treeId:'+treeId;\n solrQuery += ' AND geneRank:[* TO *]';\n // possibly apply filter\n if (filter) {\n solrQuery += ' AND ' + filter;\n }\n // run the query\n request(url + solrQuery, function(err, response, body) {\n if (err) {\n res.json({error: err});\n }\n var nodes = JSON.parse(body).response.docs;\n var geneByRank = {};\n nodes.forEach(function(n) {\n var rank = n.geneRank[0];\n geneByRank[rank] = {\n treeId: n.treeId,\n biotype: n.nodeType,\n geneId: n.geneId,\n location: {\n region: n.geneRegion,\n start: n.geneStart,\n end: n.geneEnd,\n strand: n.geneStrand\n }\n };\n if (n.geneName) {\n geneByRank[rank].geneName = n.geneName;\n }\n if (n.geneDescription) {\n geneByRank[rank].geneDescription = n.geneDescription;\n }\n });\n res.json(geneByRank);\n });\n}", "function neighboring(a, b) {\n console.log(a);\n console.log(b);\n console.log(linkedByIndex);\n return linkedByIndex[a.id + \",\" + b.id] || linkedByIndex[b.id + \",\" + a.id] || a.id == b.id;\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "getUnvisitedNeighbors(neighbor = null) {\n const directions = neighbor === null ? this.graph[this.currentRoom] : this.graph[neighbor]\n\n const unvisited = []\n for (let i in directions) {\n if (directions[i] === null && !this.visited.has(directions[i])) {\n unvisited.push(i)\n }\n }\n return unvisited\n }", "function neighbours(x1,y1,colour)\r\n{\r\n\treturn neighbours_ext(x1,y1,colour,grid);\r\n}", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "function neighboring(a, b) {\n return linkedByIndex[a.index + \",\" + b.index];\n }", "getNeighbors() {\n let neighbors = [];\n switch(growthPattern){\n case GROWPATTERN.diamond: \n for (let i = -1; i < 2; i++) {\n for (let j = -1; j < 2; j++) {\n let nearX = i+this.xIndex;\n let nearY = j+this.yIndex;\n if (nearX > -1 && nearX < cols && \n nearY > -1 && nearY < rows && abs(i)!=abs(j)) {\n neighbors.push(this.board.grid[nearX][nearY]);\n }\n }\n }\n break;\n default:\n print(\"Error in neighbors\");\n }\n return neighbors;\n }", "function getNeighborSet(cell_idx) {\n\n // reset return array\n var nset = [];\n\n if (!result.cells.hasOwnProperty(cell_idx) || result.cells[cell_idx] == undefined)\n {\n LOG.debug(\"No cell with that ID: \" + cell_idx);\n return nset;\n }\n\n //LOG.debug('getNeighborSet cell_idx: ' + cell_idx + ' cell size: ' + result.cells.length);\n\n // check if index range is sensible\n if (cell_idx >= 0 && cell_idx < result.cells.length && result.cells[cell_idx].site != undefined) {\n\n var cell_id = result.cells[cell_idx].site.id;\n var halfedges = result.cells[cell_idx].halfedges;\n\n //LOG.debug(result.cells);\n\n //LOG.debug('halfedge count: ' + halfedges.length);\n\n // go through each halfedge & check for edge's sites on two ends\n for (var i=0; i < halfedges.length; i++) {\n\n var edge = halfedges[i].edge;\n /*\n LOG.debug('edge ' + i + ' site_id: ' + halfedges[i].site.id + ' va (' + edge.va.x + ', ' + edge.va.y + ') vb (' + edge.vb.x + ', ' + edge.vb.y + ')');\n LOG.debug('lSite: ' + edge.lSite + ' id: ' + (edge.lSite !== null ? edge.lSite.id : 'null'));\n LOG.debug('rSite: ' + edge.rSite + ' id: ' + (edge.rSite !== null ? edge.rSite.id : 'null'));\n */\n // take the bisector's site from the other side of current given index\n //var id = (edge.bisectingID[0] == index ? edge.bisectingID[1] : edge.bisectingID[0]);\n\n var site = (edge.lSite.id === cell_id ? edge.rSite : edge.lSite);\n //LOG.debug('lSite.id: ' + edge.lSite.id + ' cell_id: ' + cell_id + ' site: ' + site);\n\n if (site !== null)\n nset.push(site.id);\n }\n }\n\n return nset;\n }", "function getNeighbors(tile){\r\n var indexofTile=tile.index(); //get the index of the cell on the grid\r\n var neighbors=[]; \r\n checknextNeigbor(tile); //call the function to check if there is next neighbor and push it in the array \r\n checkpreviousNeigbor(tile); //call the function to check if there is previous neighbor and push it in the array \r\n //check if cell has up neighbor\r\n if(tile.parent().prev().children().eq(indexofTile).length) { \r\n var upTile=tile.parent().prev().children().eq(indexofTile);\r\n neighbors.push(upTile);\r\n checknextNeigbor(upTile);\r\n checkpreviousNeigbor(upTile);\r\n }\r\n //check if cell has down neighbor\r\n if(tile.parent().next().children().eq(indexofTile).length){\r\n var downTile=tile.parent().next().children().eq(indexofTile);\r\n neighbors.push(downTile);\r\n checknextNeigbor(downTile);\r\n checkpreviousNeigbor(downTile);\r\n \r\n }\r\n function checknextNeigbor(cell){ //the function to check if there is next neighbor and push it in the array \r\n if(cell.next().length){ //check if cell has next neighbor\r\n neighbors.push(cell.next()); \r\n }}\r\n function checkpreviousNeigbor(cell){ //the function to check if there is previous neighbor and push it in the array \r\n if(cell.prev().length){ //check if cell has next neighbor\r\n neighbors.push(cell.prev()); \r\n }}\r\n return neighbors; //return neighbors of certain cell\r\n}", "getNeighbor(direction) {\n switch (direction) {\n case \"North\":\n return this.tileNorth;\n case \"South\":\n return this.tileSouth;\n case \"East\":\n return this.tileEast;\n case \"West\":\n return this.tileWest;\n }\n }", "function neighbours(x, y, width, height) {\n var neighbourList = [];\n var right = cell(x + 1, y, width, height);\n var bottom = cell(x, y + 1, width, height);\n if (right !== null) neighbourList.push(right);\n if (bottom !== null) neighbourList.push(bottom);\n return neighbourList;\n}", "function get_neighbours(x,y,visited){\n var neighbours=[];\n var index=((y-1)*no_columns)+(x-1);\n visited[x+','+y]=true;\n //top neighbour\n if(y-1>0 && !grids[index-no_columns].classList.contains('obstacle') && visited[x+','+(y-1)]===undefined){\n neighbours.push([x,(y-1)]);\n visited[x+','+(y-1)]=true;\n };\n //right neighbour\n if(x+1<=no_columns && !grids[index+1].classList.contains('obstacle') && visited[(x+1)+','+y]===undefined){\n neighbours.push([(x+1),y]);\n visited[(x+1)+','+y]=true;\n };\n //bottom neighbour\n if(y+1<=no_rows && !grids[index+no_columns].classList.contains('obstacle') && visited[x+','+(y+1)]===undefined){\n neighbours.push([x,(y+1)]);\n visited[x+','+(y+1)]=true;\n };\n //left neighbour\n if(x-1>0 && !grids[index-1].classList.contains('obstacle') && visited[(x-1)+','+y]===undefined){\n neighbours.push([(x-1),y]);\n visited[(x-1)+','+y]=true;\n };\n return neighbours;\n }", "function neighboring(a, b) {\n return linkedByIndex[`${a.index},${b.index}`];\n }", "getNeighbours(row, col){\n let isTop = (row == 0),\n isBottom = (row == this.rows - 1),\n isLeft = (col == 0),\n isRight = (col == this.cols - 1);\n let neighbours = [[-1, -1], [-1, 0],[-1, 1],[0, -1],[0, 1],[1, -1], [1, 0],[1, 1]];\n // [ -1,-1 -1, 0 -1, 1 ]\n // neighbours [ 0, -1 0, 1 ]\n // [ 1, -1 1, 0 1, 1 ]\n\n\n //IF is top row, removes neightbours above\n if(isTop) {\n neighbours = neighbours.filter(function (e) {\n return e[0] !== -1\n })\n }\n\n if(isBottom){\n neighbours = neighbours.filter(function (e) {\n return e[0] !== 1\n })\n }\n\n if(isLeft){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== -1\n })\n }\n\n if(isRight){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== 1\n })\n }\n\n neighbours.forEach(e => {\n e[0] += row;\n e[1] += col;\n });\n return neighbours;\n }", "static getNeighbours(isTop, isBottom, isLeft, isRight) {\n let neighbours = [[-1, -1], [-1, 0],[-1, 1],[0, -1],[0, 1],[1, -1], [1, 0],[1, 1]];\n // [ -1,-1 -1, 0 -1, 1 ]\n // neighbours [ 0, -1 0, 1 ]\n // [ 1, -1 1, 0 1, 1 ]\n\n\n //IF is top row, removes neightbours above\n if(isTop) {\n neighbours = neighbours.filter(function (e) {\n return e[0] !== -1\n })\n }\n\n if(isBottom){\n neighbours = neighbours.filter(function (e) {\n return e[0] !== 1\n })\n }\n\n if(isLeft){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== -1\n })\n }\n\n if(isRight){\n neighbours = neighbours.filter(function (e) {\n return e[1] !== 1\n })\n }\n return neighbours;\n }", "findNeighbours() {\n const n = this.neighbours;\n const { row, col } = this.pos;\n n.topleft = boxes[row - 1]?.[col - 1]; // get top left corner\n n.top = boxes[row - 1]?.[col]; // get the top box\n n.topright = boxes[row - 1]?.[col + 1]; // get top right corner\n n.right = boxes[row]?.[col + 1]; // get the right box\n n.bottomright = boxes[row + 1]?.[col + 1]; // get bottom right corner\n n.bottom = boxes[row + 1]?.[col]; // get the bottom box\n n.bottomleft = boxes[row + 1]?.[col - 1]; // get bottom left corner\n n.left = boxes[row]?.[col - 1]; // get the left box\n // add all neighbours that exist to allNeighbours array\n this.allNeighbours = Object.values(n).filter((n) => n);\n }", "getNeighbourCells(cell, dist = 1) {\n let neighbours = [];\n neighbours.push(this._maze?.[cell.x]?.[cell.y-dist]);\n neighbours.push(this._maze?.[cell.x]?.[cell.y+dist]);\n neighbours.push(this._maze?.[cell.x-dist]?.[cell.y]);\n neighbours.push(this._maze?.[cell.x+dist]?.[cell.y]);\n\n /** Filter out out of bound cells */\n neighbours = neighbours.filter(cell => cell !== undefined);\n return neighbours;\n }", "function get4Coor(index,n1,n2,n3){\n allCell[index].neighbor = [n1,n2,n3];\n}", "getNeighbors(grid, d, isWall) {\n // Could be a property of the class?\n let moves = [[-d,0],[0,d],[d,0],[0,-d]];\n let neighbors = [];\n for (let move of moves) {\n\n const [row,col] = move;\n let nr = row + this.y;\n let nc = col + this.x;\n\n //if it is or is not a wall, then we add this to our valid neighbors array;\n if(isValidLocation(grid,nr,nc) && \n (isWall === grid[nr][nc].isWall)) {\n\n neighbors.push(grid[nr][nc]);\n }\n }\n \n return neighbors\n }", "function neigh(a, b) {\n return a == b || adjlist[a + \"-\" + b];\n}", "getNeighbor(direction) {\n // tslint:disable-next-line:no-unsafe-any\n return tiled_1.BaseTile.prototype.getNeighbor.call(this, direction);\n }", "findNeighbors(grid) {\r\n // console.log(`current cell position X:${this.positionX}, Y:${this.positionY}`);\r\n\r\n // items.neighbors = \r\n\r\n //left item position\r\n if (this.positionX - 1 > -1) {\r\n // console.log(`Left neighbor`);\r\n this.neighbors.push(grid.items[this.positionY][this.positionX - 1]);\r\n }\r\n //right item position\r\n if (this.positionX + 1 <= grid.width - 1) {\r\n // console.log(`Right neighbor`);\r\n this.neighbors.push(grid.items[this.positionY][this.positionX + 1]);\r\n }\r\n\r\n //top left item position\r\n if (this.positionX - 1 > -1 && this.positionY - 1 > -1) {\r\n // console.log('Top Left')\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX - 1]);\r\n }\r\n //top right item position\r\n if (this.positionX + 1 <= grid.width - 1 && this.positionY - 1 > -1) {\r\n // console.log('Top Right')\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX + 1]);\r\n }\r\n //top item position\r\n if (this.positionY - 1 > -1) {\r\n // console.log(`Top neighbor`);\r\n this.neighbors.push(grid.items[this.positionY - 1][this.positionX]);\r\n }\r\n\r\n //bottom left item position\r\n if (this.positionX - 1 > -1 && this.positionY + 1 <= grid.height - 1) {\r\n // console.log('Bottom Left');\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX - 1]);\r\n }\r\n\r\n //bottom right item position\r\n if (this.positionX + 1 <= grid.width - 1 && this.positionY + 1 <= grid.height - 1) {\r\n // console.log('Bottom Right')\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX + 1]);\r\n }\r\n //bottom item position\r\n if (this.positionY + 1 <= grid.height - 1) {\r\n // console.log(`Bottom neighbor`);\r\n this.neighbors.push(grid.items[this.positionY + 1][this.positionX]);\r\n }\r\n }", "function getNeighborObjects(neighbors) {\n let nodeObjects = []\n neighbors.forEach((neighbor) => {\n let nodeId = neighbor[0] + '-' + neighbor[1]\n nodeObjects.push(getObject(nodeId))\n });\n return nodeObjects\n }", "function getNeighborhoodLabels(nodeIndex){\n\t\tlet neighborsIndex = []\n\t\tglobalData.links.map(function(link){\n\t\t\tif(link.source.index === nodeIndex && !neighborsIndex.includes(link.target.index))\n\t\t\t\tneighborsIndex.push(link.target.index)\n\t\t\tif(link.target.index === nodeIndex && !neighborsIndex.includes(link.source.index))\n\t\t\t\tneighborsIndex.push(link.source.index)\n\t\t})\n\t\treturn neighborsIndex.map(function(index){ return \"node\" + index} )\n\t}", "getNeighbors(vertices, index, adj){\n const neighbors = [];\n for(let i = 0; i < vertices.length; i ++){\n if(adj[index][i] === 1) neighbors.push(i);\n }\n return neighbors;\n }", "getNeighbors(currentCell) {\n var neighbors = [];\n\n // add logic to get neighbors and add them to the array\n for (var xOffset = -1; xOffset <= 1; xOffset++) {\n for (var yOffset = -1; yOffset <= 1; yOffset++) {\n var neighborColumn = currentCell.column + xOffset;\n var neighborRow = currentCell.row + yOffset;\n\n // do something with neighborColumn and neighborRow\n /* Step 9\n - updated it with isValidPosition\n - Checks to prevent the cell that is the currentCell to be added to the array\n */\n if(this.isValidPosition(neighborColumn, neighborRow)){\n var neighborCell = this.cells[neighborColumn][neighborRow];\n \n if(neighborCell != currentCell){\n neighbors.push(neighborCell);\n }\n }\n }\n}\n\n return neighbors;\n}", "function CellNeighbor(neighboar, direction){\n this.direction = direction;\n this.cell = neighboar;\n}", "function findNeighboring (thing, i , j) {\n var coords = {};\n\n if (A.world[i-1]) {\n // the row above exists....\n if (A.world[i-1][j-1] && A.world[i-1][j-1] === thing) { coords.row = i - 1; coords.col = j - 1; };\n if (A.world[i-1][j] === thing) { coords.row = i - 1; coords.col = j; };\n if (A.world[i-1][j+1] && A.world[i-1][j+1] === thing) { coords.row = i - 1; coords.col = j + 1; };\n }\n if (A.world[i][j-1] && A.world[i][j-1] === thing) { coords.row = i; coords.col = j - 1; }; // the 'current' row\n if (A.world[i][j+1] && A.world[i][j+1] === thing) { coords.row = i; coords.col = j + 1; };\n if (A.world[i+1]) {\n // the row below exists...\n if (A.world[i+1][j-1] && A.world[i+1][j-1] === thing) { coords.row = i + 1; coords.col = j - 1; };\n if (A.world[i+1][j] === thing) { coords.row = i + 1; coords.col = j; };\n if (A.world[i+1][j+1] && A.world[i+1][j+1] === thing) { coords.row = i + 1; coords.col = j + 1; };\n }\n return coords;\n}", "function getNeighbors (cell) {\n var x = cell[0], y = cell[1];\n return [\n [x - 1, y + 1], [x, y + 1], [x + 1, y + 1],\n [x - 1, y ], [x + 1, y ],\n [x - 1, y - 1], [x, y - 1], [x + 1, y - 1]\n ];\n }", "function getNeighborSquares(start) {\n var offset = [-1, 0, 1];\n var neighbors = [];\n offset.forEach(function(xoff) {\n offset.forEach(function(yoff) {\n if (xoff == 0 && yoff == 0) return; // Don't record self\n var neighbor = coords(start.x + xoff, start.y + yoff);\n if (inBounds(neighbor)) { // only record if it's inbounds\n neighbors.push(neighbor);\n }\n });\n });\n\n return neighbors;\n}", "get unflaggedNeighbours() {\n return this.allNeighbours.filter((n) => !n.isDug && !n.hasFlag);\n }", "getNeighbors(cell, options = {}) {\n return this.model.getNeighbors(cell, options);\n }", "function getNeighborLookupFunction(lyr, arcs) {\n var classifier = getArcClassifier(lyr.shapes, arcs, {reusable: true});\n var classify = classifier(onShapes);\n var currShapeId;\n var neighbors;\n var callback;\n\n function onShapes(a, b) {\n if (b == -1) return -1; // outer edges are b == -1\n return a == currShapeId ? b : a;\n }\n\n function onArc(arcId) {\n var nabeId = classify(arcId);\n if (nabeId == -1) return;\n if (callback) {\n callback(nabeId, arcId);\n } else if (neighbors.indexOf(nabeId) == -1) {\n neighbors.push(nabeId);\n }\n }\n\n return function(shpId, cb) {\n currShapeId = shpId;\n if (cb) {\n callback = cb;\n forEachArcId(lyr.shapes[shpId], onArc);\n callback = null;\n } else {\n neighbors = [];\n forEachArcId(lyr.shapes[shpId], onArc);\n return neighbors;\n }\n };\n }", "neighborhood() {\n // const thisId = this.customer().neighborhoodId;\n // return store.neighborhoods.find(function(neighborhood) {return neighborhood.id === thisId});\n // two lines of code above works well, but trying another way\n return store.neighborhoods.find(function(neighborhood) {return neighborhood.id === this.neighborhoodId}.bind(this.customer()));\n }", "addNeighbors() {\n let i = this.r;\n let j = this.c;\n if (i > 0) this.neighbors.push(grid[i - 1][j]);\n if (i < n - 1) this.neighbors.push(grid[i + 1][j]);\n if (j > 0) this.neighbors.push(grid[i][j - 1]);\n if (j < m - 1) this.neighbors.push(grid[i][j + 1]);\n }", "function tryAnotherNeighbor(start, destination)\n{\n // Sort our best positions\n start.neighbors.sort(function(a, b)\n {\n return a.f - b.f\n });\n\n for (i = 0; i < start.neighbors.length; i++)\n {\n // Make sure position is not a wall or the agent\n if (start.neighbors[i].f > 0 && start.neighbors[i] != destination)\n {\n return start.neighbors[i];\n }\n }\n\n // Default case\n return start;\n}", "getNeighbors(i, j) {\n\t\tlet neighbors = 0;\n // This section checks above the cell\n //checks up left\n if (i-1 >= 0 && j-1 >= 0 && this.grid[i-1][j-1] > 0){\n neighbors++;\n }\n //checks up\n if (i-1 >= 0 && this.grid[i-1][j] > 0){\n neighbors++;\n }\n //checks up right\n if (i-1 >= 0 && j+1 < this.cols && this.grid[i-1][j+1] > 0){\n neighbors++;\n }\n // This section checks the right and left neighbors\n //checks left\n if (j-1 >= 0 && this.grid[i][j-1] > 0){\n neighbors++;\n }\n //checks right\n if (j+1 < this.cols && this.grid[i][j+1] > 0){\n neighbors++;\n }\n //This section checks below the cell\n //checks down left\n if (i+1 < this.rows && j-1 >= 0 && this.grid[i+1][j-1] > 0){\n neighbors++;\n }\n //checks down\n if (i+1 < this.rows && this.grid[i+1][j] > 0){\n neighbors++;\n }\n //checks down right\n if (i+1 < this.rows && j+1 < this.cols && this.grid[i+1][j+1] > 0){\n neighbors++;\n }\n\t\treturn neighbors;\n\t}", "visitedNeighbors() {\n for (var i = 0; i < this.neighbors.length; i++) {\n if(!this.neighbors[i].visited) {\n return false;\n }\n }\n return true;\n }", "function getNeighbours(trainingSet, testInstance, k)\n{\n var distances = []\n var list_testInstance = listify(testInstance);\n // console.log(list_testInstance);\n // console.log(\"here\")\n\n for (partner of trainingSet)\n {\n var name = partner.firstName\n list_trainingSet = listify(partner);\n // console.log(list_trainingSet);\n dist = euclideanDistance(list_testInstance, list_trainingSet);\n distances.push([name, dist])\n }\n // console.log('// ----------------------------------------------------')\n \n// sort distances by order of magnitude\nvar distancesSorted = distances.sort(function (a, b)\n{\n return a[1] - b[1];\n});\n// console.log(distancesSorted)\n//console.log('// ----------------------------------------------------')\nvar neighbours = []\nvar counter = 0\n// return top k neighbours\nwhile (counter < k)\n{\n if (counter >= distancesSorted.length) break\n if (!Object.is(distancesSorted[counter], undefined)) \n { \n var element = distancesSorted[counter];\n var obj = {id: String, match: Number, rank: Number}\n obj = {id:element[0],match: element[1], rank: counter + 1};\n neighbours.push(obj);\n \n }\n counter++;\n}\nreturn neighbours;\n}", "function getNeighborCoords(i, j) {\n return [\n [i - 1, j - 1], // The three cells in the row above.\n [i - 1, j],\n [i - 1, j + 1],\n [i, j - 1], // The two cells in the same row, to the left and right.\n [i, j + 1],\n [i + 1, j - 1], // The three cells in the row below.\n [i + 1, j],\n [i + 1, j + 1]\n ];\n}", "getNeighbors(node) {\n const left = Math.max(node.col - 1, 0);\n const top = Math.max(node.row - 1, 0);\n const right = Math.min(node.col + 1, this.grid.length - 1);\n const bottom = Math.min(node.row + 1, this.grid[0].length - 1);\n\n const neighbors = [];\n\n for (let c = left; c <= right; c ++) {\n for (let r = top; r <= bottom; r ++) {\n // Skip the current node\n // Skip corners if diagonal routing is disabled\n if (c === node.col && r === node.row ||\n c !== node.col && r !== node.row && !this.options.diagonal) {\n continue;\n }\n\n const n = this.grid[c][r];\n\n if (!n.closed) {\n neighbors.push(n);\n }\n }\n }\n\n return neighbors;\n }", "function getNeighbors(row, col) {\n var neighbors = [];\n var s = 2; //the seperation of the main cells\n if (isInMaze(row, col - s)) {\n neighbors.push([[row, col], [row, col - s]]);\n }\n if (isInMaze(row - s, col)) {\n neighbors.push([[row, col], [row - s, col]]);\n }\n if (isInMaze(row, col + s)) {\n neighbors.push([[row, col], [row, col + s]]);\n }\n if (isInMaze(row + s, col)) {\n neighbors.push([[row, col], [row + s, col]]);\n }\n \n return neighbors;\n}", "getGridPointNeighbors(grid, gridPoint, predicateFn) {\n let ix = gridPoint.ix,\n iy = gridPoint.iy,\n result = [],\n neighbor; // NOTE:\n // It's important to push bottom neighbors first since this method is used\n // in collectPath(), which reversively collects path from end to start node\n // and if bottom neighbors are pushed first in result array then collectPath()\n // will produce a line which is more suitable (pleasant looking) for our purposes.\n\n if (iy < grid.height - 1) {\n neighbor = grid.points[iy + 1][ix];\n (!predicateFn || predicateFn(neighbor)) && result.push(neighbor);\n }\n\n if (iy > 0) {\n neighbor = grid.points[iy - 1][ix];\n (!predicateFn || predicateFn(neighbor)) && result.push(neighbor);\n }\n\n if (ix < grid.width - 1) {\n neighbor = grid.points[iy][ix + 1];\n (!predicateFn || predicateFn(neighbor)) && result.push(neighbor);\n }\n\n if (ix > 0) {\n neighbor = grid.points[iy][ix - 1];\n (!predicateFn || predicateFn(neighbor)) && result.push(neighbor);\n }\n\n return result;\n }", "static fetchNeighborhoods (callback) {\r\n return DBHelper.fetchRestaurants()\r\n .then(restaurants => {\r\n // Filter restaurants to have only given neighborhood\r\n // Get all neighborhoods from all restaurants\r\n const neighborhoods = restaurants.map((v, i) => restaurants[i].neighborhood)\r\n // Remove duplicates from neighborhoods\r\n return neighborhoods.filter((v, i) => neighborhoods.indexOf(v) == i)\r\n })\r\n }", "neighborhood(){\n return store.neighborhoods.find(neighborhood=>{\n return neighborhood.id === this.neighborhoodId\n })\n }", "get_neighbours(node, visited_nodes){\n var size_x = occupation.length;\n var size_y = occupation[0].length;\n var x = node.posx;\n var y = node.posy;\n var lst_ret = [];\n\n if(x-1 >= 0 && visited_nodes[x-1][y].visited == 0){\n lst_ret.push(visited_nodes[x-1][y]);\n }\n if(x+1 < size_x && visited_nodes[x+1][y].visited == 0){\n lst_ret.push(visited_nodes[x+1][y]);\n }\n if(y-1 >= 0 && visited_nodes[x][y-1].visited == 0){\n lst_ret.push(visited_nodes[x][y-1]);\n }\n if(y+1 < size_y && visited_nodes[x][y+1].visited == 0){\n lst_ret.push(visited_nodes[x][y+1]);\n }\n\n return lst_ret;\n }", "function calculate_Neighbors (x_index, y_index) {\n return [\n [x_index - 1, y_index + 1, \"NW\"],\n [x_index, y_index + 1, \"N\"],\n [x_index + 1, y_index + 1, \"NE\"],\n [x_index - 1, y_index, \"W\"],\n [x_index + 1, y_index, \"E\"],\n [x_index - 1, y_index - 1, \"SW\"],\n [x_index, y_index - 1, \"S\"],\n [x_index + 1, y_index - 1, \"SE\"],\n ]\n}" ]
[ "0.70360017", "0.69515157", "0.6904606", "0.6728604", "0.66022277", "0.658964", "0.65655285", "0.6554215", "0.6554215", "0.653251", "0.6527548", "0.6436163", "0.64205074", "0.63417596", "0.6336554", "0.63360125", "0.63254595", "0.6303912", "0.6288841", "0.62830627", "0.62754846", "0.62736195", "0.6272796", "0.6264221", "0.6264221", "0.62431175", "0.62384367", "0.623757", "0.6216883", "0.62105393", "0.6207968", "0.62008077", "0.62008077", "0.6198535", "0.6195856", "0.6194516", "0.61890686", "0.61890686", "0.61890686", "0.61890686", "0.6176517", "0.616843", "0.61678207", "0.61678207", "0.6163976", "0.6162193", "0.6160013", "0.6143068", "0.61315966", "0.612612", "0.61227274", "0.61187685", "0.61129606", "0.61072314", "0.61072314", "0.61072314", "0.61072314", "0.6099398", "0.6099398", "0.6088507", "0.60813314", "0.6062418", "0.60619056", "0.6060358", "0.6041374", "0.60401887", "0.60279614", "0.60185105", "0.6011442", "0.6002319", "0.5997061", "0.5992991", "0.5988109", "0.5982018", "0.5980635", "0.59646356", "0.59365565", "0.59242046", "0.5922101", "0.5902937", "0.58883035", "0.5883547", "0.5883226", "0.58642316", "0.5857967", "0.58411014", "0.58259124", "0.5804411", "0.58009875", "0.5783937", "0.5771646", "0.57655865", "0.5764426", "0.5763532", "0.57554495", "0.5749442", "0.5748657", "0.57480466", "0.574187", "0.5740397" ]
0.68856156
3
fetch data from game
function getData() { var url1 = 'http://localhost:8080/api/game_view/' + myParam fetch(url1) .then(response => response.json()) .then(response => { let slvGames = response console.log(response) main(slvGames) }) .catch(err => console.log(err)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getData(){\n pos.board = [];\n fetch(\"/api/games\").then(function(response){if(response.ok){return response.json()}\n}).then(function (json){\n jsongames = json;\n app.player = json.player\n createPos();\n createGames();\n bottons();\n \n });\n }", "async function getGameData() {\n var res = await fetch(\"/games/search?limit=-1\")\n var resp = await res.json();\n return resp\n}", "function getData() {\n playArea.main.classList.add(\"visible\");\n gameObj = data.data; //function ud(data) {\n buildBoard();\n //fetch method to get data from the url, instead of using the 'data' object above\n}", "async function getStat() {\n const responseFromServer = await fetch('/game-data');\n game_data = await responseFromServer.json();\n \n displayPrompt();\n}", "function fetchGameList(){\n\tfetch(\"https://rawg-video-games-database.p.rapidapi.com/games?page=1\", {\n\t\"method\": \"GET\",\n\t\"headers\": {\n\t\t\"x-rapidapi-host\": \"rawg-video-games-database.p.rapidapi.com\",\n\t\t\"x-rapidapi-key\": \"ba56e18dfbmsha0533de8919d27bp10d3dcjsn5229ce979bb3\"\n\t}\n\t})\n\t.then((resp) => resp.json())\n\t.then(function (response) {\n\t\t\tvar jsonGameList = response;\n\t\t\t//Envia el ID de cada uno de los juegos en la primera página\n\t\t\tfor(var i = 0; i < 19; i++){\n\t\t\t\tfetchGameInfo(jsonGameList.results[i].id);\n\t\t\t}\n\t})\n\t.catch(function (err) {\n\t\t\tconsole.log(\"No se puedo obtener el recurso\", err);\n\t});\n}", "async getData() {\n if(this.state.numberOfPlayers > 2 && this.state.numberOfPlayers <= 4){\n try {\n let result = await fetch('http://localhost:8080/initializegame') \n let data = await result.json()\n await this.props.updatephase();\n console.log(data);\n }\n catch(e){\n console.log(e)\n }\n }\n else{\n alert(\"There's \"+this.state.numberOfPlayers+\" players the game cannot start\");\n }\n \n }", "async function loadGames() {\n const allGameInfoResponse = await fetch(url + '/readAllGames', {\n method: \"GET\",\n headers: {\n \"Content-type\": \"application/json; charset=UTF-8\"\n }\n });\n if (allGameInfoResponse.ok) {\n const games = await allGameInfoResponse.json();\n window.games = games;\n console.log(games);\n }\n else {\n console.log(allGameInfoResponse);\n }\n}", "getGames(){\n let games = fetch(API_URL +'/api/games',\n {method: 'GET'}).then((response) => response.json())\n return games;\n }", "function fetchGame(gameUrl) {\n switch(gameUrl) {\n case 'stryk':\n return fetch(URL_STRYKTIPSET)\n .then(result => result.json())\n .then(data => parseGameData_(data)) \n\n break;\n case 'europa':\n return fetch(URL_EUROPATIPSET)\n .then(result => result.json())\n .then(data => parseGameData_(data)) \n break;\n case 'topp':\n return fetch(URL_TOPPTIPSET)\n .then(result => result.json())\n .then(data => parseGameData_(data)) \n break;\n default: console.warn('Wrong API call');\n }\n }", "loadMujeresForGame () {\n return http.get(\"auth/data/gameMujeres\", User.getToken());\n }", "async function fetchData() {\n const request = await axios.get(fetchUrl);\n setGames(request.data.results);\n return request;\n }", "getData() {\n setInterval(function() {\n fetch(\"/api/game_view/\" + app.getURL())\n .then(function(response) {\n if (response.ok) {\n return response.json();\n } else {\n throw new Error(\"Unable to retrieve data\");\n }\n })\n .then(function(jsonData) {\n app.game = jsonData;\n if (app.game.ships.length == 5) {\n app.placeShips = false;\n } else {\n app.placeShips = true;\n }\n console.log(\"checking ship GET DATA\");\n if (app.game.gameState == \"tie\") {\n app.openModal(\"tieAlert\");\n } else if (app.game.gameState == \"win\") {\n app.openModal(\"winAlert\");\n } else if (app.game.gameState == \"lost\") {\n app.openModal(\"lossAlert\");\n }\n app.checkShip();\n app.checkHits();\n app.checkSalvoes();\n });\n }, 1000);\n }", "function getLobbyData(){}", "getGameData() {\n return {\n d: this._data,\n m: this._moved,\n t: this._taken,\n w: this.winner,\n };\n }", "function getGameInfo() {\n limiter.request({\n url: `https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?champData=all&${api}`,\n method: 'GET',\n json: true,\n }, (error, response) => {\n if (!error && response.statusCode === 200) {\n champions = response.body.data;\n version = response.body.version;\n console.log(champions);\n }\n if (error) {\n throw new Error('Cannot connect to Riot API');\n }\n });\n}", "function loadData(){ \t\n \t//if (gameData.data.player.playerID>0) {\n \t\tCORE.LOG.addInfo(\"PROFILE_PAGE:loadData\");\n \t\t//var p = new ProfileCommunication(CORE.SOCKET, setData); \t\t\n \t\t//p.getData(gameData.data.player.playerID); \t\t\n \t\t\n \t//}\n \t//else \n \t\tsetDataFromLocalStorage(); \t \t \t\n }", "getGameData () {\n let siteIdIndex = window.location.search('games/');\n let gameId = window.location.slice(siteIdIndex + 6);\n fetch(API_URL.games + `/${gameId}`, {\n headers: {\n 'Authorization': `Bearer ${this.props.authToken}`\n }\n })\n .then(res=> res.json())\n .then(data=> {\n this.props.dispatch(loadGameState(data));\n })\n .catch(err=> {\n console.log(JSON.stringify(err));\n //display in status component, don't redirect\n //this.props.dispatch(updateGameStatusError(err))\n })\n }", "function getLiveGames(){\n\n fetch('https://api.opendota.com/api/live')\n .then(convertToJSON) \n .then(getMatchInfo)\n .then(filterTeams)\n .then(writeMatchInfo)\n\n}", "async getGameInfos() {\n\t\tawait this.login(LOGIN_ACCOUNT_GAUTIER)\n\t\tconst game = await this.sendRequest({ rsn:'2ynbmhanlb',guide:{ login:{ language:1,platform:'gaotukc',ug:'' } } }, '699002934')\n\n\t\treturn game.a\n\t}", "getPlayer() {\n fetch(\"/api/games\")\n .then(function(response) {\n if (response.ok) {\n return response.json();\n } else {\n throw new Error(\"Unable to retrieve data\");\n }\n })\n .then(function(jsonData) {\n app.player = jsonData.player;\n });\n }", "function getData() {\r\n fetch('http://www.omdbapi.com?s='+guardian+'&apikey=893a62a')\r\n .then(Response => Response.json())\r\n .then(data => {\r\n moviesData = data.Search\r\n console.log(moviesData);\r\n render(moviesData);\r\n })\r\n }", "function runRetrieveGame() {\n retrieveGame.get(gameId, function(e, r) {\n if (e) {\n callback(e);\n return;\n }\n else if (!r) {\n callback (Error.GAME_NOT_FOUND);\n return;\n }\n\n game.gameId = r.gameId;\n game.gameName = r.gameName;\n game.gameBoard = gameBoard;\n game.gameBoardState = gameBoardState;\n game.gameFinished = r.isFinished;\n game.lastWinner = r.lastWinner;\n game.private = r.private;\n game.gamePass = r.gamePass;\n game.p1Score = r.p1Score;\n game.p2Score = r.p2Score;\n game.p1Id = r.p1Id;\n game.p2Id = r.p2Id;\n game.moves = r.moves;\n game.p1Turn = r.p1Turn;\n\n if (callback)\n callback(null, game);\n });\n }", "function getFromDb(){\n var gameID = $('input[name=\"get_gameId\"]').val();\n console.log(gameID);\n //var gameID = '18';\n $.ajax({\n method: \"GET\",\n url: \"/chess/api/api.php/games/\"+gameID+\"/?csrf=\"+token+\"&transform=1\"\n })\n .done(function( response ) {\n //console.log(response);\n //console.log('fen: '+response.games[0].fen);\n //renderPositionFen(response.games[0].fen);\n $('.board').attr('data-chess-game-id',gameID);\n renderPositionPgn(response.pgn);\n updateMoveList();\n updatePlayers(response.player_w, response.player_b);\n updateFEN();\n updatePGN();\n updateTurn();\n addGameListeners();\n });\n}", "function loadGameData()\n\t\t\t{\n\t\t\t\tif(gameName == \"fatcat7\")\n\t\t\t\t{\n\t\t\t\t\tgame = new FatCat7Game();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"bounty\")\n\t\t\t\t{\n\t\t\t\t\tgame = new BountyGame();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"gummibar\")\n\t\t\t\t{\n\t\t\t\t\tgame = new GummiBarGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"aprilmadness\")\n\t\t\t\t{\n\t\t\t\t\tgame = new AprilMadnessGame();\n\t\t\t\t\tisFreeSpinGame = true;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"moneybooth\")\n\t\t\t\t{\n\t\t\t\t\tgame = new MoneyBoothGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t}\n\t\t\t\telse if(gameName == \"astrologyanswers\")\n\t\t\t\t{\n\t\t\t\t\tgame = new AstrologyAnswersGame();\n\t\t\t\t\tisFreeSpinGame = false;\n\t\t\t\t\tisBothFreeSpinAndOtherBonus = true;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tgame.importGame(xmlData);\n\t\t\t}", "function fetchGames(callback){\n var url = 'http://wap.mlb.com/gdcross/components/game/mlb/year_'+year+'/month_'+month+'/day_'+day+'/miniscoreboard.json';\n console.log('fetching url: ' + url);\n http.get(url, function(res){\n var body = '';\n res.on('data', function(chunk) {\n body += chunk;\n });\n res.on('end', function() {\n var mlbResponse = JSON.parse(body)\n callback(mlbResponse.data.games.game);\n });\n });\n}", "function getData() {\r\n // retrieve our data object\r\n fetch(\"./data.json\") // go and get the data (fetch boy!)\r\n .then(res => res.json()) // good dog! clean the stick (convert the data to a plain object)\r\n .then(data => {\r\n console.log(data);\r\n\r\n buildTeam(data);\r\n\r\n })\r\n .catch(error => console.error(error));\r\n }", "function lobbyData() {\n\t\t//alert('list of local players: ' + players);\n\t\t\n\t\t//puts all players into json object\n \tvar jObject={};\t\n \tfor(i in players)\n\t {\n\t jObject[i] = players[i];\n\t }\n\t\t//checks web for new players\n\t\tvar gamePlayerData = new globals.xml.gamePlayers(input.gameID, jObject);\n\t}", "function getPlayer() {\n hideButtonsAndText();\n let sport = qs(\"textarea\").value;\n let url = INDEX_URL + \"sport=\" + sport;\n if(sport === \"list\") {\n getSports();\n } else {\n fetch(url, {mode: 'cors'})\n .then(checkStatus)\n .then(JSON.parse)\n .then(showPlayer)\n .catch(printError);\n }\n }", "function getAllData() {\n fillPlayerList();\n}", "retrieveGame() {\n const sql = {\n text: `SELECT * FROM rooms`,\n };\n return db.query(sql).then((dbResult) => dbResult.rows[0]);\n }", "function loadData() {\n $.get(\"/api/games\")\n .done(function (data) {\n updateView(data)\n console.log(data);\n })\n .fail(function (jqXHR, textStatus) {\n showOutput(\"Failed: \" + textStatus);\n });\n }", "function loadData() {\n $.get(\"/api/games\")\n .done(function (data) {\n updateView(data)\n console.log(data);\n })\n .fail(function (jqXHR, textStatus) {\n showOutput(\"Failed: \" + textStatus);\n });\n }", "function getSingleGame(_idGame)\n{\n\t$.ajax({\n\t\turl: 'https://test-ta.herokuapp.com/games/' + _idGame,\n\t\ttype:'GET'\n\t}).success(function(_data){\n\t\tconsole.log(_data);\n\t});\n}", "async getGame() {\n return (await this._client.helix.games.getGameById(this._data.game_id));\n }", "async function requestGameState() {\n await fetch(`/api/game/state/${roomId}`).then(res => res.json());\n}", "function getGameInformation() {\n fetch('/api/updateGame').then(function(response) {\n if (response.status !== 200) {\n console.log(response.status + \" msg: \" + resonse.value);\n return;\n }\n response.text().then(function(data) {\n information.innerHTML = data;\n\n })\n });\n}", "getGames() {\n return axios.get(Constants.GAMES_ENDPOINT)\n .then((result) => {\n return result.data;\n })\n }", "function getData()\t{\t\n\t\tCORE.LOG.addInfo(\"SKILLS_SYNCH:getData\");\n\t\t_this_.socket.emit('skillsGetData',\n\t\t\t{ \t\t\n\t\t\t\tplayerID:gameData.data.player.playerID\n\t\t\t}\n\t \t);\n\t}", "async function getAllGameInfo(game){\n const res = await fetch(\"/api/game/info\",{\n method:\"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n info:{\n game: game,\n admin: adminId\n }\n })\n });\n return res.json();\n}", "function retrieve() {\n return playerInfo;\n }", "function getData(){\r\n\r\n \r\n //url of the site where the info comes from\r\n const Launches_URL = \"https://api.spacexdata.com/v2/launches/all\";\r\n \r\n let url = Launches_URL;\r\n\r\n \r\n \r\n \r\n //calling the method that will look through the retrieved info\r\n $.ajax({\r\n dataType: \"json\",\r\n url: url,\r\n data: null,\r\n success: jsonLoaded\r\n });\r\n\t}", "function get_new_gamedata() {\r\n\treturn {\r\n\t\t'turn' : 0,\r\n\t\t'board' : [-1, -1, -1, -1, -1, -1, -1, -1, -1],\r\n\t\t'ended' : false\r\n\t};\r\n}", "async function getData() {\n cardsDiv.innerHTML = `<h1>loading..</h1>`;\n const response = await fetch(endPoint);\n const data = await response.json();\n return data.data;\n}", "async getGame() {\n return this.__request(`${this.api_url}/game/start`, \"POST\");\n }", "function getData() {\n\t\tstate.gameInProgress = true;\n\t\t// Get the data, and on success start\n\t\t$.ajax({\n\t\t\ttype: \"GET\",\n\t\t\turl: \"ajax/data\",\n\t\t\tsuccess: function(result) {\n\t\t\t\tstate.wordList = result.data;\n\t\t\t\tstate.cursor = 0\n\t\t\t\tstate.round = 1\n\t\t\t\tdisplayQuestion();\n\t\t\t},\n\t\t\terror: function() {\n\t\t\t\tdata = 'Could not reach server';\n\t\t\t},\n\t\t});\n\t}", "async getData(){\n\t //old api await axios.get('http://bkjuniorkn.sk/admin/api.php?players')\n\t await axios.get('https://bkjuniorkn.sk/ITU/app/players')\n\t .then(response=> {\n\t \tconsole.log(\"-----Downloading data from database(loading screen)-----\")\n\t\t console.log(response.data);\n\t\t this.setState({players: response.data})\n\t\t //console.log(this.state.players)\n\t\t console.log(\"-----Data has been successfully donwloaded-----\")\n\t\t // console.log(this.state.players[0].name)\n\t })\n\t}", "function getData(pid, game, options) {\n let data = {};\n if (options.field) { // sending the field data\n data.field = game.field.getPack(data.players.list);\n }\n if (options.opponent) { // sending public data of the player\n data.opponent = game.players.list[pid].getPublicPack();\n }\n if (options.self) { // sending all data of the player\n data.self = game.players.list[pid].getPack();\n }\n return data;\n }", "async function getData() {\n try {\n const res = await fetch('https://cdn.rawgit.com/akabab/superhero-api/0.2.0/api/all.json')\n const data = await res.json()\n setDatabase(data)\n } catch (error) {\n console.log(error)\n }\n }", "function getGameData(stringified)\n{\n\tCB_console(\"Showing current data (\" + (stringified ? \"stringified\" : \"object\") + \"):\");\n\tvar data = CB_GEM.getData(stringified);\n\tCB_console(data);\n\talert(stringified ? data : JSON.stringify(data));\n}", "async myGames (data = {}) {\n return await this.request('get', '/my-games', data, {games: ensureArray})\n }", "function getPlayerData() {\n\t\tCallModel.fetch('UserGet', {\n\t\t\tid: $routeParams.player1Id\n\t\t},\n\t\t{\n\t\t\tsuccess: function (response) {\n\t\t\t\t$scope.player1.fullName = response.first_name + ' ' + response.last_name;\n\t\t\t\t$scope.player1.id = response.id;\n\t\t\t}\n\t\t});\n\n\t\tCallModel.fetch('UserGet', {\n\t\t\tid: $routeParams.player2Id\n\t\t},\n\t\t{\n\t\t\tsuccess: function (response) {\n\t\t\t\t$scope.player2.fullName = response.first_name + ' ' + response.last_name;\n\t\t\t\t$scope.player2.id = response.id;\n\t\t\t}\n\t\t})\n\t}", "function getData() {\n openWebEocSession();\n var data = new XMLHttpRequest();\n data.open('GET', baseURL + boardURL, true);\n data.onload = function () {\n if (this.status == 200) {\n let allData = JSON.parse(this.responseText);\n populateAllVariables(allData);\n }\n }\n data.send();\n\n\n}", "static fetchAllGames(url) {\n fetch(url)\n .then(res => res.json())\n .then(gamesObjects => {\n\n // Show the \"Create New Game\" form on the page\n Game.showCreateGameForm();\n\n gamesObjects.forEach(gameObject => {\n \n \n\n // Create a new Game object on the front-end\n const game = new Game(gameObject.id, gameObject.name, gameObject.status, gameObject.phase)\n gameObject.players.forEach(playerObject => {\n const player = new Player(playerObject.id, playerObject.name);\n game.players.push(player);\n }) \n \n // Renders a specific game on the page\n game.renderGameListCard();\n\n })\n\n // Open websocket connection with new games\n Game.createGamesWebsocketConnection();\n\n })\n }", "function fetchMissions() {\n\n /** Add data from missions api to a variable and call any related functions */\n axios.get(MISSIONS).then(response => {\n missionData = response.data;\n createMissionCards();\n });\n}", "function getGameInfo(gameID) {\n $.ajax({\n type: \"get\",\n url: \"/game/\" + gameID,\n success: function(data) {\n if (data.success) {\n currentGame = data.game;\n\t\t gameCode = currentGame.code;\n createGameLobby();\n }\n }\n });\n}", "function loadUnlockData() {\n\n for (var i = 0; i < unlockData.length; i++) {\n\n var gameId = unlockData[i].gameId;\n var unlockState = unlockData[i].unlockState;\n\n if (unlockState == true) {\n displayGame(gameId);\n } else {\n displayGameLock(gameId);\n }\n\n }\n\n}", "async fetchData()\n {\n let response = await AsyncStorage.getItem('@JapQuiz:list');\n let listOfData = await JSON.parse(response) || [];\n\n if (listOfData.score)\n this._currentPoint = listOfData.score;\n else\n this._currentPoint = 0;\n\n if (listOfData.wrong_list)\n this._wrong_list = listOfData.wrong_list;\n else\n this._wrong_list = [];\n }", "function getData() {\n animate();\n \n var url = window.API.getAPIUrl(\"comps\");\n \n //url += \"?env=development\"; //When needed the development branch, for lab.fermat.org\n\n window.API.getCompsUser(function (list){ \n\n window.loadMap(function() {\n\n window.tileManager.JsonTile(function() {\n\n window.preLoad(function() {\n\n window.tileManager.fillTable(list);\n TWEEN.removeAll();\n window.logo.stopFade();\n window.helper.hide('welcome', 1000, true);\n init();\n\n });\n });\n });\n });\n\n \n//Use when you don't want to connect to server\n/*setTimeout(function(){\n var l = JSON.parse(testData);\n \n window.preLoad(function() {\n \n window.tileManager.JsonTile(function() {\n \n window.loadMap(function() {\n tileManager.fillTable(l);\n\n TWEEN.removeAll();\n logo.stopFade();\n init();\n });\n })\n });\n\n }, 6000);*/\n}", "function getData() {\n animate();\n \n var url = window.API.getAPIUrl(\"comps\");\n \n //url += \"?env=development\"; //When needed the development branch, for lab.fermat.org\n\n window.API.getCompsUser(function (list){ \n\n window.loadMap(function() {\n\n window.tileManager.JsonTile(function() {\n\n window.preLoad(function() {\n\n window.tileManager.fillTable(list);\n TWEEN.removeAll();\n window.logo.stopFade();\n window.helper.hide('welcome', 1000, true);\n init();\n\n });\n });\n });\n });\n\n \n//Use when you don't want to connect to server\n/*setTimeout(function(){\n var l = JSON.parse(testData);\n \n window.preLoad(function() {\n \n window.tileManager.JsonTile(function() {\n \n window.loadMap(function() {\n tileManager.fillTable(l);\n\n TWEEN.removeAll();\n logo.stopFade();\n init();\n });\n })\n });\n\n }, 6000);*/\n}", "static async getData() {\n const url = 'http://cparkchallenge.herokuapp.com/report/:lat/:long';\n\n return await fetch(url)\n .then(dataFromServer => dataFromServer.json());\n }", "function getGames(player) {\n playerId = player || \"\";\n if (playerId) {\n playerId = \"/?player_id=\" + playerId;\n }\n $.get(\"/api/games\" + playerId, function(data) {\n console.log(\"Games\", data);\n games = data;\n if (!games || !games.length) {\n displayEmpty(player);\n }\n else {\n initializeRows();\n }\n });\n }", "function fetchData() {\n fetch(url, {\n method: \"get\",\n headers: {\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"x-apikey\": key,\n \"cache-control\": \"no-cache\",\n },\n })\n .then((e) => e.json())\n .then((data) => {\n //Data sendes til functionen handleData\n handleData(data);\n });\n }", "getGameInfos() {\n return game_infos;\n }", "function getInfo() {\n fetch(TRAINERS_URL)\n .then(response => response.json())\n .then(json => makeCard(json.data))\n}", "function get_game_overview(game_id) {\n view_game_id = game_id;\n var dataObj = {\n \"content\" : [ {\n \"session_id\" : get_cookie()\n }, {\n \"game_id\" : game_id\n } ]\n };\n call_server('game_overview', dataObj);\n}", "async function getCards(currentPlayerName) {\n\n let response = await fetch(\"http://nowaunoweb.azurewebsites.net/api/game/GetCards/\" + gameId + \"?playerName=\" + currentPlayerName, {\n method: 'GET',\n contentType: 'application/json'\n\n });\n\n if (response.ok) {\n let result = await response.json();\n return result;\n }\n else {\n alert(\"Methode getCards, HTTP-Error: \" + response.status);\n }\n}", "function poll() {\n $.ajax({\n method: \"GET\",\n url: \"/gs/\" + (gameID).toString()\n }).done((gs) => {\n loaded = window.performance.now();\n parseGameState(gs);\n turnResolve();\n })\n }", "componentDidMount() {\n this.getData().then((data) => {\n this.getThisBoardgame(data);\n });\n }", "function getCard() {\n if (!this.classList.contains(\"unfound\")) {\n let id = this.id;\n let url = \"https://webster.cs.washington.edu/pokedex/pokedex.php?pokemon=\" + id;\n fetch(url)\n .then(checkStatus)\n .then(JSON.parse)\n .then(myCard);\n }\n }", "function readResponse(data) {\r\n\tgame.readResponse(data);\r\n}", "function get_data() {}", "_updateGameData() {\n console.log('_updateGameData::......')\n\n this._showLoading(true, '正在读取游戏数据... ...')\n\n this.gameprops.gameIndex = -1\n this.gameprops.gameDataList = []\n\n // 读取游戏数据\n // let eosClient = EOSJSApi.Localnet(EOSJS_CONFIG.clientConfig)\n // eosClient.contract(EOSJS_CONFIG.contractName)\n // .then((contract) => {\n // console.log('client_updateGameData::' + contract_name + '合约加载成功!')\n // // contract.wish(EOS_CONFIG.contractReceiver, { authorization: [EOS_CONFIG.contractReceiver] })\n // // .then((res) => { this.setState({ pingStatus: 'success' }) })\n // // .catch((err) => { this.setState({ pingStatus: 'fail' }); console.log(err) })\n // })\n\n let eosjs = EOSJSApi.Localnet(EOSJS_CONFIG.clientConfig);//EOSJSApi(EOSJS_CONFIG.clientConfig)\n eosjs.contract(contract_name)\n .then((contract) => {\n console.log('_updateGameData::' + contract_name + '合约加载成功!')\n\n eosjs.getTableRows({\"scope\":contract_name, \"code\":contract_name, \"table\":\"game\", \"json\": true})\n .then(result => {\n console.log('_updateGameData::读取游戏列表成功!')\n\n let rows = result.rows\n let len = rows.length\n for(let i = 0; i < len; i ++){\n var id = result.rows[i].id\n var winner = result.rows[i].winner\n var player1 = result.rows[i].player1\n var player2 = result.rows[i].player2\n var createtime = result.rows[i].createtime\n var owner = result.rows[i].owner\n\n \t// console.log('_updateGameData::rows[' + i + '].id:' + id)\n \t// console.log('_updateGameData::rows[' + i + '].winner:' + winner)\n \t// console.log('_updateGameData::rows[' + i + '].player1:' + player1)\n // console.log('_updateGameData::rows[' + i + '].player2:' + player2)\n // console.log('_updateGameData::rows[' + i + '].createtime:' + createtime)\n // console.log('_updateGameData::rows[' + i + '].owner:' + owner)\n\n this.gameprops.gameDataList.push({\n id: id,\n winner: winner,\n player1: player1,\n player2: player2,\n createtime: createtime,\n owner: owner\n })\n }\n\n if(len > 0){\n this.gameprops.gameIndex = len - 1\n }else{\n this.gameprops.gameIndex = -1\n }\n\n this._refreshUIView()\n \t})\n .catch((err) => {\n console.log('_updateGameData::读取游戏列表失败!')\n this.gameprops.gameIndex = -1\n this._refreshUIView()\n })\n })\n }", "async function fetchData() {\n const favoriteResponse = await axios.get(\n \"https://6161517ee46acd001777c003.mockapi.io/cart\"\n ); // получаем кроссовки из БД для favorites\n\n const itemsResponse = await axios.get(\n \"https://6161517ee46acd001777c003.mockapi.io/favorites\"\n ); // получаем кроссовки из БД для корзины\n const cartResponse = await axios.get(\n \"https://6161517ee46acd001777c003.mockapi.io/items\"\n ); // получаем кроссовки из БД для главной страницы\n\n setIsLoading(false);\n setCardSneakers(favoriteResponse.data);\n setCardFavorite(itemsResponse.data);\n setSneakers(cartResponse.data);\n }", "async function getData() {\n await fetchingData(\n endP({ courseId }).getCourse,\n setCourse,\n setIsFetching\n );\n\n await fetchingData(\n endP({ courseId }).getGroups,\n setGroups,\n setIsFetching\n );\n }", "function fetchStory(){\n fetch(\"./winnerTeams.json\").then(data=>data.json()).then(stroyDataVisualization);\n}", "async function hentdata() {\n const result = await fetch(url, options);\n alleUre = await result.json();\n console.log(alleUre);\n visUre();\n}", "static fetchT1() {\n return db.execute('SELECT player.name as ID,player.real_name,player.position,`character`.name as \"main\",clan.name as \"戰隊\",player.photo FROM player,clan,`character` where player.belong_clan=clan.cid AND clan.cid=1 AND player.main = `character`.chid;');\n }", "function get_games_current() {\n var dataObj = {\n \"content\" : [ {\n \"session_id\" : get_cookie()\n } ]\n };\n call_server('games_current', dataObj);\n}", "fetchData() {\n this.initLoading();\n this.setAndGetInstanceFromSandBox(this.view, this.qs_url).then(instance => {\n this.setLoadingSuccessful();\n this.data.instance = instance;\n }).catch(error => {\n this.setLoadingError(error);\n debugger;\n });\n\n this.getParentInstancesForPath();\n }", "function fetchData() {\n\tshowLoader(); // invoke loader\n\tfetch('https://api.magicthegathering.io/v1/cards?random=true&pageSize=100&language=English')\n\t\t.then((response) => response.json())\n\t\t.then((data) => {\n\t\t\thideLoader(); // invoke hide loader func\n\t\t\tconsole.log(data);\n\t\t\tdataArr = data.cards.slice();\n\t\t\tconsole.log(dataArr); // test\n\t\t\tloadArr = dataArr.slice(0, n);\n\t\n\t\t\trenderCardList(loadArr);\n\t\t\tbtnLoadMore.style.display = 'block'; // show load more button\n\t\t});\n}", "function loadGame(){\n\tgame = getJSON(\"http://navy.hulu.com/create?user=rhassan@andrew.cmu.edu\");\n\tboard = [];\n\t\n\t// Display game information\n\twriteToConsole(\"GAME ID = \" + game.game_id);\n\twriteToConsole(\"SHIPS = [\" + game.ship_sizes + \"]\");\n\twriteToConsole(\"BOARD = (\" + game.board_size.width + \", \" + game.board_size.height + \")\");\n\t\n\t// Intialize board to default values\n\tfor(var w=0; w<game.board_size.width; w++){\n\t\tboard[w] = [];\n\t\tfor(var h=0; h<game.board_size.height; h++){\n\t\t\tboard[w][h]=0;\t\t// signifies uninspected\n\t\t}\n\t}\n\t\n\tships = game.ship_sizes;\n\t\n\traiseSuccess(\"Game intialized\");\n}", "async getter () {\n const seasonsNS = await getSeasons(env.apiLink,env.apiVersion,this.state.lang)\n const storiesNS = await getStories(env.apiLink,env.apiVersion,this.state.lang)\n const questsNS = await getQuests(env.apiLink,env.apiVersion,this.state.lang)\n const characters = await getCharacters(env.apiLink,env.apiVersion,this.state.lang,this.state.key)\n\n if (characters['text'] || characters['text'] === 'Invalid access token') {\n this.setState({\n apiKeyError : 'Invalid key',\n loading: false\n })\n } else {\n const seasons = seasonsNS.sort(function(a, b){return a['order']-b['order']})\n const stories = loadHash.orderBy(storiesNS, ['season', 'order'])\n const quests = loadHash.orderBy(questsNS, ['story', 'level']) // for the moment 'level' is the best way for short this thing\n\n let questsDone = {}\n let backstories = {}\n let characterId = {}\n for (let i = 0; i<characters.length; i++) {\n questsDone[characters[i]] = await getDoneQuests(env.apiLink,env.apiVersion,this.state.lang,this.state.key,characters[i])\n backstories[characters[i]] = await getBackstories(env.apiLink,env.apiVersion,this.state.key,characters[i])\n characterId[characters[i]] = await getInfoCharacter(env.apiLink,env.apiVersion,this.state.lang,this.state.key,characters[i])\n }\n\n return {seasons, stories, quests, characters, questsDone, backstories, characterId}\n }\n }", "function get_player_data_from_db(playername) {\n /*\n TODO: Replace with DB calls\n Return hash like `var cruoti` is setup above\n */\n var playerData = JSON.parse(sessionStorage.getItem('playerData'));\n return playerData[playername];\n}", "async retrieveFromDatabase(username) {\n const query = new Parse.Query('Game');\n query.equalTo('code', this.roomName);\n\n return await query\n .first({\n useMasterKey: true,\n })\n .then((game) => {\n if (!game) return undefined;\n\n const gc = new RoomClient();\n\n for (const x in gc) {\n if (replayAttributes.includes(x)) gc[x] = game.get(x);\n }\n\n gc.stage = 'REPLAY';\n\n gc.username = username;\n gc.clients = gc.players;\n gc.code = this.roomName;\n\n return gc;\n })\n .catch((err) => {\n console.log(err);\n });\n }", "function getStandings() {\n // Blok kode mengambil data dari cache jika tersedia\n if (\"caches\" in window) {\n caches.match(standing_endpoint).then(function (response) {\n if (response) {\n response.json()\n .then(function (data) {\n // Objek/array JavaScript dari response.json() masuk lewat data.\n // Menyusun komponen card standings secara dinamis\n standings(data);\n });\n }\n });\n }\n\n fetchApi(standing_endpoint)\n .then(status)\n .then(json)\n .then(function (data) {\n standings(data);\n })\n .catch(error);\n}", "function getHabits() {\n \n var url = \"http://www.rocketman-endeavours.com/HabitTracker/get_habits.php?user_id=1\";\n \n \n \n fetch(url).then(function(response) {\n console.log(\"Got response from server:\", response);\n return response.json();\n }).then(function(json) {\n \n console.log(\"Got JSON response from server:\" + JSON.stringify(json));\n //Load into JSON\n HabitsBuffer = json;\n \n console.log(HabitsBuffer[0][\"name\"]);\n //var data = json[\"root\"][\"station\"][0];\n\t });\n \n}", "function getPlayerData() {\n var storedPlayerInitials = JSON.parse(localStorage.getItem(\"player-initials\"));\n if (storedPlayerInitials !== null) {\n playerInitials = storedPlayerInitials;\n }\n var storedPlayerScores = JSON.parse(localStorage.getItem(\"player-scores\"));\n if (storedPlayerScores !== null) {\n playerScores = storedPlayerScores;\n }\n}", "static getPlayerInfo(){\n //refer to database for player info\n var playerInfoRef = database.ref('players');\n //repeatedly read database for player info\n playerInfoRef.on(\"value\",(data)=>{\n //for all the player in the game\n allPlayers = data.val();\n })\n }", "fetchData() {\n this.initLoading();\n let qs = this.setAndGetQuerySetFromSandBox(this.view, this.qs_url);\n this.data.instance = qs.cache = qs.model.getInstance({}, qs);\n this.setLoadingSuccessful();\n this.getParentInstancesForPath();\n }", "fetchData() {\n this.initLoading();\n let qs = this.setAndGetQuerySetFromSandBox(this.view, this.qs_url);\n this.data.instance = qs.cache = qs.model.getInstance({}, qs);\n this.setLoadingSuccessful();\n this.getParentInstancesForPath();\n }", "async function getTopCard() {\n\n let response = await fetch(\"http://nowaunoweb.azurewebsites.net/api/game/TopCard/\" + gameId, {\n method: 'GET',\n contentType: 'application/json'\n\n });\n\n if (response.ok) {\n let result = await response.json();\n\n if (result.Value == 13 || result.Value == 14) {\n result.Color = wildColor;\n }\n return result;\n }\n else {\n alert(\"Methode getTopCard, HTTP-Error: \" + response.status);\n }\n}", "retrieveAllGames() {\n return freendiesApi.retrieveAllGames()\n }", "function newGameFetch() {\n event.preventDefault();\n let playerOneId = selectPlayerOne[selectPlayerOne.selectedIndex].dataset.playerId\n let playerTwoId = selectPlayerTwo[selectPlayerTwo.selectedIndex].dataset.playerId\n playerOneName.innerHTML = selectPlayerOne[selectPlayerOne.selectedIndex].innerHTML\n playerTwoName.innerHTML = selectPlayerTwo[selectPlayerTwo.selectedIndex].innerHTML\n fetch('http://localhost:3000/api/v1/games', postGameObj(playerOneId, playerTwoId))\n .then(res => res.json())\n .then(gameData => appendGamePage(gameData))\n .catch(errors => console.log(errors.messages))\n}", "function fetchEnemyData() {\n return axios({\n method: \"get\",\n url: \"https://randomuser.me/api/\"\n });\n}", "function getGameDataPackage()\r\n{\r\n Android.test(\"creating package...\");\r\n return gameString(startingJSON);\r\n}", "function getStanding() {\n if (\"caches\" in window) {\n caches.match(ENDPOINT_COMPETITION).then(function (response) {\n if (response) {\n response.json().then(function (data) {\n console.log(\"Competition Data: \" + data);\n showStanding(data);\n });\n }\n });\n }\n\n fetchAPI(ENDPOINT_COMPETITION)\n .then((data) => {\n showStanding(data);\n })\n .catch((error) => {\n console.log(error);\n });\n}", "async function getData() {\n const api_url = \"json/scenes.json\";\n const response = await fetch(api_url);\n const data = await response.json();\n showSceneThree(data);\n loadSceneThreeSVG();\n console.log(data);\n}", "function getAllGames()\n {\n ajaxHelper(gamesUri, 'GET').done(function (data)\n {\n self.games(data);\n });\n }", "async fetchData() {\n const response = await fetch(\"https://randomuser.me/api/?results=10\");\n if (!response.ok) {\n console.log(\n \"Looks like there was a problem. Status Code: \" + response.status\n );\n }\n\n let data = await response.json();\n let dataf = null;\n return dataf.results;\n }", "createNewGame() {\n fetch('http://192.168.1.234:3000/api/', {\n method: 'POST',\n cache: 'no-cache',\n body: '',\n headers: {\n 'Content-Type': 'application/json'\n }\n })\n .then(async (res) => {\n const data = await res.json();\n if (res.status === 200) {\n Alert.alert(\n 'New Trivia Game',\n 'Play against friends by having them enter the Game ID ' + data.gameId,\n [\n {\n text: 'Play Now', onPress: () => {\n this.loadData(data.gameId);\n }\n }\n ]\n )\n } else {\n throw new Error('Error from server creating game')\n }\n })\n .catch(error => {\n console.log(error)\n });\n }" ]
[ "0.75280356", "0.7517257", "0.73830163", "0.73606074", "0.7176202", "0.7150462", "0.7028436", "0.6899854", "0.6895091", "0.6875735", "0.68416965", "0.68074477", "0.67192066", "0.6700201", "0.6659182", "0.66576904", "0.6633427", "0.66072726", "0.6596919", "0.65950954", "0.65257484", "0.6507303", "0.64932626", "0.6466246", "0.64575255", "0.64466685", "0.6442757", "0.64414215", "0.64365536", "0.6428242", "0.6415628", "0.6415628", "0.6398588", "0.6369052", "0.6365667", "0.6362831", "0.63594335", "0.6358621", "0.6344853", "0.6335848", "0.6328459", "0.6322379", "0.6308533", "0.63075304", "0.6302213", "0.6300955", "0.6292358", "0.629135", "0.62892133", "0.62709934", "0.62695813", "0.6263568", "0.62548834", "0.6251498", "0.62506616", "0.62399673", "0.6234194", "0.6231336", "0.6231336", "0.62310594", "0.62266", "0.62111336", "0.62082607", "0.6207638", "0.6206821", "0.6205934", "0.6194357", "0.61925286", "0.6190763", "0.6181113", "0.6180757", "0.616638", "0.6151526", "0.6146155", "0.61432767", "0.613055", "0.6124575", "0.6123302", "0.61197245", "0.61094254", "0.6106589", "0.61065865", "0.6096916", "0.60958636", "0.6095369", "0.6092471", "0.6092267", "0.6092204", "0.6090505", "0.6090505", "0.6081078", "0.6080226", "0.60772514", "0.606483", "0.6058925", "0.6053289", "0.6044827", "0.60421336", "0.6039057", "0.60384095" ]
0.71849775
4
create game history table
function histTable(slvGames){ var hitArr = [] var hitArrOpp = [] var arr = opponentInfo(slvGames) slvGames.gamePlayer.forEach(elem => { let user = document.getElementById("player") let opponent = document.getElementById("opponent") if(elem.gp_id == myParam){ user.innerHTML = elem.player.name + " " } else if(elem.gp_id != myParam){ opponent.innerHTML = elem.player.name } }) arr.forEach(el => { if(el.gp_id == myParam){ let x = document.getElementById("O" + el.ship) x.innerHTML = el.ship hitArrOpp.push(el.ship) } else if(el.gp_id != myParam){ let y = document.getElementById(el.ship) y.innerHTML = el.ship hitArr.push(el.ship) } }) // set hits on my ships var hitOnSub = 0; var hitOnPT = 0; var hitOnCar = 0; var hitOnDes = 0; var hitOnBat = 0; for(var i=0;i<hitArr.length;i++){ if(hitArr[i] === "Submarine"){ hitOnSub++; if(hitOnSub == 3){ let p = document.getElementById("sSub") p.innerHTML = "Submarine" p.style.color = "red" } } else if(hitArr[i] === "Patrol Boat"){ hitOnPT++; if(hitOnPT == 2){ let p = document.getElementById("sPat") p.innerHTML = "Patrol Boat" p.style.color = "red" } } else if(hitArr[i] === "Carrier"){ hitOnCar++; if(hitOnCar == 5){ let p = document.getElementById("sCar") p.innerHTML = "Carrier" p.style.color = "red" } } else if(hitArr[i] === "Battleship"){ hitOnBat++; if(hitOnBat == 4){ let p = document.getElementById("sBat") p.innerHTML = "Battleship" p.style.color = "red" } } else if(hitArr[i] === "Destroyer"){ hitOnDes++; if(hitOnDes == 3){ let p = document.getElementById("sDes") p.innerHTML = "Destroyer" p.style.color = "red" } } } // set hits on Opponent ships var hitOnOSub = 0; var hitOnOPT = 0; var hitOnOCar = 0; var hitOnODes = 0; var hitOnOBat = 0; for(var i=0;i<hitArrOpp.length;i++){ if(hitArrOpp[i] === "Submarine"){ hitOnOSub++; if(hitOnOSub == 3){ let p = document.getElementById("osSub") p.innerHTML = "Submarine" p.style.color = "red" } } else if(hitArrOpp[i] === "Patrol Boat"){ hitOnOPT++; if(hitOnOPT == 2){ let p = document.getElementById("osPat") p.innerHTML = "Patrol Boat" p.style.color = "red" } } else if(hitArrOpp[i] === "Carrier"){ hitOnOCar++; if(hitOnOCar == 3){ let p = document.getElementById("osCar") p.innerHTML = "Carrier" p.style.color = "red" } } else if(hitArrOpp[i] === "Battleship"){ hitOnOBat++; if(hitOnOBat == 3){ let p = document.getElementById("osBat") p.innerHTML = "Battleship" p.style.color = "red" } } else if(hitArrOpp[i] === "Destroyer"){ hitOnODes++; if(hitOnODes == 3){ let p = document.getElementById("osDes") p.innerHTML = "Destroyer" p.style.color = "red" } } } // set my ships display slvGames.ships.forEach(ship => { let Pt = document.getElementById("patrol boat-hit") let Cr = document.getElementById("carrier-hit") let Sb = document.getElementById("submarine-hit") let Dt = document.getElementById("destroyer-hit") let Bt = document.getElementById("battleship-hit") if(ship.type == "Carrier" && hitOnCar > 0){ document.getElementById("carrier-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "h" + el) div.setAttribute("class", "col-1") div.innerHTML = el Cr.appendChild(div) }) } else if(ship.type == "Battleship" && hitOnBat != 0){ document.getElementById("battleship-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "h" + el) div.setAttribute("class", "col-1") div.innerHTML = el Bt.appendChild(div) }) } else if(ship.type == "Submarine" && hitOnSub != 0){ document.getElementById("submarine-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "h" + el) div.setAttribute("class", "col-1") div.innerHTML = el Sb.appendChild(div) }) } else if(ship.type == "Patrol Boat" && hitOnPT != 0){ document.getElementById("patrol boat-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "h" + el) div.setAttribute("class", "col-1") div.innerHTML = el Pt.appendChild(div) }) } else if(ship.type == "Destroyer" && hitOnDes != 0){ document.getElementById("destroyer-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "h" + el) div.setAttribute("class", "col-1") div.innerHTML = el Dt.appendChild(div) }) } }) // set my Opponents ships display slvGames.ships.forEach(ship => { let Pt = document.getElementById("Opatrol boat-hit") let Cr = document.getElementById("Ocarrier-hit") let Sb = document.getElementById("Osubmarine-hit") let Dt = document.getElementById("Odestroyer-hit") let Bt = document.getElementById("Obattleship-hit") if(ship.type == "Carrier" && hitOnOCar > 0){ document.getElementById("Ocarrier-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "ocar" + ship.ships_locations.indexOf(el)) div.setAttribute("class", "col-1") div.innerHTML = el Cr.appendChild(div) }) } else if(ship.type == "Battleship" && hitOnOBat != 0){ document.getElementById("Obattleship-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "obat" + ship.ships_locations.indexOf(el)) div.setAttribute("class", "col-1") div.innerHTML = el Bt.appendChild(div) }) } else if(ship.type == "Submarine" && hitOnOSub != 0){ document.getElementById("Osubmarine-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "osub" + ship.ships_locations.indexOf(el)) div.setAttribute("class", "col-1") div.innerHTML = el Sb.appendChild(div) }) } else if(ship.type == "Patrol Boat" && hitOnOPT != 0){ document.getElementById("Opatrol boat-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "opat" + ship.ships_locations.indexOf(el)) div.setAttribute("class", "col-1") div.innerHTML = el Pt.appendChild(div) }) } else if(ship.type == "Destroyer" && hitOnODes != 0){ document.getElementById("Odestroyer-hit").style.marginBottom = '10px' ship.ships_locations.forEach(el => { let div = document.createElement("div") div.setAttribute("id", "odes" + ship.ships_locations.indexOf(el)) div.setAttribute("class", "col-1") div.innerHTML = el Dt.appendChild(div) }) } }) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "create_search_history_table(){\n\t\tvar create_search_history_cols = \"(id integer PRIMARY KEY AUTOINCREMENT, project_id integer, keyword varchar, file_name varchar, file_line integer, file_pos integer, user_id integer, created_at datetime, updated_at datetime)\";\n\t\tvar create_search_history_query = \"CREATE TABLE IF NOT EXISTS search_histories \" + create_search_history_cols + \";\";\n\t\tthis.sqlite3_db.exec(create_search_history_query);\n\t}", "generateHistoryTable(currencyHistory) {\n let resultDiv = document.getElementsByClassName('search-result');\n let table = document.createElement('TABLE');\n let day = 30;\n let period = 10;\n\n for (let i = 10; i > 0; i--) {\n var tr = document.createElement('TR');\n for (let j = 0; j < 3; j++) {\n var td = document.createElement('TD')\n td.appendChild(document.createTextNode(`${Object.keys(currencyHistory)[day-(period*j)]} - ${Object.values(currencyHistory)[day-(period*j)]}`));\n tr.appendChild(td)\n }\n day--;\n table.appendChild(tr);\n table.setAttribute('class', 'currency-history');\n }\n\n resultDiv[0].appendChild(table);\n }", "addGameResult(winner) {\n if (!this.state.resultAdded) {\n let wonPlayerName = winner === \"0\" ? this.state.players[0].name : this.state.players[1].name;\n const currentDate = new Date().toLocaleString();\n let newTable = Object.values(Object.assign({}, this.state.resultsTable));\n console.log(\"NEW TABLE \" + newTable);\n newTable.push({ wonPlayerName: wonPlayerName, currentDate: currentDate });\n console.log(newTable);\n this.setState({\n resultsTable: newTable,\n resultAdded: true\n });\n }\n\n\n }", "function generateHistory(data) {\r\n var table = document.createElement(\"table\");\r\n table.className = \"historyTable\";\r\n \r\n var body = document.createElement(\"tbody\");\r\n table.appendChild(body);\r\n \r\n dojo.style(table, \"border\", \"1px solid #D7D7D7\");\r\n \r\n var topRow = document.createElement(\"tr\");\r\n body.appendChild(topRow);\r\n topRow.appendChild(document.createElement(\"td\"));\r\n topRow.firstChild.setAttribute(\"colspan\", \"3\");\r\n topRow.firstChild.innerHTML = \"History\";\r\n\r\n dojo.style(topRow, \"backgroundColor\", \"#F1F1F1\");\r\n\r\n var prices = data.prices ? fixArray(data.prices) : [];;\r\n //var subtitles = data.subtitles;\r\n \r\n var events = [];\r\n \r\n function formatPriceValue(value) {\r\n value = fixArray(value);\r\n if (!value.length) {\r\n return value[0] ? value[0].text + \":\" + value[0].value : value;\r\n }\r\n var str = \"<table><tbody>\";\r\n \r\n for (var i = 0; i < value.length; i++) {\r\n str += \"<tr><td>\" + value[i].text + \"</td><td>\" + value[i].value + \"</td></tr>\";\r\n }\r\n str += \"</tbody></table>\";\r\n return str;\r\n }\r\n \r\n \r\n for (var i = prices.length - 1; i > -1; i--) {\r\n var desc = (i == 0) ? \"Initial Price\" : \"Price changed\";\r\n \r\n events.push({date: prices[i].date, value: formatPriceValue(prices[i].value), text: desc});\r\n }\r\n\r\n events.sort(function(a, b){\r\n if (a.date < b.date) {\r\n return -1;\r\n }\r\n if (a.date == b.date) {\r\n return 0;\r\n }\r\n return 1;\r\n });\r\n \r\n for (var i = events.length - 1; i > -1; i--) {\r\n var row = document.createElement(\"tr\");\r\n var dateCell = document.createElement(\"td\");\r\n var priceCell = document.createElement(\"td\");\r\n var descCell = document.createElement(\"td\");\r\n \r\n var date = new Date(Number(events[i].date));\r\n \r\n var min = date.getMinutes();\r\n var hour = date.getHours();\r\n \r\n dateCell.innerHTML = date.getDate() + \"/\" + (date.getMonth() + 1) + \"/\" \r\n + date.getFullYear() + \" \" + (hour % 12) + \":\" + (min < 10 ? \"0\" + min : min) + (hour >= 12 ? \"PM\" : \"AM\");\r\n priceCell.innerHTML = events[i].value;\r\n descCell.innerHTML = events[i].text;\r\n \r\n row.appendChild(dateCell);\r\n row.appendChild(priceCell);\r\n row.appendChild(descCell);\r\n \r\n dojo.forEach([dateCell, priceCell, descCell], \"dojo.style(item, 'padding', '4px');\");\r\n \r\n \r\n dojo.style(row, \"backgroundColor\", \"#E7ECFF\");\r\n body.appendChild(row);\r\n }\r\n \r\n if (data.isNew) {\r\n dojo.style(table.rows[table.rows.length - 1], \"backgroundColor\", \"#DBCA18\");\r\n }\r\n \r\n dojo.style(table, {\"marginTop\": \"8px\", \"fontSize\": \"8pt\"});\r\n return table;\r\n}", "function iniciarTablaHistorial(tx) {\n\ttx.executeSql('CREATE TABLE IF NOT EXISTS Historial (IDUsuario, CuentaDesde, CuentaHasta, Monto, FechaHora)');\n}", "function createHistory() {\n var history = {\n 'subject' : string[1],\n 'date' : new Date().toString()\n };\n saveHistory(history);\n }", "function genHistoryList() {\n document.querySelector('#searchHistory').innerHTML = \"\"\n for (var idx = 0 ; idx < searchSave.length ; idx++) {\n document.querySelector('#searchHistory').innerHTML +=\n `\n <tr>\n <td scope=\"row\">${searchSave[idx]}</td>\n </tr>\n `\n }\n}", "function createTable(e){\n if(localStorage.getItem(\"id\")){\n id=parseInt(localStorage.getItem(\"id\"),10)+1\n }\n //console.log(\"adicionado pelo botao \"+e.target.name + \"added \" + label)\n var aux_table = {id, label,color: \"#e04141\",attribute_aux,physics:\"false\"}\n localStorage.setItem(\"id\",id)\n var graph_aux=arrayTable[0]\n if(arrayTable && graph_aux){\n graph_aux.nodes.push(aux_table)\n arrayTable.concat(graph_aux)\n hookTable(arrayTable.concat(graph_aux))\n if(arrayTable.length>0){\n localStorage.setItem('tables',JSON.stringify(arrayTable))\n console.log(\"adding\")\n }\n }\n }", "function drawHistory() {\n let historyElement = document.getElementById(\"history\");\n let displayString = \"\";\n for (let i = 0; i < gameHistory.length; i++) {\n displayString +=\n \"<li>\" +\n gameHistory[i].playerMove +\n \" vs \" +\n gameHistory[i].cpuMove +\n \"</li>\";\n }\n historyElement.innerHTML = displayString;\n}", "function generateHistoryObject() {\n\n let o = {}\n\n for (let i = 0; i < 28; i++) {\n o[i] = 0\n }\n\n return o\n\n}", "storeHistory(){\n let winner\n if (this.finalScore1>this.finalScore2) {\n winner = \"VÕITIS MEESKOND 1\"\n } else if (this.finalScore1<this.finalScore2) {\n winner = \"VÕITIS MEESKOND 2\"\n } else {\n winner = \"Mäng jäi viiki!\"\n }\n\n let savedHistory = {\n team1: this.finalScore1,\n team2: this.finalScore2,\n winningteam: winner\n }\n\n this.gameHistory.push(savedHistory); // pushes to gameHistory\n localStorage.setItem(\"gameHistory\", JSON.stringify(this.gameHistory)); // makes local storage entry to string\n }", "function addToHistory(playerMove, cpuMove) {\n const gameResult = {\n playerMove,\n cpuMove\n };\n gameHistory.push(gameResult);\n console.log(gameHistory);\n}", "function setOrderHistory(){\n orderHistory = getOrderHistory(VIP_id); // fetches the order list\n var order_table = document.getElementById(\"order_his_tab\");\n\n var row_header = document.createElement(\"tr\"); // first creates the row for the headers of the table\n\n var name_header = document.createElement(\"th\");\n var date_header = document.createElement(\"th\");\n\n name_header.textContent = get_string(\"order_b_name\");\n date_header.textContent = get_string(\"order_date\");\n\n row_header.appendChild(name_header);\n row_header.appendChild(date_header);\n order_table.appendChild(row_header);\n\n for(i in orderHistory) { // iterates through the orderHistory and adds a new row for each index within the array and displays the cells\n var row = document.createElement(\"tr\");\n for(j in orderHistory[i]){\n var cell = document.createElement('td');\n cell.textContent = orderHistory[i][j];\n row.appendChild(cell);\n }\n order_table.appendChild(row);\n }\n }", "function setHistory(){\r\n\tvar test = \"\";\r\n\tcorrectPlayers.forEach(function(player){\r\n \t\ttest += player.name+\"= \"+player.correct+\"<br>\"\r\n\r\n \t});\r\n // \tconsole.log(test);\r\n\tvar saveHistory = \"Score= \"+score+\"/\"+maxScore+\", Tries= \"+tries+\", Date= \"+date+\", Time= \"+timeused+\", GameID= \"+\"#\"+gameNumber+\"<br> Correct Players: <br>\"+test;\r\n\r\n\tvar historyArray= [\r\n\t{\r\n\t\tscore: score,\r\n\t\tmaxscore: maxScore,\r\n\t\ttries: tries,\r\n\t\tdate: date,\r\n\t\ttimeused: timeused,\r\n\t\tgameNumber: gameNumber,\r\n\t\tcorrectplayers: correctPlayers\r\n\t}];\r\n\t\r\n\tconsole.log(historyArray);\r\n\tnewGameNumber();\r\n\tfor (var i = 0 ; i <= 9; i++) {\r\n\t\tif(document.getElementById(\"history-\"+(i+1)).innerHTML == \"\"){\r\n\t\t\tlocalStorage.setItem(\"History\"+(i+1),saveHistory);\r\n\t\t\thistory[i] = localStorage.getItem(\"History\"+(i+1));\r\n\t\t\tdocument.getElementById(\"history-\"+(i+1)).innerHTML = history[i];\r\n\t\t\t\r\n\t\t\tlocalStorage.setItem(\"HistoryArray\"+(i+1),JSON.stringify(historyArray[0]));\r\n\r\n\t\t\thistoryArrayList[i] = JSON.parse(localStorage.getItem(\"HistoryArray\"+(i+1)));\r\n\t\t\tconsole.log(historyArrayList);\r\n\t\t\treturn;\r\n\t\t}else{\r\n\t\t\thistoryList++;\r\n\t\t}\r\n\t}\r\n\tconsole.log(correctPlayers);\r\n\t// if history is full\r\n\tif(historyList==10){\r\n\t\t// moves history one place down\r\n\t\t\tfor(var i = 9 ; i >= 0; i--){\r\n\t\t\t\tvar temp = localStorage.getItem(\"History\"+i);\r\n\t\t\t\tlocalStorage.setItem(\"History\"+(i+1),temp);\r\n\t\t\t\thistory[i] = temp;\r\n\t\t\t\tdocument.getElementById(\"history-\"+(i+1)).innerHTML = history[i];\r\n\r\n\t\t\t\tvar temp2 = JSON.parse(localStorage.getItem(\"HistoryArray\"+i));\r\n\t\t\t\tlocalStorage.setItem(\"HistoryArray\"+(i+1),JSON.stringify(temp2));\r\n\t\t\t\thistoryArrayList[i] = temp2;\r\n\t\t\t\t// console.log(historyArrayList)\r\n\t\t\t\t// document.getElementById(\"historyArray-\"+(i+1)).innerHTML = \"test\"+historyArrayList[i].score;\r\n\r\n\t\t\t\t// console.log(temp);\r\n\t\t\t}\r\n\t\t\tlocalStorage.setItem(\"History\"+1,saveHistory);\r\n\t\t\thistory[0] = localStorage.getItem(\"History\"+1);\r\n\t\t\tdocument.getElementById(\"history-\"+1).innerHTML = history[0];\r\n\r\n\t\t\tlocalStorage.setItem(\"HistoryArray\"+1,JSON.stringify(historyArray[0]));\r\n\t\t\thistoryArrayList[0] = JSON.parse(localStorage.getItem(\"HistoryArray\"+1));\r\n\t\t\t// alert(\"else activated\");\r\n\t}\r\n\r\n}", "function createRbTable(playerGames) {\n var table = '<table id=\"player-table\" class=\"table table-hover\">' + rbHeaders;\n\n playerGames.forEach(function(game) {\n table += '<tr>' + col(game.date) + col(game.opponent) + col(game.result) + col(game.rush_attempts) +\n col(game.rush_yards) + col(game.avg_yards_per_rush) + col(game.rush_tds) + col(game.receptions) +\n col(game.rec_yards) + col(game.avg_yards_per_rec) + col(game.rec_tds) + col(game.fumbles)\n + col(game.fumbles_lost) + '</tr>';\n });\n\n return table;\n }", "function quickinsertHistory(pFramedata)\r\n{ \r\n var statements = [];\r\n \r\n pFramedata[\"HISTORYID\"] = a.getNewUUID();\r\n pFramedata[\"HISTORY_ID\"] = pFramedata[\"HISTORYID\"];\r\n pFramedata[\"RELATION_ID\"] = a.valueof(\"$global.user_relationid\");\r\n pFramedata[\"ENTRYDATE\"] = a.valueof(\"$sys.date\");\r\n\r\n var fields = [\"HISTORYID\", \"RELATION_ID\", \"ENTRYDATE\", \"MEDIUM\", \"DIRECTION\", \"SUBJECT\", \"INFO\", \"DATE_NEW\", \"USER_NEW\"];\r\n var types = a.getColumnTypes(\"HISTORY\", fields);\r\n if ( pFramedata[\"INFO\"] == null) pFramedata[\"INFO\"] = \"\";\r\n statements.push([\"HISTORY\", fields, types, getColumnValues(fields, pFramedata)]);\r\n \r\n fields = [\"HISTORYLINKID\", \"HISTORY_ID\", \"ROW_ID\", \"OBJECT_ID\", \"DATE_NEW\", \"USER_NEW\"];\r\n types = a.getColumnTypes(\"HISTORYLINK\", fields);\r\n if(pFramedata[\"ORGRELID\"] != undefined)\r\n {\r\n pFramedata[\"HISTORYLINKID\"] = a.getNewUUID();\r\n pFramedata[\"ROW_ID\"] = pFramedata[\"ORGRELID\"];\r\n pFramedata[\"OBJECT_ID\"] = \"1\";\r\n statements.push([\"HISTORYLINK\", fields, types, getColumnValues(fields, pFramedata)]);\r\n }\r\n\r\n if (pFramedata[\"PERSRELID\"] != undefined)\r\n {\r\n pFramedata[\"HISTORYLINKID\"] = a.getNewUUID();\r\n pFramedata[\"ROW_ID\"] = pFramedata[\"PERSRELID\"];\r\n if(pFramedata[\"ORGID\"] == \"0\")\r\n {\r\n pFramedata[\"OBJECT_ID\"] = \"2\"; //Historienverknüpfung für Privatperson\r\n }\r\n else \r\n {\r\n pFramedata[\"OBJECT_ID\"] = \"3\"; //Historienverknüpfung für Person in Firma\r\n }\r\n statements.push([\"HISTORYLINK\", fields, types, getColumnValues(fields, pFramedata)]);\r\n }\r\n if ( pFramedata[\"SALESPROJECTID\"] != undefined ) // Vertriebsprojekt\r\n {\r\n pFramedata[\"HISTORYLINKID\"] = a.getNewUUID();\r\n pFramedata[\"ROW_ID\"] = pFramedata[\"SALESPROJECTID\"];\r\n pFramedata[\"OBJECT_ID\"] = \"16\";\r\n statements.push([\"HISTORYLINK\", fields, types, getColumnValues(fields, pFramedata)]);\r\n }\r\n // Themenbau eintragen\r\n var HistoryThemeIDs = [];\r\n var val = a.getTableData(\"$comp.tblThemen\", a.ALL);\r\n if (val.length > 0)\r\n {\r\n fields = [\"HISTORY_THEMEID\", \"THEME_ID\", \"THEME\", \"HISTORY_ID\", \"DATE_NEW\", \"USER_NEW\"];\r\n types = a.getColumnTypes(\"HISTORY_THEME\", fields);\r\n for (i=0; i < val.length; i++)\r\n {\r\n if (val[i][2] == null) val[i][2] = \"\";\r\n statements.push([\"HISTORY_THEME\", fields, types, [val[i][0], val[i][1], val[i][2], pFramedata[\"HISTORYID\"], pFramedata[\"DATE_NEW\"], pFramedata[\"USER_NEW\"]]]);\r\n HistoryThemeIDs.push(val[i][0]);\r\n } \r\n }\r\n a.sqlInsert(statements);\r\n\r\n // Wiedervorlage-Aufgabe setzen wenn im Themenbaum für die eingetragenen Themen ein Reminder gestezt ist !!, \r\n if ( HistoryThemeIDs.length > 0 ) setreminder(HistoryThemeIDs);\r\n return pFramedata;\r\n}", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n }", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n }", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n }", "function saveHistory(date, game, score, difficulty, timeLimit) {\n switch (game) {\n case 'Whack-A-Mole':\n let moleHistory = localStorage.getItem(\"moleHistory\");\n\n let dataMole = {\n \"date\": date,\n \"game\": game,\n \"score\": score,\n \"difficulty\": difficulty,\n \"time_limit\": timeLimit, \n }\n getMole()\n if (moleHistory !== null) {\n let parseMole = JSON.parse(moleHistory);\n parseMole.push(dataMole);\n return localStorage.setItem(\"moleHistory\", JSON.stringify(parseMole))\n } else {\n return localStorage.setItem(\"moleHistory\", JSON.stringify([dataMole]))\n }\n break;\n\n case \"Snake Game\":\n let snakeHistory = localStorage.getItem(\"snakeHistory\");\n\n let dataSnake = {\n \"date\": date,\n \"game\": game,\n \"score\": score,\n \"time_played\": timeLimit, \n }\n getSnake()\n if (snakeHistory !== null) {\n let parseSnake = JSON.parse(snakeHistory);\n parseSnake.push(dataSnake);\n localStorage.setItem(\"snakeHistory\", JSON.stringify(parseSnake))\n } else {\n localStorage.setItem(\"snakeHistory\", JSON.stringify([dataSnake]))\n }\n if (snakeHistory !== null) {\n let parseSnake = JSON.parse(snakeHistory);\n parseSnake.push(dataSnake);\n return localStorage.setItem(\"snakeHistory\", JSON.stringify(parseSnake))\n } else {\n return localStorage.setItem(\"snakeHistory\", JSON.stringify([dataSnake]))\n }\n break;\n\n case \"Tic-tac-toe Game\":\n let ticHistory = localStorage.getItem(\"ticHistory\");\n let board = score.split(\",\");\n let finalTally = [];\n for (let i = 0; i < board.length; i++) {\n let number = parseInt(board[i]);\n finalTally.push(number);\n }\n \n let dataTic = {\n \"date\": date,\n \"game\": game,\n \"rounds\": finalTally[0] + finalTally[1] + finalTally[2],\n \"player 1\": finalTally[0],\n \"player 2\": finalTally[1],\n \"draws\": finalTally[2],\n \"type\": difficulty,\n }\n\n getTicTacToe()\n if (ticHistory !== null) {\n let parseTic = JSON.parse(ticHistory);\n parseTic.push(dataTic);\n return localStorage.setItem(\"ticHistory\", JSON.stringify(parseTic))\n } else {\n return localStorage.setItem(\"ticHistory\", JSON.stringify([dataTic]))\n }\n break;\n }\n}", "static get TABLE_NAME() {\n return \"login_history\";\n }", "function createTable(thisMode) {\n\t\t//console.log(\"And the mode is: \" + thisMode);\n\n\t\tplayerIndex = 0;\n\n\t\t// This function creates a new row for every one of the items on the Firebase\n\t\tfunction buildRows(orderText) {\n\t\t\t// Creating the table body\n\t\t\tvar newTBody = $(\"<tbody>\");\n\n\t\t\t// Open the elements on the THISMODE collection and bring items ordered by ORDERTEXT\n\t\t\tdb.collection(thisMode)\n\t\t\t\t.orderBy(orderText)\n\t\t\t\t.get()\n\t\t\t\t.then((snapshot) => {\n\t\t\t\t\t// Do this for every element in the collection\n\t\t\t\t\tsnapshot.docs.forEach((doc) => {\n\t\t\t\t\t\t// Do this ONLY for the number of entries defined by LEADERTALLY\n\t\t\t\t\t\tif (playerIndex < leaderTally) {\n\t\t\t\t\t\t\t// Increment iteration index\n\t\t\t\t\t\t\tplayerIndex++;\n\n\t\t\t\t\t\t\t// Creating new row\n\t\t\t\t\t\t\tvar newTrHead = $(\"<tr>\").appendTo(newTBody);\n\n\t\t\t\t\t\t\t// Creating entry for the player's ranking\n\t\t\t\t\t\t\tvar newTd = $(\"<td>\").text(playerIndex).appendTo(newTrHead);\n\n\t\t\t\t\t\t\t// Creating entry for the player's name\n\t\t\t\t\t\t\tnewTd = $(\"<td>\").text(doc.data().name).appendTo(newTrHead);\n\n\t\t\t\t\t\t\t// Creating entry for the player's country flag\n\t\t\t\t\t\t\tnewTdimg = $(\"<td>\").appendTo(newTrHead);\n\n\t\t\t\t\t\t\t// Creating image tag for the flag\n\t\t\t\t\t\t\tvar newImg = $(\"<img>\")\n\t\t\t\t\t\t\t\t.attr(\"src\", doc.data().flag)\n\t\t\t\t\t\t\t\t.attr(\"id\", \"flag\")\n\t\t\t\t\t\t\t\t.appendTo(newTdimg);\n\n\t\t\t\t\t\t\tswitch (thisMode) {\n\t\t\t\t\t\t\t\tcase \"easy\":\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's number of tries\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\").text(doc.data().tries).appendTo(newTrHead);\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase \"timed\":\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's number of tries\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\").text(doc.data().tries).appendTo(newTrHead);\n\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's overall timed used\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\")\n\t\t\t\t\t\t\t\t\t\t.text(doc.data().overallTime)\n\t\t\t\t\t\t\t\t\t\t.appendTo(newTrHead);\n\t\t\t\t\t\t\t\t\tbreak;\n\n\t\t\t\t\t\t\t\tcase \"challenge\":\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's max level\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\").text(doc.data().level).appendTo(newTrHead);\n\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's overall timed used\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\")\n\t\t\t\t\t\t\t\t\t\t.text(doc.data().overallTime)\n\t\t\t\t\t\t\t\t\t\t.appendTo(newTrHead);\n\n\t\t\t\t\t\t\t\t\t// Creating entry for the player's overall tries\n\t\t\t\t\t\t\t\t\tnewTd = $(\"<td>\")\n\t\t\t\t\t\t\t\t\t\t.text(doc.data().overallTries)\n\t\t\t\t\t\t\t\t\t\t.appendTo(newTrHead);\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\n\t\t\t// Return the reows with data\n\t\t\treturn newTBody;\n\t\t}\n\n\t\t// Clear the previous table\n\t\t$(\"#leaderBody\").html(\"\");\n\n\t\t// Creating the table structure\n\t\tvar newTable = $(\"<table>\")\n\t\t\t.addClass(\"table table-dark\")\n\t\t\t.attr(\"id\", \"leaderboard-table\")\n\t\t\t.appendTo($(\"#leaderBody\"));\n\n\t\t// Creating the table heather\n\t\tvar newTHead = $(\"<thead>\").appendTo(newTable);\n\n\t\t// Creating new row\n\t\tvar newTrHead = $(\"<tr>\").appendTo(newTHead);\n\n\t\t// Creating column heather for ranking\n\t\tvar newTh = $(\"<th>\").attr(\"scope\", \"col\").text(\"#\").appendTo(newTrHead);\n\n\t\t// Creating column heather for username\n\t\tnewTh = $(\"<th>\").attr(\"scope\", \"col\").text(\"Username\").appendTo(newTrHead);\n\n\t\t// Creating column heather for country flag\n\t\tnewTh = $(\"<th>\").attr(\"scope\", \"col\").text(\"Country\").appendTo(newTrHead);\n\n\t\tswitch (thisMode) {\n\t\t\tcase \"easy\":\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\")\n\t\t\t\t\t.attr(\"scope\", \"col\")\n\t\t\t\t\t.text(\"Tries\")\n\t\t\t\t\t.appendTo(newTrHead);\n\n\t\t\t\t// Call function to build the rows... sorting by 'tries'\n\t\t\t\tvar newLines = buildRows(\"tries\").appendTo(newTable);\n\t\t\t\tbreak;\n\n\t\t\tcase \"timed\":\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\")\n\t\t\t\t\t.attr(\"scope\", \"col\")\n\t\t\t\t\t.text(\"Tries\")\n\t\t\t\t\t.appendTo(newTrHead);\n\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\").attr(\"scope\", \"col\").text(\"Time\").appendTo(newTrHead);\n\n\t\t\t\t// Call function to build the rows... sorting by 'overallTime'\n\t\t\t\tvar newLines = buildRows(\"overallTime\").appendTo(newTable);\n\t\t\t\tbreak;\n\n\t\t\tcase \"challenge\":\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\")\n\t\t\t\t\t.attr(\"scope\", \"col\")\n\t\t\t\t\t.text(\"Level\")\n\t\t\t\t\t.appendTo(newTrHead);\n\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\")\n\t\t\t\t\t.attr(\"scope\", \"col\")\n\t\t\t\t\t.text(\"Tries\")\n\t\t\t\t\t.appendTo(newTrHead);\n\n\t\t\t\t// Creating column heather for tries\n\t\t\t\tnewTh = $(\"<th>\").attr(\"scope\", \"col\").text(\"Time\").appendTo(newTrHead);\n\n\t\t\t\t// Call function to build the rows... sorting by 'level'\n\t\t\t\tvar newLines = buildRows(\"level\").appendTo(newTable);\n\t\t\t\tbreak;\n\t\t}\n\t}", "function drawTable(game) {\n\n var tableHeaders = \"<tr>\";\n var firstAndSecondScores = \"<tr>\";\n var finalScores = \"<tr>\";\n var rowEnder = '</tr>';\n var table = \"\";\n var runningTotal = null;\n game.frames.forEach(function(frame, index){\n runningTotal += frame.getFinalFrameScore();\n if (!(frame instanceof TenthFrame)) {\n tableHeaders += '<th scope=\"col\" colspan=\"2\">' + (index + 1) +'</th>';\n firstAndSecondScores += '<td scope=\"row\">' + deNullify(frame.getFirstScore()) + '</td>' +\n '<td scope=\"row\">' + xOrSlash(frame) + '</td>';\n finalScores += '<td colspan=\"2\">' + prepareRunningTotal(runningTotal, frame) + '</td>';\n } else {\n tableHeaders += '<th scope=\"col\" colspan=\"3\">' + (index + 1) +'</th>';\n firstAndSecondScores += '<td scope=\"row\">' + deNullify(frame.getFirstScore()) + '</td>' +\n '<td scope=\"row\">' + deNullify(frame.getSecondScore()) + '</td>' +\n '<td scope=\"row\">' + deNullify( frame.getBonusScore()) + '</td>';\n finalScores += '<td colspan=\"3\">' + prepareRunningTotal(runningTotal, frame) + '</td>';\n }\n });\n\n table = tableHeaders + rowEnder + firstAndSecondScores + rowEnder + finalScores + rowEnder;\n return table;\n}", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n this.compound = 0;\n this.closed = false;\n }", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n this.compound = 0;\n this.closed = false;\n }", "function History() {\n this.time = 0;\n this.done = []; this.undone = [];\n this.compound = 0;\n this.closed = false;\n }", "function makeTable(gameboard, playerTable=true) {\n const table = document.createElement('table');\n if (playerTable) table.classList.toggle(\"playerTable\");\n // Not using thead because both left and top are axes, so it would look weird\n // to have one head at the top only like that\n // The following sets up the top of the table\n const theadrow = document.createElement('tr');\n const thindex = document.createElement('th');\n thindex.textContent = \"Index\";\n theadrow.appendChild(thindex);\n let thtop;\n for (let i = 0; i < 10; i++) {\n thtop = document.createElement('th');\n thtop.textContent = i;\n theadrow.appendChild(thtop);\n }\n table.appendChild(theadrow);\n // The following sets up the following rows\n let tr, th, char, td;\n for (let i = 0; i < 10; i++){\n tr = document.createElement('tr');\n th = document.createElement('th');\n // get index row character\n char = String.fromCharCode(('A'.charCodeAt(0) + i));\n th.textContent = char;\n tr.appendChild(th);\n // fill rest of row\n for (let j = 0; j < 10; j++){\n td = document.createElement('td');\n let cellContent = gameboard.getGameboard()[i][j];\n td.textContent = cellContent === 'O' ? '.' : cellContent; // Use this when not testing\n // td.textContent = cellContent; // Use when testing\n if (!playerTable) {\n td.addEventListener('click', (e) => {\n let playerAttacked = player.playerAttack(gameboard, i, j); // if successful, returns true\n console.log(`You the player attacked position: ${i}, ${j}`);\n if (gameboard.checkGameover()) alert('Game is over! The player won!');\n if (playerAttacked) {\n // Need to select the specific td element. Try using the event.target or something like that here to get the correct element.\n let thisTD = e.target;\n let cellContent = gameboard.getGameboard()[i][j];\n thisTD.textContent = cellContent; // must update table to show attack mark on gameboard\n // now must have npc do their turn. Since this is not asynchronous, should disallow race conditions\n console.log(`And now the npc attacks...`);\n npc.aiAttack(player.gameboard);\n // Need to rerender npc table now... how to do this...\n // method that takes an existing table and renders gameboard over it?\n rerenderGameboard(player.gameboard, document.querySelector('.playerTable'))\n // maybe here check for game over\n if (player.gameboard.checkGameover()) alert('Game is over! NPC player won!');\n\n }\n });\n } else {\n // give unique positional id's only to td elements of the players table\n td.id = `td${i}-${j}`;\n }\n tr.appendChild(td);\n }\n table.appendChild(tr);\n }\n return table;\n}", "loadHistory(){\n\t\tlet history = []\n\t\tthis.state.history.forEach((msg) => {\n\t\t\thistory.push(<tr><td>{msg}</td></tr>);\n\t\t});\n\t\treturn history;\n\t}", "function saveHistory(guess){\n guesses.push(guess);\n}", "function constructTable()\n{\n\tvar el = document.getElementById(\"varnishstat\");\n\tvar table = document.getElementById(\"varnishstat-inner\");\n\tsparklineDataHistory = {};\n\tel.removeChild(table);\n\ttable = document.createElement(\"table\");\n\ttable.className = \"table table-condensed\";\n\ttable.id = \"varnishstat-inner\";\n\theader = table.createTHead();\n\ttr = header.insertRow(0);\n\ttd = tr.insertCell(0);\n\ttd.textContent = \"Name\";\n\ttd.className = \"varnishstat-Name\";\n\ttd = tr.insertCell(1);\n\ttd.textContent = \"Current\";\n\ttd.className = \"varnishstat-Current\";\n\ttd = tr.insertCell(2);\n\ttd.textContent = \"Change\";\n\ttd.className = \"varnishstat-Change\";\n\ttd = tr.insertCell(3);\n\ttd.textContent = \"Average\";\n\ttd.className = \"varnishstat-Average\";\n\ttd = tr.insertCell(4);\n\ttd.textContent = \"Average 10\";\n\ttd.className = \"varnishstat-Average10\";\n\ttd = tr.insertCell(5);\n\ttd.textContent = \"Average 100\";\n\ttd.className = \"varnishstat-Average100\";\n\ttd = tr.insertCell(6);\n\ttd.textContent = \"Average 1000\";\n\ttd.className = \"varnishstat-Average1000\";\n\ttd = tr.insertCell(7);\n\ttd.textContent = \"Description\";\n\ttd.className = \"varnishstat-Description\";\n\t\n\tfor (v in vdata[0]) {\n\t\tif (v == 'timestamp')\n\t\t\tcontinue;\n\t\tignoreNullTable[v] = ignoreNullTable[v] || vdata[0][v]['value'] > 0;\n\t\tif (!ignoreNullTable[v] && ignore_null)\n\t\t\tcontinue;\n\t\torigv = v;\n\t\tv = n(v);\n\t\ttr = table.insertRow(-1);\n\t\ttd = tr.insertCell(0);\n\t\ttd.id = v + \"-name\";\n\t\ttd.textContent = origv;\n\t\ttd = tr.insertCell(1);\n\t\tx = document.createElement(\"div\");\n\t\tx.id = v + \"-cur\";\n\t\ty = document.createElement(\"SPAN\");\n\t\ty.id = v + \"-spark\";\n\t\ty.style.float = \"right\";\n\t\ty.style.width = \"50%\";\n\t\ttd.appendChild(y);\n\t\ttd.appendChild(x);\n\t\t\n\t\ttd = tr.insertCell(2);\n\t\tx = document.createElement(\"div\");\n\t\tx.id = v + \"-diff\";\n\t\ty = document.createElement(\"SPAN\");\n\t\ty.id = v + \"-spark2\";\n\t\ty.style.float = \"right\";\n\t\ty.style.width = \"50%\";\n\t\ttd.appendChild(y);\n\t\ttd.appendChild(x);\n\t\ttd = tr.insertCell(3);\n\t\ttd.id = v + \"-avg\";\n\t\ttd = tr.insertCell(4);\n\t\ttd.id = v + \"-avg10\";\n\t\ttd = tr.insertCell(5);\n\t\ttd.id = v + \"-avg100\";\n\t\ttd = tr.insertCell(6);\n\t\ttd.id = v + \"-avg1000\";\n\t\ttd = tr.insertCell(7);\n\t\ttd.id = v + \"-sdec\";\n\t\ttd.textContent = vdata[0][origv]['description'];\n\t}\n\tel.appendChild(table);\n\tupdateTable();\n}", "saveInHistory(state) {\n let histName = state.currentHistoryName;\n\n if (histName === null) {\n // New history row\n histName = this.getNewHistoryName(state);\n state.currentHistoryName = histName;\n }\n\n state.history[histName] = {\n name: histName,\n lastModification: Date.now(),\n points: state.points,\n links: state.links,\n tooltips: state.tooltips,\n defaultPointColor: state.defaultPointColor,\n defaultLinkColor: state.defaultLinkColor,\n defaultTooltipColor: state.defaultTooltipColor,\n defaultTooltipFontColor: state.defaultTooltipFontColor\n };\n\n this.storeHistory(state.history);\n }", "function save_history () {\n\tvar ds = currHds();\n\tedit_history [edit_history_index] = JSON.stringify(ds.toJSON());\n}", "function addToHistory(user1, user2, db) {\n db.run(`INSERT INTO histories (userID, spokentoID)\n VALUES ('${user1}', '${user2}');`);\n}", "function createActivityTable() {\n // explicitly declaring the rowIdNum protects rowids from changing if the \n // table is compacted; not an issue here, but good practice\n const cmd = 'CREATE TABLE ActivityTable (id INTEGER PRIMARY KEY, date INTEGER, activity TEXT, amount FLOAT';\n db.run(cmd, function(err, val) {\n if (err) {\n console.log(\"Database creation failure\",err.message);\n } else {\n console.log(\"Created database\");\n }\n });\n}", "function createQbTable(playerGames) {\n var table = '<table id=\"player-table\" class=\"table table-hover\">' + qbHeaders;\n playerGames.forEach(function(game) {\n table += '<tr>' + col(game.date) + col(game.opponent) + col(game.result) + col(game.pass_attempts) +\n col(game.pass_completions) + col(game.pass_yards) + col(game.comp_percentage) +\n col(game.avg_yards_per_pass) + col(game.pass_tds) + col(game.interceptions) + col(game.qb_rating)\n + col(game.passer_rating) + col(game.rush_attempts) + col(game.rush_yards) +\n col(game.avg_yards_per_rush) + col(game.rush_tds) + '</tr>';\n\n });\n return table;\n }", "function addDataToLog() {\r\n\tvar sessionsCol = document.createElement(\"th\");\r\n\tsessionsCol.setAttribute(\"scope\", \"row\");\r\n\tif (currentTab === \"pomodoro\") {\r\n\t\tvar sessionData = document.createTextNode(\"Focus\");\r\n\t} else if (currentTab === \"short break\") {\r\n\t\tvar sessionData = document.createTextNode(\"Short Break\");\r\n\t} else if (currentTab === \"long break\") {\r\n\t\tvar sessionData = document.createTextNode(\"Long Break\");\r\n\t}\r\n\r\n\tsessionsCol.appendChild(sessionData);\r\n\r\n\tvar dateCol = document.createElement(\"td\");\r\n\tdateData = document.createTextNode(currentDate);\r\n\tdateCol.appendChild(dateData);\r\n\r\n\tvar startTimeCol = document.createElement(\"td\");\r\n\tdata = document.createTextNode(currentStartTime);\r\n\tstartTimeCol.appendChild(data);\r\n\r\n\tvar endTimeCol = document.createElement(\"td\");\r\n\tdata = document.createTextNode(currentEndTime);\r\n\tendTimeCol.appendChild(data);\r\n\r\n\tvar timeCol = document.createElement(\"td\");\r\n\tif (allPossibleModes[currentTab].localStorage === undefined) {\r\n\t\tdata = document.createTextNode(allPossibleModes[currentTab].defaultTime + \" min\");\r\n\t\ttimeCol.appendChild(data);\r\n\t} else {\r\n\t\tdata = document.createTextNode(allPossibleModes[currentTab].localStorage + \" min\");\r\n\t\ttimeCol.appendChild(data);\r\n\t}\r\n\tvar row = document.createElement(\"tr\");\r\n\trow.setAttribute(\"scope\", \"row\");\r\n\trow.appendChild(sessionsCol);\r\n\trow.appendChild(dateCol);\r\n\trow.appendChild(startTimeCol);\r\n\trow.appendChild(endTimeCol);\r\n\trow.appendChild(timeCol);\r\n\trow.innerHTML += '<td><input class=\"form-control\" type=\"text\" placeholder=\"\" onchange=\"storeLogDescription(this)\"></td>';\r\n\trow.innerHTML +=\r\n\t\t'<td><button type=\"button\" class=\"close\" onclick = \"deleteLog(this)\" aria-label=\"Close\"><i class=\"fas fa-trash-alt\"></i></button></td>';\r\n\tlocationUpdateLog.appendChild(row);\r\n\tstoreLogItems();\r\n\tremoveNoDataLoggedText();\r\n}", "function addHistory( data ) {\n\n if ( typeof(aio.history) != 'object' ) { aio.history = []; } // Change aio.history to array\n if ( typeof(aio.history) == 'object' && aio.history.length > 19 ) { aio.history.pop(); } // Delete oldest record if total exceeds 20\n\n // Add this new record\n aio.history.unshift( data );\n updateHistory();\n\n}", "function history(){\n $.getJSON('/team_dashboard/leads_history',data=>{\n \n historytable(data)\n })\n}", "function initialize() {\n var db = getDatabase();\n db.transaction(\n function(tx) {\n // Create the history table if it doesn't already exist\n // If the table exists, this is skipped\n tx.executeSql('CREATE TABLE IF NOT EXISTS history(uid INTEGER UNIQUE, url TEXT)');\n // Limit history entries to 10\n tx.executeSql('CREATE TRIGGER IF NOT EXISTS delete_till_10 INSERT ON history WHEN (select count(*) from history)>9 \\\nBEGIN \\\n DELETE FROM history WHERE history.uid IN (SELECT history.uid FROM history ORDER BY history.uid limit (select count(*) -10 from history)); \\\nEND;')\n });\n}", "function makeHtmlBoard() {\n let htmlBoard = document.getElementById(\"board\");\n\n // create top row that listens for player click\n // click represents col where game piece will be placed\n let top = document.createElement(\"tr\");\n top.setAttribute(\"id\", \"column-top\");\n top.addEventListener(\"click\", handleClick);\n\n // create individual col cells up to max WIDTH and then append to top row\n for (let col = 0; col < WIDTH; col++) {\n let headCell = document.createElement(\"td\");\n headCell.setAttribute(\"id\", col);\n top.append(headCell);\n }\n // also append top row to game board\n htmlBoard.append(top);\n\n // dynamically creates the main part of html board\n // uses HEIGHT to create table rows\n // uses WIDTH to create table cells for each row\n for (let row = 0; row < HEIGHT; row++) {\n let gameRow = document.createElement(\"tr\");\n\n for (let col = 0; col < WIDTH; col++) {\n let gameCell = document.createElement(\"td\");\n\n gameCell.setAttribute(\"id\", `${row}-${col}`);\n // you'll use this later, so make sure you use y-x\n\n gameRow.append(gameCell);\n\n }\n htmlBoard.append(gameRow);\n\n }\n\n // add event listener for undo button which may be hidden initially\n let undo = document.querySelector(\".undo\");\n undo.addEventListener(\"click\", takeBackMostRecentMove);\n}", "function newgame(table, gameType = 'Killer') {\n //let id = uuid.generate();\n if (games[table]) throw new Error(\"game already created\");\n let g = {type: gameType, table, board: undefined, model: undefined, players: [], phase: 'setup', tricks: [], trick: {} };\n games[table] = g;\n return g;\n}", "function createWrOrTeTable(playerGames) {\n var table = '<table id=\"player-table\" class=\"table table-hover\">' + wrAndTeHeaders\n playerGames.forEach(function(game) {\n table += '<tr>' + col(game.date) + col(game.opponent) + col(game.result) +\n col(game.receptions) + col(game.rec_yards) + col(game.avg_yards_per_rec) + col(game.rec_tds) +\n col(game.rush_attempts) + col(game.rush_yards) + col(game.avg_yards_per_rush) + col(game.rush_tds) +\n col(game.fumbles) + col(game.fumbles_lost) + '</tr>';\n });\n return table;\n }", "gameInit() {\n\t\tthis.curGameData = new GameData(this.genome.length);\n\t\tthis.playHist = [];\n\t\tfor (let i = 0; i < this.hist.length; i++) {\n\t\t\tthis.playHist.push(this.hist[i]);\n\t\t}\n\t}", "function get_new_gamedata() {\r\n\treturn {\r\n\t\t'turn' : 0,\r\n\t\t'board' : [-1, -1, -1, -1, -1, -1, -1, -1, -1],\r\n\t\t'ended' : false\r\n\t};\r\n}", "function createHistoryLine(id, statut, acteur, commentaire, urlfile) {\n var out = [];\n var dtDA;\n \n dtDA = Utilities.formatDate(new Date(), Session.getScriptTimeZone(), \"dd/MM/yyyy HH:mm:ss\")\n // Liste des donnees a injecter dans le Google Sheet Process Achat / Historique DA\n out.push(id);\n out.push(statut);\n out.push(acteur);\n out.push(dtDA);\n out.push(commentaire);\n out.push(concatHistoriqueDA(statut, acteur, dtDA,commentaire, urlfile));\n Log_Info(\"createHistoryLine\", Utilities.formatString(\"DA=%s, out=%s\",id,out));\n // Ecriture des donnes de la demande d'achat dans le Google Sheet / Historique DA associe\n SpreadsheetApp.openById(CLSID)\n .getSheetByName(SHEET_HISTODA)\n .appendRow(out);\n // Mise a jour du flag Updated\n setDAData(id,COLUMN_DA_UPADTED,true);\n}", "function createHistoryTriggers(client) {\n return function(callback) {\n var sql = _.reduce(['postnummer', 'vejstykke', 'adgangsadresse', 'adresse', 'ejerlav', 'adgangsadresse_tema'], function(sql, datamodelName) {\n var datamodel = datamodels[datamodelName];\n var table = datamodel.table;\n sql += format('DROP FUNCTION IF EXISTS %s_history_update() CASCADE;\\n', table);\n sql += format('CREATE OR REPLACE FUNCTION %s_history_update()\\n', table);\n sql += 'RETURNS TRIGGER AS $$\\n';\n sql += 'DECLARE\\n';\n sql += 'seqnum integer;\\n';\n sql += 'optype operation_type;\\n';\n sql += \"BEGIN\\n\";\n\n // we need to verify that one of the history fieldMap have changed, not just the tsv- or geom columns\n var isNotDistinctCond = datamodel.columns.map(function(column) {\n return format(\"OLD.%s IS NOT DISTINCT FROM NEW.%s\", column, column);\n }).join(\" AND \");\n\n sql += format(\"IF TG_OP = 'UPDATE' AND (%s) THEN\\n\", isNotDistinctCond);\n sql += \"RETURN NULL;\\n\";\n sql += \"END IF;\\n\";\n\n\n sql += \"seqnum = (SELECT COALESCE((SELECT MAX(sequence_number) FROM transaction_history), 0) + 1);\\n\";\n sql += \"optype = lower(TG_OP);\\n\";\n\n // set valid_to on existing history row\n sql += \"IF TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN\\n\";\n\n var keyClause = _.map(datamodel.key, function(keyColumn) {\n return keyColumn + ' = OLD.' + keyColumn;\n }).join(' AND ');\n\n sql += format(\"UPDATE %s_history SET valid_to = seqnum WHERE %s AND valid_to IS NULL;\\n\", table, keyClause);\n sql += \"END IF;\\n\";\n\n // create the new history row\n sql += \"IF TG_OP = 'UPDATE' OR TG_OP = 'INSERT' THEN\\n\";\n sql += format(\"INSERT INTO %s_history(\\n\", table);\n sql += 'valid_from, ';\n sql += datamodel.columns.join(', ') + ')\\n';\n sql += \" VALUES (\\n\";\n sql += 'seqnum, ' + datamodel.columns.map(function(column) {\n return 'NEW.' + column;\n }).join(', ') + \");\\n\";\n sql += \"END IF;\\n\";\n\n // add entry to transaction_history\n sql += format(\"INSERT INTO transaction_history(sequence_number, entity, operation) VALUES(seqnum, '%s', optype);\", datamodel.name);\n sql += \"RETURN NULL;\\n\";\n sql += \"END;\\n\";\n sql += \"$$ LANGUAGE PLPGSQL;\\n\";\n\n // create the trigger\n sql += format(\"CREATE TRIGGER %s_history_update AFTER INSERT OR UPDATE OR DELETE\\n\", table);\n sql += format(\"ON %s FOR EACH ROW EXECUTE PROCEDURE\\n\", table);\n sql += format(\"%s_history_update();\\n\", table);\n\n return sql;\n }, '');\n console.log(sql);\n client.query(sql, [], callback);\n };\n}", "addGame (newWeek, newHomeTeamRank, newAwayTeamRank, newDateTime) {\n let newGame = new Game(newWeek, newHomeTeamRank, newAwayTeamRank, newDateTime)\n// as list's index start from 0 but there is no week 0. so minus 1 from week\n this.allGames[newWeek - 1].push(newGame)\n }", "function createTable(table) {\n d3.select(\"tbody\")\n .html(\"\")\n .selectAll(\"tr\")\n .data(table)\n .enter()\n .append(\"tr\")\n .html(d=>{\n return `<td>${d.datetime}</td>\n <td>${d.city}</td>\n <td>${d.state}</td>\n <td>${d.country}</td>\n <td>${d.shape}</td>\n <td>${d.durationMinutes}</td>\n <td>${d.comments}</td>`\n })\n}", "function createGames() {\n let gboard= document.getElementById('tableGames');\n let gms=\"\";\n \n let tableArray = jsongames.games.reverse()\n\n for (let i=0;i<jsongames.games.length;i++){\n \n gms += `<li>Creation Date: ${tableArray[i].creationDate}</li><ul>`;\n \n if(tableArray[i].gamePlayer.length === 2){\n for (gp in tableArray[i].gamePlayer){\n gms += `<li>Player: ${tableArray[i].gamePlayer[gp].player.username}</li>`;\n \n if(jsongames.player.id === tableArray[i].gamePlayer[gp].player.id){\n gms += `<li><a href=\"/web/game.html?gp=${tableArray[i].gamePlayer[gp].id}\"><button id=\"gp_${tableArray[i].gamePlayer[gp].id}\" class=\"btn btn-danger\" type=\"button\" ><span class=\"spinner-grow spinner-grow-sm\"></span>Enter!</button></a></li>`\n }\n }\n }\n if(tableArray[i].gamePlayer.length === 1){\n for (gp in tableArray[i].gamePlayer){\n gms += `<li>Player: ${tableArray[i].gamePlayer[gp].player.username}</li>`;\n \n if(jsongames.player.id === tableArray[i].gamePlayer[gp].player.id){\n gms += `<li><a href=\"/web/game.html?gp=${tableArray[i].gamePlayer[gp].id}\"><button id=\"gp_${tableArray[i].gamePlayer[gp].id}\" class=\"btn btn-danger\" type=\"button\" ><span class=\"spinner-grow spinner-grow-sm\"></span>Enter!</button></a></li>`\n }else{\n if(tableArray[i].player !== \"guest\"){\n gms += `<li><button id=\"g_${tableArray[i].id}\" data-gameid=\"${tableArray[i].id}\" class=\"btn btn-success\" type=\"button\" onclick=\"joinGame(this)\" ><span class=\"spinner-border spinner-border-sm\"></span>Join!</button></li>`\n }\n }\n }\n } \n gms+= `</ul>`;\n }\n\n gboard.innerHTML= gms;\n}", "function create_table ()\n{\n moves = -1;\n finished = false;\n var game_table_element = get_by_id (\"game-table-tbody\");\n for (var row = 0; row < n_rows; row++) {\n var tr = create_node (\"tr\", game_table_element);\n for (var col = 0; col < n_cols; col++) {\n var td = create_node (\"td\", tr);\n var colour = random_colour ();\n td.className = \"piece \" + colour;\n game_table[row][col].colour = colour;\n start_table[row][col] = colour;\n game_table[row][col].element = td;\n game_table[row][col].flooded = false;\n }\n }\n /* Mark the first element of the table as flooded. */\n game_table[0][0].flooded = true;\n /* Initialize the adjacent elements with the same colour to be flooded\n from the outset. */\n flood (game_table[0][0].colour, true);\n append_text (get_by_id(\"max-moves\"), max_moves);\n}", "function addToPlayerHistory(history) {\n let count = countSameLetter(computerBase, history);\n playerHistory.push(`${history}: ${count} letters in common`);\n renderPlayerList();\n}", "function makeHistory(guess, cows, bulls) {\n // The start of the html string containing users guess\n var htmlString = `<div class=\"history-guess\">${guess}</div>`;\n // we need to know how many times total to loop so we add cows and bull\n var total = cows + bulls;\n for ( var j = 0; j < total; j++) {\n // check and see if there were cows in out total\n // this if/else if guarantees we do all cows first, then bulls\n if(cows > 0) {\n // if true, then we can make a cow element\n htmlString += '<div class=\"history-pic cow\"></div>';\n // remove one cow from the list so we dont make to many\n cows--;\n // check and see if there were bulls in our total\n } else if (bulls > 0) {\n // add a bull element to the html string\n htmlString += '<div class=\"history-pic bull\"></div>';\n // remove a bull so we dont make them forever\n bulls--;\n }\n }\n // Here we prepend (put the element on top of the others) inside\n // the history div\n $(\"#history\").prepend(`<div class=\"history-entry\">${htmlString}</div>`);\n }", "function createTable(size) {\n\tmytable = $('<table></table>').attr({ id: \"gameTable\" });\n\tfor (var i = 0; i < size; i++) {\n\t\t// Append the row to the table\n\t\tvar row = $('<tr></tr>').attr({ class: [\"class1\", \"class2\", \"class3\"].join(' ') }).appendTo(mytable);\n\t\tfor (var j = 0; j < size; j++) {\n\t\t\t// Append the cell (td) to the row\n\t\t\t$('<td></td>').text(\"Unplayed\").appendTo(row);\n\t\t}\n\t\t \t\t \n\t}\n\treturn mytable;\n}", "function drawGame() {\n var x, y;\n var gameTable = '<table class=\"game-board\">';\n\n // The higher rows get added to the table first\n for (y = board.BOARD_HEIGHT - 1; y > -1; y--) {\n // Generate each row\n gameTable += '<tr>';\n for (x = 0; x < board.BOARD_WIDTH; x++) {\n gameTable += '<td class=\"' + board.space[x][y] + '\">&nbsp;</td>';\n }\n gameTable += '</tr>';\n }\n gameTable += '</table>';\n // Leave in plain js rather than jquery for efficiency\n document.getElementById(\"game\").innerHTML = gameTable;\n }", "function Game(board, turn, history){\n\n // initialize valuest\n this.board = board;\n this.turn = turn;\n this.history = history;\n }", "function createResultsTable(table, db, callback) {\n if(table.length){ callback(); }\n else {\n db.run(\"create table results (id integer, date text, home_id integer, away_id integer, status text, round integer, scoreHome integer, scoreAway integer)\", callback);\n }\n}", "function loadHistory() {\n if (Cookie.prototype.checkCookie(\"history\")) {\n var history = Cookie.prototype.getCookie(\"history\"), i, row, col, curPlayer;\n if (history.length % 3 === 0) {\n for (i = 0; i < history.length; i += 3) {\n row = parseInt(history.charAt(i + 1), 10);\n col = parseInt(history.charAt(i + 2), 10);\n curPlayer = parseInt(history.charAt(i), 10);\n ticTacToeBoard.update(row, col, curPlayer);\n if (i === history.length - 3) {\n currentPlayer = curPlayer === player1.getValue() ? player2.getValue() : player1.getValue();\n }\n }\n }\n }\n}", "function createTable() {\n\n db.transaction(function (tx) { tx.executeSql(createStatement, [], showRecords, onError); });\n\n}", "function delegate_history(data) {\n\tif(haswebsql) {\n\t\tsstorage.lastviewed=Ext.encode(data);\n\t\tglossdb.data.addhistory(data.title,data.target);\n\t}\n\telse {\n\t\tstorage.lastviewed = Ext.encode(data);\n\t}\n}", "function AddToHistory(i,vals)\n{\n var d = new Date();\n var t = Math.ceil(d.getTime()/1000);\n var entry;\n if (!history.length) {\n entry = history[0] = [];\n historyTime = t;\n } else {\n // add entries up to this time if necessary\n while (historyTime < t) {\n ++historyTime;\n history.unshift([]);\n if (history.length > kPosHisLen) history.pop();\n }\n entry = history[0];\n }\n if (vals) {\n // copy current damper positions into history\n for (var j=0; j<3; ++j) {\n // (fixed to 4 decimals because these are for display only)\n entry[j+i] = vals[j].toFixed(4);\n }\n // log our calculated values once per second\n if (logCalTime != t) {\n logCalTime = t;\n LogReadings(0);\n }\n }\n return t;\n}", "function createBoard() {\n\tconst board = document.querySelector('.game');\n\tconst rows = document.createElement('tr');\n\n\t//Create the head row\n\trows.setAttribute('id', 'HeaderRow');\n\trows.classList.add('row');\n\trows.addEventListener('click', (e) => {\n\t\tgamePlay(e);\n\t});\n\n\t//Create the header column and append to header row\n\tfor (let col = 0; col < WIDTH; col++) {\n\t\tconst cols = document.createElement('td');\n\t\tcols.setAttribute('id', `c${col}`);\n\t\tcols.classList.add('colHead');\n\t\trows.append(cols);\n\t}\n\n\t// Append to board\n\tboard.append(rows);\n\n\t//Create the remaining boards\n\tfor (let myRow = 0; myRow < HEIGHT; myRow++) {\n\t\tconst row = document.createElement('tr');\n\t\tfor (let myCol = 0; myCol < WIDTH; myCol++) {\n\t\t\tconst cols = document.createElement('td');\n\t\t\tcols.setAttribute('id', `r${myRow}c${myCol}`);\n\t\t\tcols.dataset.row = myRow;\n\t\t\tcols.dataset.col = myCol;\n\t\t\tcols.classList.add('col');\n\t\t\trow.append(cols);\n\t\t}\n\t\tboard.append(row);\n\t}\n}", "function create_game_board(){\n update_number_of_players();\n create_player_areas();\n // create new game\n game_instance.deal_cards();\n \n render_cards();\n apply_card_event_handlers();\n \n game_instance.determine_winners();\n // determine_winners();\n // show_best_hands(); //for diagnostics\n }", "function createTable() {\r\n $tbody.innerHTML = \"\";\r\n \r\n var sighting, sightingKeys;\r\n var dom;\r\n var columnValue;\r\n \r\n for (var i = 0; i < ufoData.length; i++) {\r\n sighting = ufoData[i];\r\n sightingKeys = Object.keys(sighting);\r\n\t\r\n $dom = $tbody.insertRow(i);\r\n\t/* insert the column values: 0=date, 1=city, 2=state, 3=country, 4=shape, 5=duration, 6=comments*/\t\r\n for (var j = 0; j < sightingKeys.length; j++) {\r\n columnValue = sightingKeys[j];\r\n $dom.insertCell(j).innerText = sighting[columnValue];\r\n }\r\n }\r\n}", "function showCurrentGameHistory(\n currentGameHistory,\n wordsTableElements\n) {\n if (currentGameHistory.length > 0) {\n currentGameHistory.forEach((wordObj) => {\n const wordData = document.createElement('tr');\n const language = document.createElement('td');\n const word = document.createElement('td');\n const wordMeaning = document.createElement('td');\n\n language.innerHTML = wordObj.lang;\n word.innerHTML = wordObj.word;\n wordMeaning.innerHTML = wordObj.meaning;\n wordData.appendChild(language);\n wordData.appendChild(word);\n wordData.appendChild(wordMeaning);\n wordsTableElements.wordsTableBody.appendChild(wordData);\n wordsTableElements.wordsHistoryDiv.style.visibility = 'visible';\n wordsTableElements.wordsHistoryDiv.style.opacity = 1;\n });\n }\n}", "function _createHistoryFrame() {\n\t\t\tvar $historyFrameName = \"unFocusHistoryFrame\";\n\t\t\t_historyFrameObj = document.createElement(\"iframe\");\n\t\t\t_historyFrameObj.setAttribute(\"name\", $historyFrameName);\n\t\t\t_historyFrameObj.setAttribute(\"id\", $historyFrameName);\n\t\t\t// :NOTE: _Very_ experimental\n\t\t\t_historyFrameObj.setAttribute(\"src\", 'javascript:;');\n\t\t\t_historyFrameObj.style.position = \"absolute\";\n\t\t\t_historyFrameObj.style.top = \"-900px\";\n\t\t\tdocument.body.insertBefore(_historyFrameObj,document.body.firstChild);\n\t\t\t// get reference to the frame from frames array (needed for document.open)\n\t\t\t// :NOTE: there might be an issue with this according to quirksmode.org\n\t\t\t// http://www.quirksmode.org/js/iframe.html\n\t\t\t_historyFrameRef = frames[$historyFrameName];\n\t\t\t\n\t\t\t// add base history entry\n\t\t\t_createHistoryHTML(_currentHash, true);\n\t\t}", "function addHistory(name, time) {\n\n vm.histories.push({\n 'name': name,\n 'time': time,\n });\n\n\n }", "function addRowsToCurrentKeysTable() {\n var $tr = $('<tr/>'),\n $actionTD = $('<td/>'),\n $keyTD = $('<td/>'),\n documentFragment = document.createDocumentFragment();\n\n _.each(Keys.getPlayerKeys(), function () {\n $tr.append($actionTD, $keyTD);\n documentFragment.appendChild($tr[0].cloneNode(true));\n });\n\n $playerKeysTable.append(documentFragment);\n }", "function createRow(history){\n transactionHistory.innerHTML = \"\";\n console.log(history)\n for(let i = history.length-1; i >= 0; i--){\n \n let row = document.createElement('tr');\n \n row.append(history[i][0]);\n row.append(history[i][1]);\n row.append(history[i][2]);\n row.append(history[i][3]);\n\n //adds extra classes in order to filter transaction type\n if(history[i][1].textContent === 'debit'){\n row.classList.add('debit')\n }\n else{\n row.classList.add('credit')\n }\n if(i< history.length-1-4){\n row.style.display = \"none\";\n }\n transactionHistory.append(row);\n \n }\n\n}", "static get tableName() {\n return \"Game\";\n }", "function buildTable(){\n\n}", "function getHistory(counter, table, doneCallback) {\n noPlayers = parseInt(tableau.connectionData);\n myurl = myProxy + 'https://fantasy.premierleague.com/drf/element-summary/' + counter.toString();\n $.getJSON(myurl, function(resp) {\n console.log(counter);\n console.log(resp);\n tableData = [];\n\n // Iterate over the JSON object\n for (var i = 0, len = resp.history.length; i < len; i++) {\n tableData.push({\n\t\t\t\t\t'id': resp.history[i].id,\n\t\t\t\t\t'kickoff_time': resp.history[i].kickoff_time,\n\t\t\t\t\t'kickoff_time_formatted': resp.history[i].kickoff_time_formatted,\n\t\t\t\t\t'team_h_score': resp.history[i].team_h_score,\n\t\t\t\t\t'team_a_score': resp.history[i].team_a_score,\n\t\t\t\t\t'was_home': resp.history[i].was_home,\n\t\t\t\t\t'round': resp.history[i].round,\n\t\t\t\t\t'total_points': resp.history[i].total_points,\n\t\t\t\t\t'value': resp.history[i].value,\n\t\t\t\t\t'transfers_balance': resp.history[i].transfers_balance,\n\t\t\t\t\t'selected': resp.history[i].selected,\n\t\t\t\t\t'transfers_in': resp.history[i].transfers_in,\n\t\t\t\t\t'transfers_out': resp.history[i].transfers_out,\n\t\t\t\t\t'loaned_in': resp.history[i].loaned_in,\n\t\t\t\t\t'loaned_out': resp.history[i].loaned_out,\n\t\t\t\t\t'minutes': resp.history[i].minutes,\n\t\t\t\t\t'goals_scored': resp.history[i].goals_scored,\n\t\t\t\t\t'assists': resp.history[i].assists,\n\t\t\t\t\t'clean_sheets': resp.history[i].clean_sheets,\n\t\t\t\t\t'goals_conceded': resp.history[i].goals_conceded,\n\t\t\t\t\t'own_goals': resp.history[i].own_goals,\n\t\t\t\t\t'penalties_saved': resp.history[i].penalties_saved,\n\t\t\t\t\t'penalties_missed': resp.history[i].penalties_missed,\n\t\t\t\t\t'yellow_cards': resp.history[i].yellow_cards,\n\t\t\t\t\t'red_cards': resp.history[i].red_cards,\n\t\t\t\t\t'saves': resp.history[i].saves,\n\t\t\t\t\t'bonus': resp.history[i].bonus,\n\t\t\t\t\t'bps': resp.history[i].bps,\n\t\t\t\t\t'influence': resp.history[i].influence,\n\t\t\t\t\t'creativity': resp.history[i].creativity,\n\t\t\t\t\t'threat': resp.history[i].threat,\n\t\t\t\t\t'ict_index': resp.history[i].ict_index,\n\t\t\t\t\t'ea_index': resp.history[i].ea_index,\n\t\t\t\t\t'open_play_crosses': resp.history[i].open_play_crosses,\n\t\t\t\t\t'big_chances_created': resp.history[i].big_chances_created,\n\t\t\t\t\t'clearances_blocks_interceptions': resp.history[i].clearances_blocks_interceptions,\n\t\t\t\t\t'recoveries': resp.history[i].recoveries,\n\t\t\t\t\t'key_passes': resp.history[i].key_passes,\n\t\t\t\t\t'tackles': resp.history[i].tackles,\n\t\t\t\t\t'winning_goals': resp.history[i].winning_goals,\n\t\t\t\t\t'attempted_passes': resp.history[i].attempted_passes,\n\t\t\t\t\t'completed_passes': resp.history[i].completed_passes,\n\t\t\t\t\t'penalties_conceded': resp.history[i].penalties_conceded,\n\t\t\t\t\t'big_chances_missed': resp.history[i].big_chances_missed,\n\t\t\t\t\t'errors_leading_to_goal': resp.history[i].errors_leading_to_goal,\n\t\t\t\t\t'errors_leading_to_goal_attempt': resp.history[i].errors_leading_to_goal_attempt,\n\t\t\t\t\t'tackled': resp.history[i].tackled,\n\t\t\t\t\t'offside': resp.history[i].offside,\n\t\t\t\t\t'target_missed': resp.history[i].target_missed,\n\t\t\t\t\t'fouls': resp.history[i].fouls,\n\t\t\t\t\t'dribbles': resp.history[i].dribbles,\n\t\t\t\t\t'element': resp.history[i].element,\n\t\t\t\t\t'fixture': resp.history[i].fixture,\n\t\t\t\t\t'opponent_team': resp.history[i].opponent_team,\n 'player_id': counter\n });\n }\n table.appendRows(tableData);\n //doneCallback();\n //console.log(data.history_past[0].id);\n counter++;\n if (counter <= noPlayers) {\n\t\t\t//if (counter <= 10) {\n getHistory(counter, table, doneCallback);\n } else {\n doneCallback();\n }\n });\n }", "function logEvents(contract, eventType, description) {\n $('#eventsTable > tbody:last-child').append(\"<tr><th>\" + contract + \"</th>\" +\n \"<th>\" + eventType + \"</th>\" +\n \"<th>\" + description + \"</th>\" +\n \"</tr> \");\n}", "function createGrid() {\r\n\tvar gameTable = $( \"<table></table>\" );\r\n\tfor(let i=0 ; i<gameSize ; i++) {\r\n\t\tvar line = $( \"<tr></tr>\" );\r\n\t\tfor(let j=0 ; j<gameSize ; j++) {\r\n\t\t\tvar cell = $( \"<td></td>\" );\r\n\t\t\tcell.addClass(\"cell\");\r\n\t\t\tcell.attr(\"id\", \"cell\"+i+\"-\"+j);\r\n\t\t\tcell.appendTo(line);\r\n\t\t}\r\n\t\tline.appendTo(gameTable);\r\n\t}\r\n\tgameTable.appendTo($( \"#floodit\" ));\r\n\t$( '<span id=\"flooditNbSteps\"></span>' ).appendTo($( \"#floodit\" ));\r\n}", "function push_history() {\n\tedit_history_index++;\n\tsave_history();\n\tedit_history.length = edit_history_index+1;\n}", "function build_table(difficulty) {\n\tvar leaderboard = document.getElementById(\"leaderboard\");\n\tvar title = \"<h1>Scores (\" + difficulty.replace(/\\b\\w/g, l => l.toUpperCase()) + \")</h1>\"\n\tvar table = \"<table class=\\\"table table-bordered table-hover table-striped\\\">\"\n\ttable += \"<thead><tr class=\\\"success\\\"><th>Rank</th><th>Username</th><th>Score</th></tr></thead>\"\n\ttable += \"<tbody>\"\n\t/* Assume: Array is sorted by score */\n\tfor (var i = 0; i < data.length; i++) {\n\t\tif (data[i].username === \"\") {\n\t\t\tdata[i].username = \"Anonymous\";\n\t\t}\n\n\t\ttable += \"<tr>\"\n\t\ttable += \"<th scope=\\\"row\\\">\" + (i + 1) + \"</th>\" + \n\t\t \"<td>\" + data[i].username + \"</td>\" +\n\t\t \"<td>\" + data[i].score + \"</td>\"\n\t\ttable += \"</tr>\"\n\t} \n\ttable += \"</tbody></table>\"\n\tleaderboard.innerHTML = title + table;\n\n\trender_chart();\n}", "function createTable(values) {\n if (values.length !== 0) {\n printTable(values);\n } else {\n log(chalk.red('Your database is empty. Please add information.'))\n };\n\n start();\n}", "function saveTranscriptEntries(players) {\n transcriptHistory.push(new RollbackPoint(players));\n}", "function Game(values){\n this.date = values.date;\n this.homeTeamId = values.homeTeamId;\n this.awayTeamId = values.awayTeamId;\n this.homeGoals = Number(values.homeGoals);\n this.awayGoals = Number(values.awayGoals);\n }", "function generateTable() {\n\tvar request = new XMLHttpRequest();\n\n\trequest.open('GET', url + \"/gentable\", true);\n\trequest.addEventListener('load', function () {\n\t\tif (request.status >= 200 && request.status < 400) {\n\t\t\tvar dataReceived = JSON.parse(request.responseText);\n\t\t\tvar dataReceived2 = JSON.parse(dataReceived.tab);\n\t\t\tcreateTable(dataReceived2);\n\n\t\t} else {\n\t\t\tconsole.log(\"Network request error: \" + request.statusText);\n\t\t}\n\t});\n\trequest.send(null);\n}", "function historyAdd( visitDtm, useTp, usrNm, usrId, savAmt, useAmt, accumAmt, goosNm ) {\r\n\r\n\tnRow = tblBody.insertRow(), colVisitDtm = nRow.insertCell(), colUseTp = nRow.insertCell(), colUsrNm = nRow.insertCell(), colUsrId = nRow.insertCell(), colApplyAmt = nRow.insertCell(), colAccumAmt = nRow.insertCell(), colGoosNm = nRow.insertCell();\r\n\t\r\n\tcolVisitDtm\t.className\t= \"text-center\";\r\n\tcolUseTp\t.className \t= \"text-center\";\r\n\tcolUsrNm\t.className \t= \"text-left\";\r\n\tcolUsrId\t.className \t= \"text-center\";\r\n\tcolApplyAmt\t.className \t= \"text-right\";\r\n\tcolAccumAmt\t.className \t= \"text-right\";\r\n\tcolGoosNm\t.className \t= \"text-left\";\r\n\t\r\n\tcolUsrNm.style.fontSize = \"0.8em\";\r\n\tcolUsrId.style.fontSize = \"0.8em\";\r\n\r\n\tcolGoosNm.style.whiteSpace\t= \"nowrap\";\r\n\t\r\n\tcolVisitDtm .innerHTML = '<td>' + toDateFormat( visitDtm ) \t\t\t\t\t\t\t\t\t+ '</td>';\r\n\tcolUseTp \t.innerHTML = '<td>' + ( useTp == \"U\" ? mLang.get(\"use\") : mLang.get(\"save\") ) \t+ '</td>';\r\n\tif( useTp == \"U\" ) {\t// Change display color that used type.\r\n\t\tcolUseTp.style.color = \"red\";\r\n\t}\r\n\tcolUsrNm\t.innerHTML = '<td>' + usrNm \t\t\t\t\t\t\t\t\t\t\t+ '</td>';\r\n\tcolUsrId\t.innerHTML = '<td>' + toPhoneFormat( usrId )\t\t\t\t\t\t\t+ '</td>';\r\n\tcolApplyAmt\t.innerHTML = '<td>' + toNumWithSep( useTp == \"U\" ? useAmt : savAmt )\t+ '</td>';\r\n\tcolAccumAmt\t.innerHTML = '<td>' + toNumWithSep( accumAmt )\t\t\t\t\t\t\t+ '</td>';\r\n\tcolGoosNm\t.innerHTML = '<td>' + toBlank( goosNm )\t\t\t\t\t\t\t\t\t+ '</td>';\r\n}", "updateHistory(currentBoard) {\n /* add current board to history and increment history index\n *** if historyIndex is less than historyLength-1, it \n means that a move has been played after the user has \n used the jump backwards button. Therefore, all elements in history after\n where historyIndex currently is should be erased *** \n */\n const historyIndex = this.state.historyIndex;\n const historyLength = this.state.history.length;\n var history = this.state.history;\n if (historyIndex < historyLength - 1) {\n history = this.state.history.splice(0, historyIndex + 1);\n }\n\n return history.concat([{ currentBoard: currentBoard }]);\n }", "function createTableFromPrefs() {\n createTable(loadPreferences());\n}", "function cloneHistory(action, index, board) {\n let temp = document.getElementById(\"temp_history\")\n let clone = document.importNode(temp.content, true)\n historyStack = clone.querySelector('.stack')\n historyDesc = clone.querySelector('.desc')\n historyImage = clone.querySelector('.img')\n \n if(board == historyBoard) {\n historyStack.addEventListener('click', () => { \n symbolUndoCount = actionArray.length - index - 1\n updateHistoryView(index, board); \n undo(index);\n }) \n historyImage.src = document.getElementById(action.aid).src\n historyDesc.innerHTML = \"STAMP ADDED\"\n } else {\n historyStack.addEventListener('click', () => { \n textureUndoCount = pathArray.length - index - 1\n updateHistoryView(index, board); \n undoTexture(index);\n })\n } \n return clone\n }", "function recordHistoryforSheet(this_sheet_name) {\n var ss = SpreadsheetApp.getActiveSpreadsheet();\n var sheet = ss.getSheetByName(this_sheet_name);\n var source = sheet.getRange(\"A1:I1\");\n var dates = source.getDisplayValues();\n dates[0][0]='';\n sheet.appendRow(dates[0]); //Append the dates to the log\n var source = sheet.getRange(\"A2:I2\");\n var hours = source.getDisplayValues();\n hours[0][0] = 'Hours';\n sheet.appendRow(hours[0]); //Append the hours worked on those dates to the log\n var cleararea = sheet.getRange(\"B2:H2\"); \n if (this_sheet_name != \"All Staff\") cleararea.clearContent(); //clear the entry fields\n}", "function createTables() {\n\n var db = getDatabase();\n db.transaction(\n function(tx) {\n tx.executeSql('CREATE TABLE IF NOT EXISTS jenkins_data(id INTEGER PRIMARY KEY AUTOINCREMENT, jenkins_name TEXT, jenkins_url TEXT)');\n });\n }", "function display_data(){\n flush_historial();\n // get container '.historial'\n let hist = document.getElementsByClassName('historial')[0];\n // for every item in the database, we create a new row\n // in reverse order, most recent item first!\n for (var i = db_verguenza.length-1; i >= 0; i--) {\n // create row\n row = document.createElement(\"div\");\n row.classList.add('hist_row')\n\n // create cells assign values & append\n // date\n col_fecha = document.createElement(\"div\");\n col_fecha.classList.add('hist_col');\n col_fecha.id = \"hist_fecha\";\n\n let p_fecha = document.createElement(\"p\");\n let fecha = new Date (db_verguenza[i].date);\n let fecha_d = fecha.getDate();\n let fecha_m = fecha.getMonth();\n let fecha_y = fecha.getFullYear();\n let fecha_str = fecha_d + \"-\" + mes[fecha_m] + \"-\" + fecha_y;\n p_fecha.textContent = fecha_str;\n col_fecha.appendChild(p_fecha);\n\n // title\n col_title = document.createElement(\"div\");\n col_title.classList.add('hist_col');\n col_title.id = \"hist_title\";\n\n let a_title = document.createElement(\"a\");\n let title_text = db_verguenza[i].title;\n let title_link = db_verguenza[i].link;\n a_title.textContent = title_text;\n a_title.href = title_link;\n col_title.appendChild(a_title);\n\n // append all\n row.appendChild(col_fecha);\n row.appendChild(col_title);\n hist.appendChild(row);\n }\n day_counter();\n}", "function add_history() {\n let text = JSON.stringify(Y);\n if (text == y_states[y_index])\n return;\n y_index ++;\n y_states[y_index] = text;\n y_states.length = y_index + 1;\n if (y_states.length > MAX_HISTORY)\n y_states.shift();\n}", "function getHistory(verbal) {\n //The array of historic events\n let history = [];\n //At least one event, then try to add more\n do{\n //Add one more event\n history.push(getHistoricEvent());\n }while(roll('d20') <= 10);\n\n //Return the raw array if we don't need a verbal representation\n if(!verbal) return history;\n //Finally, concatenate all these events and return them\n return history.join('\\n\\t\\t');\n}", "function _init_my_job_and_quote_count_info_table(db){\n db.execute('CREATE TABLE IF NOT EXISTS my_job_and_quote_count_info('+\n 'id INTEGER PRIMARY KEY autoincrement,'+\n 'date TEXT,'+\n 'job_count INTEGER,'+\n 'quote_count INTEGER)'); \n }", "async function writeHistory() {\n\tlet translations = await HON_DB.allDocs({ include_docs: true} );\n\tlet entries = translations.rows.length - 1\n\t\t, i = 0, o, t;\n\tlet sources = await SRC_DB.allDocs({ \n\t\tinclude_docs: true,\n\t\tlimit: entries + 1\n\t} );\n\t// console.log(sources);\n\tfor ( i; i <= entries; i++ ) {\n\t\to = sources.rows[i];\n\t\tt = translations.rows[i];\n\t\tlet section = document.createElement('SECTION')\n\t\t\t, h2 = document.createElement('H2')\n\t\t\t, h3 = document.createElement('H3');\n\t\th2.innerText = o.doc.sentence;\n\t\th3.innerText = t.doc.text;\n\t\tsection.appendChild(h2);\n\t\tsection.appendChild(h3);\n\t\tif (document.body.children.length > 0)\n\t\t\tdocument.body.insertBefore(section, document.body.firstChild);\n\t\telse \n\t\t\tdocument.body.appendChild(section);\n\t}\n}", "function addtable() {\n tbody.html(\"\");\n console.log(`There are ${tableDatashape.length} records in this table.`);\n console.log(\"----------\");\n tableDatashape.forEach(function(sighting) {\n var row = tbody.append(\"tr\");\n Object.entries(sighting).forEach(function([key, value]) {\n var cell = row.append(\"td\");\n cell.text(value);\n });\n });\n }", "function make_table_for_external_dispatcher(id_of_table , row_class_name , state){\n let table_witch_contains_id = document.getElementById(id_of_table);\n let table_rows_with_class_name = document.getElementsByClassName(row_class_name);\n\n while (table_rows_with_class_name.length){ // delete all row of certain table\n table_rows_with_class_name[0].remove();\n }\n // generator html pre dani table\n for (let calendar = 0 ; calendar < gates.array_of_calendars.length; calendar++){\n for (let real_time = 0 ;real_time < gates.array_of_calendars[calendar].time_slots.length;real_time++){\n for (let certain_time_slot = 0; certain_time_slot < gates.array_of_calendars[calendar].time_slots[real_time].start_times.length ; certain_time_slot++) {\n // pokial je row prepared negenegrovat s rovnakim casom ak sa uz cas nachada v\n let row = table_witch_contains_id.insertRow();\n row.className = row_class_name;\n let cell1 = row.insertCell(0);\n let cell2 = row.insertCell(1);\n let cell3 = row.insertCell(2);\n let cell4 = row.insertCell(3);\n let cell5 = row.insertCell(4);\n let cell6 = row.insertCell(5);\n let cell7 = row.insertCell(6);\n let cell8 = row.insertCell(7);\n\n if (gates.array_of_calendars[calendar].time_slots[real_time].kamionists_2[certain_time_slot] !== null) {\n cell5.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].kamionists_1[certain_time_slot]\n + \"<br>\" + gates.array_of_calendars[calendar].time_slots[real_time].kamionists_2[certain_time_slot];\n } else {\n cell5.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].kamionists_1[certain_time_slot];\n }\n\n cell4.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].evcs[certain_time_slot];\n\n cell1.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].start_times[certain_time_slot].split(' ')[1];\n cell2.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].destinations[certain_time_slot];\n cell3.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].external_dispatchers[certain_time_slot];\n\n\n if (gates.array_of_calendars[calendar].time_slots[real_time].commoditys[certain_time_slot].length > 40){\n create_html_linked_text(gates.array_of_calendars[calendar].time_slots[real_time].commoditys[certain_time_slot],cell6)\n\n }else{\n cell6.innerHTML = gates.array_of_calendars[calendar].time_slots[real_time].commoditys[certain_time_slot];\n }\n\n cell7.innerHTML = gates.ids[calendar];\n\n let apply_button = document.createElement(\"BUTTON\")\n apply_button.className = \"btn btn-default bg-success only_one\";\n apply_button.onclick = function (){\n let index = gates.array_of_calendars[calendar].time_slots[real_time].ids[certain_time_slot];\n ajax_post_confirm(row,index);\n }\n apply_button.innerHTML = \"Confirm arrival\";\n cell8.className = \"td_flex_buttons\";\n cell8.appendChild(apply_button);\n }\n }\n }\n}", "function AddHistory(id, date_str, desc, able_delete,job_by) {\r\n\t\r\n\tvar str = \"<tr id='\" + id + \"'>\";\r\n\tstr += \"<td>\" + date_str + \"</td>\";\r\n\tstr += \"<td>\" + desc + \"</td>\";\r\n\tstr += \"<td>\" + job_by + \"</td>\";\r\n\tstr += \"<td>\" + ((able_delete)?\"<a href=\\\"#\\\" onclick=\\\"DeleteHistory('\" + id + \"', '\" + date_str + \"')\\\">Delete</a>\":\"\") + \"</td>\";\r\n\tstr = str + \"<td>\" + ((able_delete)?\"<a onclick=\\\"return LoadHistoryDesc('\" + id + \"');\\\" href='#modal_edit_timeline_desc' data-toggle='modal' >Edit</a>\":\"\") + \"</td>\";\r\n str += \"</tr>\";\r\n\r\n \r\n \r\n$(\"#\" + TAB_TIMELINE_TABLE_HISTORY + \" tr:last\").after(str);\r\n\r\n}", "function addStopToHistoryTable(position) {\n latitude = position.coords.latitude;\n longitude = position.coords.longitude;\n stopTime = moment();\n insertRow(stopTime, latitude + ' & ' + longitude, stopTime - startTime, false);\n stopButtonsUpdate();\n}", "function recordHistoryMulti (op, id_list) {\r\n let action;\r\n if (op == \"move\") action = HNACTION_BKMKMOVE;\r\n else if (op == \"remove\") action = HNACTION_BKMKREMOVE;\r\n else if (op == \"remove_tt\") action = HNACTION_BKMKREMOVETOTRASH;\r\n// else if (op == \"create\") action = HNACTION_BKMKCREATE;\r\n historyListAdd(curHNList, action, true, id_list);\r\n}", "function addStartToHistoryTable(position) {\n latitude = position.coords.latitude;\n longitude = position.coords.longitude;\n startTime = moment();\n insertRow(startTime, latitude + ' & ' + longitude, 0, false);\n startButtonsUpdate();\n}", "function createTable(saveTab) {\n // increment the count of tabs\n count++;\n\n // check if the input is valid\n if(!($(\"#inputs\").valid())) {\n return;\n }\n // create a tab element\n var list_item = $(\"<li></li>\");\n // create a delete button that is found at the top of\n // each tab element\n var delete_btn = $(\"<div>\");\n delete_btn.attr(\"class\", \"deleteBtn\");\n delete_btn.attr(\"data-tab\", \"tab-\" + count);\n delete_btn.text(\"X\");\n\n list_item.append(delete_btn);\n\n var href=$(\"<a></a>\");\n href.attr(\"href\", \"#tab-\" + count);\n href.text(\"Tab \" + count);\n list_item.append(href);\n $(\"#tabs ul\").append(list_item);\n $(\"#tabs\").append($(\"#table-\" + count));\n\n // get the values of each inputs\n var first = parseInt($(\"#firstInput\").val());\n var second = parseInt($(\"#secondInput\").val());\n var third = parseInt($(\"#thirdInput\").val());\n var fourth = parseInt($(\"#fourthInput\").val());\n\n\n // Create our table\n var tableContainer = $(\"<div>\");\n tableContainer.attr(\"id\", \"tab-\" + count);\n tableContainer.append(\"<table>\");\n var table = tableContainer.find(\"table\");\n\n // if one of the numbers is larger than the other\n // then I just reverse their order.\n if(first > second) {\n var temp = first;\n first = second;\n second = temp;\n }\n if(third > fourth) {\n var temp = third;\n third = fourth;\n fourth = temp;\n }\n\n for(i = first-1; i <= second; i++) {\n // Create the rows each iteration\n var tr = $(\"<tr>\");\n for(j = third-1; j <= fourth; j++) {\n var td = \"<td>\" + i*j + \"</td>\"\n // If it's the first block, leave it blank\n if(i == first-1 && j == third-1) {\n var td = \"<td></td>\";\n }\n // if we're creating a row, fill that td with j\n else if(i == first -1) {\n var td = \"<th>\" + j + \"</th>\"\n }\n //if were creating a column, fill that td with i\n else if(j == third -1) {\n var td = \"<td>\" + i + \"</td>\"\n }\n tr.append(td);\n }\n table.append(tr);\n }\n\n // Creating a checkbox element within a div\n var checkbox = $(\"<div>\");\n checkbox.attr(\"class\", \"checkbox\");\n // used for deleting tables when doing multiple delete\n checkbox.attr(\"data-checkbox\", \"tab-\" + count);\n // creating a label\n var label = $(\"<label>\");\n label.text(\"Tab \" + count);\n\n checkbox.append(label);\n var input = $(\"<input type='checkbox'>\");\n input.attr(\"data-checkbox\", \"tab-\" + count);\n checkbox.append(input);\n var checkboxes = $(\".checkboxes\");\n checkboxes.append(checkbox);\n // if there aren't any tables then don't show this section\n if($(\".checkbox\").length > 0) {\n $(\".deleteMultiple\").show();\n } else {\n $(\".deleteMultiple\").hide();\n }\n // append the table to the tab\n $(\"#tabs\").append(tableContainer);\n // we need to refresh the tabs so that they aren't out of date.\n $(\"#tabs\").tabs(\"refresh\");\n }", "function saveGuessHistory(guess) {\r\n guesses.push(guess);\r\n}", "function createLocalTables(db) {\n\tdb.execute('create table if not exists grouptable ( groupId integer primary key autoincrement, title varchar(255) not null)');\n\tdb.execute('create table if not exists feed ( feedId integer not null primary key autoincrement, dateAdded datetime default null, dateRemoved datetime default null, lastRead datetime default null, lastUpdated varchar(255) default null, title varchar(255) not null, type varchar(255) not null, url varchar(255) not null, userFeed varchar(255) default null, userProfile varchar(255) default null, groupId integer not null constraint groupId references grouptable(groupId) on delete cascade )');\n\tdb.execute('create table if not exists alturl ( urlId integer not null primary key autoincrement, url varchar(255) default null, feedId integer not null constraint feedId references feed(feedId) on delete cascade )');\n\tdb.execute('create table if not exists readtime ( readTimeId integer not null primary key autoincrement, readTime varchar(255) default null, feedId integer not null constraint feedId references feed(feedId) on delete cascade )');\n\tdb.execute('create table if not exists item ( itemId integer not null primary key autoincrement, guid varchar(255) not null, title varchar(255) not null, type varchar(255) default null, feedId integer not null constraint feedId references feed(feedId) on delete cascade )');\t\n\tdb.execute('create table if not exists event ( eventId integer not null primary key autoincrement, actionType varchar(255) not null, contextValue varchar(255) default null, contextValueType varchar(255) default null, dateTime datetime not null, description varchar(255) default null, duration double default null, followedLink varchar(255) default null, ipAddress varchar(255) default null, other varchar(255) default null, sessionId varchar(255) default null, tags varchar(255) default null, userDiscipline varchar(255) default null, userEmail varchar(255) default null, userName varchar(255) default null, voteLink varchar(255) default null, xfn varchar(255) default null, itemId integer not null constraint itemId references item(itemId) on delete cascade ) ');\n\tdb.execute('create table if not exists relateddata ( relatedDataId integer not null primary key autoincrement, content varchar(255) default null, describingSchema varchar(255) default null, name varchar(255) default null, eventId integer not null constraint eventId references event(eventId) on delete cascade )');\n}", "function createTableUsingSched(a, realTN, finGPW, finWTPO) {\n $('#leagueSched').empty();\n //FIRST COL SPECIAL\n var htmlrow0 = document.createElement('tr');\n for (var col = 0; col < (finWTPO + 2); col++) {\n var htmlcol = document.createElement('td');\n if (col == 0) {\n htmlcol.innerHTML = \"\";\n } else if (col == finWTPO + 1) {\n htmlcol.innerHTML = \"Playoffs\";\n } else {\n htmlcol.innerHTML = \"Week\" + col;\n }\n htmlrow0.appendChild(htmlcol);\n }\n document.getElementById(\"leagueSched\").appendChild(htmlrow0);\n\n //ALL OTHER COLs\n for (var row = 0; row < finGPW; row++) {\n var htmlrow = document.createElement('tr');\n var htmlcol = document.createElement('td');\n\n htmlcol.innerHTML = \"Game \" + (row + 1);\n htmlrow.appendChild(htmlcol);\n\n\n\n var winLoseInput = document.createElement('input');\n //teamsName.setAttribute('type', 'text');\n\n for (var col = 1; col < (finWTPO + 2); col++) {\n\n var htmlcol = document.createElement('td');\n if (col == finWTPO + 1) {\n htmlcol.innerHTML = \"Undertermined\";\n htmlrow.appendChild(htmlcol);\n } else {\n var battle = a[col - 1][row];\n var team1 = battle.substring(0, 1);\n var team2 = battle.substring(1, 2);\n //\n\n htmlcol.innerHTML = realTN[team1] + \" vs.\\n\" + realTN[team2];\n\n }\n htmlrow.appendChild(htmlcol);\n\n }\n\n document.getElementById(\"leagueSched\").appendChild(htmlrow);\n }\n}", "function HistoryEntry(variables) {\n this.timestamp = Date.now();\n this.variables = variables;\n}" ]
[ "0.7091575", "0.63410753", "0.62974286", "0.6253997", "0.6252541", "0.61758024", "0.6136654", "0.6086194", "0.60353076", "0.59864724", "0.5917377", "0.5894084", "0.5888483", "0.5887401", "0.5881616", "0.57965356", "0.57762706", "0.57762706", "0.57762706", "0.5772077", "0.57189274", "0.57080764", "0.57056886", "0.5682735", "0.5682735", "0.5682735", "0.56824315", "0.56800765", "0.56616116", "0.56529063", "0.56332666", "0.5630941", "0.5630366", "0.56167954", "0.5612848", "0.56058455", "0.5577074", "0.55752194", "0.55708766", "0.5559139", "0.55564684", "0.5526866", "0.5526087", "0.5525943", "0.5505019", "0.55033654", "0.5499751", "0.5497639", "0.5479559", "0.5475281", "0.5464062", "0.5462213", "0.5459867", "0.5439725", "0.54381824", "0.54287153", "0.54204345", "0.54198635", "0.5419228", "0.54129386", "0.5405624", "0.5403042", "0.5403015", "0.5399824", "0.53998226", "0.53987324", "0.53952664", "0.53934395", "0.5386581", "0.5379823", "0.536091", "0.5350682", "0.5337979", "0.53161263", "0.5312004", "0.5310269", "0.53061324", "0.5290516", "0.52856404", "0.52843803", "0.528438", "0.52822965", "0.5281749", "0.52786905", "0.52736634", "0.52724653", "0.5268116", "0.52622247", "0.52619755", "0.5248193", "0.5247929", "0.5246227", "0.5244404", "0.52421", "0.5238832", "0.5237005", "0.5233352", "0.52278", "0.52228415", "0.5221844", "0.52150774" ]
0.0
-1
Biggie Size Given an array, write a function that changes all positive numbers in the array to the string "big". Example: makeItBig([1,3,5,5]) returns that same array, changed to [1, "big", "big", 5].
function makeItBig(arr) { for(var i = 0; i < arr.length; i++) { arr[i] > 0 ? arr[i] = "big" : false; } return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function makeitbig(arr){\n for (var i=0;i<arr.length;i++){\n if(arr[i]>0){\n arr[i]=\"big\";\n }\n }\n return arr;\n}", "function Bigglesize(arr){\n for(var i=0; i<arr.length;i++){\n if(arr[i]>0){\n arr[i]='big';\n }\n }\n return arr;\n}", "function biggieSize(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n arr[i] = \"big\";\n }\n }\n return arr;\n}", "function makeItBig(arr){\n for(e in arr){\n if(arr[e] > 0){\n arr[e] = \"big\";\n }\n }\n return arr;\n}", "function MakeItBig(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n arr[i] = \"Big\";\n }\n }\n console.log(arr);\n }", "function biggieSize(array) {\n for (var num in array) {\n if (array[num] > 0) {\n array[num] = \"big\";\n }\n }\n return array;\n}", "function posNum(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] >= 0) {\n arr[i] = \"big\";\n }\n }\n return arr;\n}", "function numberToString(array)\n{\n for(var i =0; i <array.length; i++)\n {\n if(array[i]>=10)\n {\n array[i]=\"Big\";\n }\n if(array[i]<=5)\n {\n array[i]=\"small\";\n }\n console.log(array[i]);\n }\n console.log(\"\");\n}", "function biggieSize(arr){\n for(var i = 0; i <= arr.length; i++){\n if(arr[i] <= 0){\n console.log(arr[i])\n }\n else console.log(\"big\")\n }\n}", "function bigOrSmall(bigOrSmallArray){\n let answers = []\n for (i = 0; i < bigOrSmallArray.length; i++){\n if (bigOrSmallArray[i] >= 100){\n answers.push(`big`)\n } else {\n answers.push(`small`)\n }\n } return answers;\n }", "function stringy(size) {\n\tvar output = \"\"\n\tfor (i =0; i < size; i++) {\n\t\tif(i%2 == 0) {\n\t\t\toutput += 1\n\t\t} else {\n\t\t\toutput += 0\n\t\t};\n\t};\n\treturn output;\n}", "function stringy(size) {\n\tstring = \"1\";\n\tfor (var i = size.length - 2; i >= 0; i--) {\n\t\tif (string.endsWith(1)){\n\t\t\tstring.push(0);\n\t\t} else {\n\t\t\tstring.push(1);\n\t\t}\n\t}\n\treturn string;\n}", "function stringy(size){\n let str = '1';\n for(let i = 2; i <= size; i++){\n i % 2 ? str += '1' : str += '0';\n }\n return str;\n}", "function stringy(size) {\n return size%2===0? '10'.repeat(size/2): '10'.repeat(size/2)+'1'\n}", "function scaleArrayReplace(array, numToScale) {\n for (var i in array) {\n array[i] = array[i] * numToScale;\n }\n return array;\n}", "function makeSmall(bigNum) {\n\tvar sub = bigNum - 100;\n\tvar small = bigNum * 1;\n\tvar zero = bigNum * 0;\n\tfunction addNum(smNum) {\n\t\treturn smNum + (sub - small) * zero;\n\t}\nreturn addNum;\n}", "function numberToString(array) {\n for (let i = 0; i < array.length; i++) {\n if(array[i] < 0){\n array[i] =\"DOJO\";\n }\n \n }\n return array;\n}", "function superSize(num){\n return +[...String(num)].sort((a, b) => b - a).join(\"\");\n}", "function stringy(size){\n let string = \"\";\n for(i = 0; i<size; i++){\n if(i % 2 === 0){\n string += 1;\n }else{\n string += 0;\n }\n }\n return string;\n}", "function heavyDuty(index) { \n const bigArray = new Array(7000).fill('😊') // we are creating a big array\n console.log('created') // added console log string\n return bigArray[index] \n}", "function big_word(array) {\n var longest_words = '';\n var current_words = '';\n for (var i=0; i<array.length; i++) {\n current_words = array[i];\n if (current_words.length > longest_words.length) {\n longest_words = current_words;\n }\n }\n return longest_words;\n}", "function stringItUp(arr){\r\n const result = arr.map(function(num){\r\n return num * 1;\r\n });\r\n return result;\r\n}", "function Fit(arr){\n if(arr[0] > arr.length){\n console.log(\"Too Big!\");\n }\n else if(arr[0] < arr.length){\n console.log(\"too small!\");\n }\n else{console.log(\"Just Right!\");}\n }", "function heavyDuty() {\n const bigArray = new Array(7000).fill('😊')\n return bigArray // return big array\n}", "function numbstring(arr){\n\n for (i=0;i<arr.length;i++){\n if(arr[i]<0){\n arr[i]=\"Dojo\"\n }\n }\n\n return arr;\n\n}", "function changeNum(arr) {\n for (let i = 0; i < arr.length; i++) {\n if (Number(arr[i].innerText) > 10000000) {\n let tenMillion = Math.floor((arr[i].innerText) / 10000000)\n arr[i].innerText = `$${tenMillion}千萬`\n } else if (Number(arr[i].innerText) > 100000) {\n let tenThousand = Math.floor((arr[i].innerText) / 10000)\n arr[i].innerText = `$${tenThousand}萬`\n } else {\n let e = `$${arr[i].innerText}`\n arr[i].innerText = e\n }\n }\n}", "function megaFriend(bigword) {\n var word = \"\";\n for (var i = 0; i < bigword.length; i++) {\n if (word.length < bigword[i].length) {\n word = bigword[i];\n }\n }\n return word;\n}", "function thirteen(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = \"Dojo\"\n }\n }\n return arr;\n}", "function heavyDuty() {\n const bigArray = new Array(7000).fill('😊')\n return bigArray\n}", "function abcde(x) {\n for (var i = 0; i < x.length; i++) {\n if (x[i] > 5) {\n x[i] = \"Coding\";\n } else if (x[i] < 0) {\n x[i] = \"Dojo\";\n }\n }\n return x;\n}", "function changeCompletely(element, index, array){\n\narray[index]=Math.floor(Math.random() * 100 +2) .toString()+\n`${array [index]}s!!!`;\n\n}", "function stringItUp(arr){\r\n return arr.map(num => num.toString())\r\n }", "function numToString(arr) {\n for (var i = 0; i < arr.length; i++) {\n if(arr[i] < 0) {\n arr[i] = \"Dojo\";\n }\n }\n return arr;\n}", "function fix(v, size) {\n return v < 0 ? (size + 1 + v) : v;\n}", "function numToString(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 'Dojo';\n }\n }\n return arr;\n}", "function stringItUp(arr){\n return arr.map(number => String(number))\n}", "function stringItUp(arr){\n return arr.toString()\n}", "function superSize(num){\n var numArray = [];\n var output = '';\n\n for (let i = 0; i < num.toString().length; i++) {\n numArray.push(parseInt(num.toString().charAt(i)));\n }\n\n var sorted = numArray.sort();\n\n for (let x = sorted.length - 1; x >= 0; x--) {\n output += sorted[x];\n }\n\n return parseInt(output);\n}", "function filterLongWord (array, int) {\n var longWord = []\n for (var i = 0; i < array.length; i++) {\n if (array[i].length > int) {\n longWord.push(array[i])\n }\n }\n return longWord\n}", "function stringItUp(arr) {\n const result = arr.map(function(num){\n return num.toString();\n });\n return result;\n}", "function numToStrings(array) {\n return array.map(el => el + '')\n }", "function makeSmaller() {\n\n}", "function fakeBin(x) {\n let result = \"\";\n for (i = 0; i < x.length; i++) {\n x[i] < 5 ? (result += 0) : (result += 1);\n return result;\n }\n}", "function thingamajig(size) {\n\tvar facky = 1;\n\tclunkCounter = 0;\n\tif(size == 0) {\n\t\tdisplay(\"clanck\");\n\t} else if(size == 1) {\n\t\tdisplay(\"thunk\");\n\t} else {\n\t\twhile(size > 1) {\n\t\t\tfacky = facky * size;\n\t\t\tsize = size - 1;\n\t\t}\n\t\tclunk(facky)\n\t}\n}", "function longWord(array) {\n return array;\n}", "function scaleArray(arr,num){\n\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tarr[i] = arr[i] * num;\n\t}\n\tconsole.log(arr)\n}", "function _normalize(size) {\n var hasBigNumbers = false;\n size.forEach(function (value, index, arr) {\n if (type.isBigNumber(value)) {\n hasBigNumbers = true;\n arr[index] = value.toNumber();\n }\n });\n return hasBigNumbers;\n }", "function _normalize(size) {\n var hasBigNumbers = false;\n size.forEach(function (value, index, arr) {\n if (type.isBigNumber(value)) {\n hasBigNumbers = true;\n arr[index] = value.toNumber();\n }\n });\n return hasBigNumbers;\n }", "function _normalize(size) {\n var hasBigNumbers = false;\n size.forEach(function (value, index, arr) {\n if (type.isBigNumber(value)) {\n hasBigNumbers = true;\n arr[index] = value.toNumber();\n }\n });\n return hasBigNumbers;\n }", "function _normalize(size) {\n var hasBigNumbers = false;\n size.forEach(function (value, index, arr) {\n if (type.isBigNumber(value)) {\n hasBigNumbers = true;\n arr[index] = value.toNumber();\n }\n });\n return hasBigNumbers;\n }", "function heavyDuty(index) { // index\n const bigArray = new Array(7000).fill('😊')\n return bigArray[index] // I can access big array by the index number\n}", "function testSize(num) {\n if (num < 5) {\n return \"tiny\";\n } else if (num < 10) {\n return \"small\";\n } else if (num < 15) {\n return \"medium\";\n } else if (num < 20) {\n return \"large\";\n } else {\n return \"huge\";\n }\n}", "function stringItUp(arr){\n stringArr = arr.map(function(num){\n return num.toString()\n })\n console.log(stringArr)\n}", "function numStr(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] = 'Dojo';\n }\n }\n return arr;\n}", "function scale(arr,num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num\n }\n console.log(arr)\n}", "function changeCompletely(element, index, array) {\n array[index] = Math.floor(Math.random() * 100 + 2).toString() + ` ${array[index]}s!!!`;\n}", "function coding(x) {\n for (var i = 0; i < x.length; i++) {\n if (x[i] > 0) {\n x[i] = \"Coding\";\n }\n }\n return x;\n}", "function ScaleA(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num;\n }\n console.log(arr);\n}", "function scale(arr, num){\n for (var i = 0; i < arr.length; i++){\n arr[i] *= num;\n }\n return arr;\n}", "function whatsNext(arr) {\n var BigNumber = require('bignumber.js');\n arr = arr.map(v => new BigNumber(v));\n var len = arr.length;\n if (len % 2 == 0) {\n var zero = arr.pop(),\n ones = arr.pop() || new BigNumber(0),\n zero2 = arr.pop() || new BigNumber(0);\n arr.push(zero2.minus(1), new BigNumber(1), zero.plus(1), ones.minus(1));\n } else {\n var ones = arr.pop(),\n zero = arr.pop() || new BigNumber(0);\n arr.push(zero.minus(1), new BigNumber(1), new BigNumber(1), ones.minus(1));\n }\n if (arr[0] < 1) arr.shift();\n if (arr[arr.length - 1] < 1) arr.pop();\n \n for (var i = 1; i < arr.length; )\n if (arr[i].toString() == \"0\")\n arr.splice(i - 1, 3, arr[i - 1].plus(arr[i + 1]));\n else\n i++;\n\n console.log(arr.length);\n console.log(arr.map(n => n.toString()).join` `);\n}", "function scaleArray(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] *= num\n }\n return arr\n}", "function numToString(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n if(arr[i] <= 0) {\n newArr.push(\"Dojo\");\n }\n else {\n newArr.push(i);\n }\n }\n return newArr;\n}", "function testSize(num) {\n\tif(num < 5) {\n\t\treturn \"tiny\";\n\t} else if(num < 10) {\n\t\treturn \"small\";\n\t} else if(num < 15) {\n\t\treturn \"medium\";\n\t} else if(num < 20) {\n\t\treturn \"large\";\n\t} else {\n\t\treturn \"Huge\";\n\t}\n}", "function bestFit(arr){\n for (var i = 0; i < arr.length; i++){\n if (arr[0] > arr.length){\n console.log(\"Too Big!\");\n }\n if (arr[0]<arr.length){\n console.log(\"Too Small!\");\n }\n if (arr[0] == arr.length) {\n console.log(\"Just Right!\")\n }\n }\n}", "function makeArrayOfPossTimes (bigArray) {\n\tbigArray.forEach(function(item){\n\t\tif (uniqueTimesArray.indexOf(item) === -1) {\n\t\t\tuniqueTimesArray.push(item);\n\t\t}\n\t});\n \t// console.log(\"times array\", uniqueTimesArray);\n\tsortTimes(uniqueTimesArray);\n}", "function scaleArr(arr, num){\n for(var i = 0; i < arr.length; i++)\n arr[i] *= num;\n return arr;\n}", "function testSize(num) {\n let output = \"\";\n if (num < 5) {\n output = \"Tiny\";\n } else if (num < 10) {\n output = \"Small\";\n } else if (num < 15) {\n output = \"Medium\";\n } else if (num < 20) {\n output = \"Large\";\n } else {\n output = \"Huge\";\n }\n return output;\n}", "function makeBigger() {\n\n}", "static suffixArray(array, suffix){\n return array.map(i => i + suffix);\n }", "function numberSize(numbers) {\n var smallNumbers = [];\n var mediumNumbers = [];\n var largeNumbers = [];\n for (i = 0; i < numbers.length; i++)\n if (numbers[i] < 100) {\n smallNumbers.push(numbers[i])\n } else if (numbers[i] > 100 && numbers[i] <= 1000) {\n mediumNumbers.push(numbers[i])\n } else {\n largeNumbers.push(numbers[i])\n }\n console.log('These are my small numbers: ' + smallNumbers + '. These are my medium numbers: ' + mediumNumbers + '. These are my large numbers: ' + largeNumbers + '.');\n}", "function putBigArray(bigArray) {\n if (bigArray == null) {\n bigArray = loadBigArray()\n }\n for (let i = 0; i < bigArray.length; i++) {\n if (bigArray[i] != null) {\n const toPut = new Array(19)\n toPut[0] = i\n for (let j = 0; j < 6; j++) {\n if (bigArray[i][j] != null) {\n for (let k = 0; k < 3; k++) {\n toPut[1 + 3 * j + k] = bigArray[i][j][k]\n }\n }\n }\n Logger.log('at not string ' + (i + 3) + ', put: ' + toPut)\n // Logger.log('string?: ' + (i + 3))\n imageUrlsSheet.getSheets()[0].getRange(i + 3, 1, 1, 19).setValues([toPut])\n }\n }\n}", "function scaleArray(arr,num){\n for( var i=0;i<arr.length;i++){\n arr[i]=arr[i]*num;\n }\n return arr;\n}", "function makeItBig(string) {\n console.log(string.toUpperCase());\n}", "function testSize(num) {\n // Only change code below this line\n if (num < 5) {\n return \"Tiny\"\n } else if (num < 10) {\n return \"Small\"\n } else if (num < 15) {\n return \"Medium\"\n } else if (num < 20) {\n return \"Large\"\n } else if (num >= 20) {\n return \"Huge\"\n } else {\n return \"Change Me\";\n }\n // Only change code above this line\n}", "function scaleTheArray(arr, num) {\n for (var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * num;\n }\n return arr;\n}", "function zfill(number, size) {\n number = number.toString();\n while (number.length < size) {\n number = '0' + number;\n }\n return number;\n }", "function capMe(arr) {\n const cap = arr.map(x => x[0].toUpperCase() + \n x.substring(1, x.length).toLowerCase());\n return cap;\n}", "function bigInt2str(x,base) {\n var i,t,s=\"\";\n\n if (s6.length!=x.length) \n s6=dup(x);\n else\n copy_(s6,x);\n\n if (base==-1) { //return the list of array contents\n for (i=x.length-1;i>0;i--)\n s+=x[i]+',';\n s+=x[0];\n }\n else { //return it in the given base\n while (!isZero(s6)) {\n t=divInt_(s6,base); //t=s6 % base; s6=floor(s6/base);\n s=digitsStr.substring(t,t+1)+s;\n }\n }\n if (s.length==0)\n s=\"0\";\n return s;\n }", "function removeShorterStrings(arr, val){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n if(arr[i].length > val){\n newArr.push(arr[i]);\n }\n }\n arr = newArr;\n return arr;\n}", "function numbertostring(arr)\r\n{\r\n\tfor(var i=0;i<arr.length;i++)\r\n\t{\r\n\t\tif(arr[i]<0)\r\n\t\t{\r\n\t\t\tarr[i]=\"Dojo\";\r\n\t\t}\r\n\t}\r\n\tconsole.log(\"new arr\",arr);\r\n\t\r\n}", "function divadeThanAdd(arrToChange) {\n var newArrBig = [];\n for (var i = 0; i < arrToChange.length; i++) {\n if (arrToChange[i] == 0) {\n arrToChange[i] = 20;\n newArrBig = arrToChange;\n } else {\n arrToChange[i] = ((arrToChange[i] / 2) + 5);\n newArrBig = arrToChange;\n }\n } return newArrBig;\n}", "function num2Str(arr){\n var d = \"Dojo\";\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = d;\n }\n }\n return arr;\n}", "function shorten(x)\n{\nreturn(x);\n}", "function equalize(array) {\n return array.map((num, ind, arr) => {\n return (String(num - arr[0])).replace(/^(\\d)/, '+$1');\n });\n}", "function numberSuffix (a){\n\n var array1 = [];\n var array2 = [];\n var array3 = [];\n result = \"\";\n\n for (var i = 20; i <= 100000000; i+=10){\n array1[array1.length] = i + 1; \n }\n\n for (var i = 20; i <= 100000000; i+=10){\n array2[array2.length] = i + 2; \n }\n\n for (var i = 20; i <= 100000000; i+=10){\n array3[array3.length] = i + 3; \n }\n\n if(array1.includes(a)){\n result = a + \"st\";\n \n } else if (array2.includes(a)){\n result = a + \"nd\";\n } else if (array3.includes(a)){\n result = a + \"rd\";\n } else if(a === 1){\n result = a + \"st\";\n } else if(a === 2){\n result = a + \"nd\";\n } else if(a === 3){\n result = a + \"rd\";\n } else if(a > 3){\n result = a + \"th\";\n }\n\n return result;\n}", "function heavyDuty2() {\r\n const bigArray = new Array(7000).fill('😄');\r\n console.log('created!!!!');\r\n return function (item) {\r\n console.log(bigArray[item]);\r\n };\r\n}", "function j(a){return a.map(function(a){return\" \"+a})}", "function stringItUp(arr){\n var newArr = arr.map(function(item){\n return item.toString()\n })\n console.log(newArr)\n}", "function makeSquare (aSize) {\n let strToReturn = ''\n if (aSize > 1) {\n for (let i = 0; i < aSize; i++) {\n for (let j = 0; j < aSize; j++) {\n strToReturn = strToReturn + '*' \n }\n if (i < (aSize - 1)) {\n strToReturn = strToReturn + '\\n'\n }\n }\n } else {\n if (aSize === 1) {\n return '*'\n } else {\n return ''\n }\n }\n return strToReturn\n}", "function fakeBin(x) {\n return x.split('').map(n => n < 5 ? 0 : 1).join('');\n}", "function heavyDuty(index) { \n const bigArray = new Array(7000).fill('😊') // we are create this memory\n console.log('created')\n return bigArray[index] \n}", "function heavyDuty(index) { \n const bigArray = new Array(7000).fill('😊') // we are create this memory\n console.log('created')\n return bigArray[index] \n}", "function getBigNum(names){\n var larger = names[0];\n for(var i=0; i<=names.length; i++){\n var element = names[i];\n if (element >larger){\n larger = element;\n }\n }\n return larger;\n}", "function testSize(num) {\n if (num < 5) {\n return \"Tiny\";\n } else if (num < 10) {\n return \"Small\";\n } else if (num < 15) {\n return \"Medium\";\n } else if (num < 20) {\n return \"Large\";\n } else {\n return \"Huge\";\n }\n}", "function scaleArray(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num;\n }\n return arr;\n}", "function buildArray(int) {\nvar stringsArray = [];\nint * stringsArray.fill(\"Kiwi\") \n}", "function fitFirst(arr){\n if (arr[0] > arr.length){\n console.log(\"Too big!\")\n }else if (arr[0] < arr.length){\n console.log(\"Too small!\")\n }else{\n console.log(\"Just right!\")\n }\n}", "function bigInt2str(x, base) {\n var i, t, s = \"\";\n\n if (s6.length != x.length)\n s6 = dup(x);\n else\n copy_(s6, x);\n\n if (base == -1) { //return the list of array contents\n for (i = x.length - 1; i > 0; i--)\n s += x[i] + ',';\n s += x[0];\n }\n else { //return it in the given base\n while (!isZero(s6)) {\n t = divInt_(s6, base); //t=s6 % base; s6=floor(s6/base);\n s = digitsStr.substring(t, t + 1) + s;\n }\n }\n if (s.length == 0)\n s = \"0\";\n return s;\n }", "function filterLongWords(array,iVal){\n\n return array.filter(arr=>arr.length > iVal).join(',');\n\n}", "function scaleArray(arr, num) {\n for(var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * num;\n }\n return arr;\n}" ]
[ "0.80811465", "0.7931772", "0.7855325", "0.76918864", "0.767223", "0.7634122", "0.66327494", "0.66052264", "0.63399214", "0.5935498", "0.5913743", "0.59018666", "0.58811533", "0.58640766", "0.5807524", "0.5788728", "0.5755813", "0.56282896", "0.562583", "0.5596072", "0.55814755", "0.55786824", "0.5485296", "0.54526156", "0.5380993", "0.5347489", "0.5330818", "0.5329005", "0.5322551", "0.5321546", "0.5312092", "0.5293784", "0.5271128", "0.5259145", "0.52368826", "0.5214782", "0.5189185", "0.51692146", "0.5156307", "0.5151779", "0.51374435", "0.5133915", "0.51324284", "0.51323456", "0.51293284", "0.5123643", "0.5123554", "0.5123554", "0.5123554", "0.5123554", "0.5123499", "0.5122563", "0.5118028", "0.50964725", "0.50819546", "0.5079002", "0.5072435", "0.5070936", "0.50696754", "0.5063413", "0.5060672", "0.50516254", "0.50406975", "0.503936", "0.50324947", "0.5030993", "0.50287336", "0.50163907", "0.5013999", "0.5013649", "0.50083035", "0.49919", "0.49883437", "0.49854648", "0.49851608", "0.49732897", "0.49639875", "0.49612677", "0.4960387", "0.49599025", "0.49540484", "0.49523658", "0.49490836", "0.49436763", "0.4938079", "0.4937776", "0.49279684", "0.49271113", "0.49216017", "0.49119976", "0.49047303", "0.49047303", "0.49001414", "0.48903653", "0.48899457", "0.48887134", "0.48872742", "0.48871127", "0.48825198", "0.48767185" ]
0.77790546
3
console.log(makeItBig([1,3,5,5])); Challenge 2 Print Low, Return High Create a function that takes in an array of numbers. The function should print the lowest value in the array, and return the highest value in the array.
function printLowReturnHigh(arr) { var lowest = arr[0]; var hightest = arr[0]; for(var i = 0; i < arr.length; i++) { if(lowest > arr[i]) { lowest = arr[i]; } if(hightest < arr[i]) { hightest = arr[i]; } } console.log(lowest); return hightest; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function PrintLowReturnhigh(arr) {\n\tvar min=arr[0], max=arr[0];\n\tfor (var i = 0; i <arr.length; i++) {\n\t\tif (arr[i]>max) {\n\t\t\tmax=arr[i];\n\t\t} \n\t\tif (arr[i]<min) {\n\t\t\tmin=arr[i];\n\t\t}\n\t}\n\tconsole.log(min);\n\treturn max;\n}", "function printLowReturnHigh(arr){\n var low = arr[0];\n var high = arr [0];\n for (var i = 0; i < arr.length; i++){\n if(arr[i] > high){\n high = arr[i];\n }\n if(arr[i] < low){\n low = arr[i];\n }\n }\n console.log(low);\n return high;\n}", "function printLow_returnHigh(arr){\n var high = arr[0];\n var low = arr[0];\n\n for(let i = 1; i < arr.length; i++){\n if(high < arr[i]) high = arr[i];\n if(low > arr[i]) low = arr[i];\n }\n console.log(\"Low\", low);\n return high;\n}", "function printLowReturnHigh(array) {\n var lowestVal = array[0];\n var highestVal = array[0];\n\n for (var num in array) {\n if (array[num] > highestVal) {\n highestVal = array[num];\n } \n else if (array[num] < lowestVal) {\n lowestVal = array[num];\n }\n }\n console.log(\"Lowest value: \" + lowestVal);\n return highestVal;\n}", "function printLowReturnHigh(arr){\n let min = 0;\n let max = 0;\n for(let i = 0; i < arr.length; i ++){\n if(arr[i] > max){\n max = arr[i];\n }\n if(arr[i] < arr[i] + 1){\n min = arr[i]; \n }\n }\n console.log(min);\n return max; \n}", "function printLowReturnHigh(arr){\n var low = arr[0]\n var high =arr[0] \n for(var i = 0; i <= arr.length; i++){\n if(arr[i] > high){\n high = arr[i]\n }\n if(arr[i] < low){\n low = arr[i]\n }\n }\n console.log(low)\n return high\n}", "function printlowreturnhigh(arr){\n var min = arr[arr.length - 1];\n var max = arr[arr.length - 1];\n for(var i = arr.length - 1; i >= 0; i--){\n if(min > arr[i]){\n min = arr[i];\n }\n if(max < arr[i]){\n max = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function lowHigh(arr) {\n var min = arr[0];\n var max = arr[0];\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < min) {\n min = arr[i];\n } else if (arr[i] > max) {\n max = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function lowHigh(arr){\n let min = arr[0]\n let max = arr[0]\n for(let i = 1; i < arr.length; i++){\n if (arr[i] < min){\n min = arr[i]\n }\n if (arr[i] > max){\n max = arr[i]\n }\n }\n console.log(min)\n return max\n}", "function printlow(arr){\n var low=arr[0];\n var high=arr[0];\n for(var i=0;i<arr.length;i++){\n if(arr[i]<low){\n low=arr[i];\n }else{\n high=arr[i];\n }\n }\n console.log(low);\n return high;\n\n}", "function printHigh(arr) {\n var low = arr[0]; // 2\n var high = arr[0]; // 2\n\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] < low) {\n low = arr[i];\n } else if (arr[i] > high) {\n high = arr[i];\n }\n }\n console.log(low);\n return high;\n}", "function lowHigh(arr)\n{\n var lowNum=arr[0]\n var highNum=arr[0]\n for(var i=1; i<arr.length; i++)\n {\n if(arr[i]<lowNum)\n {\n lowNum=arr[i]\n }\n if(arr[i]>highNum)\n {\n highNum=arr[i]\n }\n }\n console.log('Low num is ' + lowNum)\n return(highNum)\n}", "function lowhighvalue(arr) {\n var lowest = arr[0];\n var highest = arr[0];\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < lowest){\n lowest = arr[i];\n }\n if (arr[i] > highest){\n highest = arr[i];\n }\n }\n console.log(lowest);\n return highest;\n}", "function printReturn(arr) {\n\n var max = arr[0];\n var min = arr[0];\n\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n if (arr[i] < min) {\n min = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function Max_Finder() {\r\n let numbers = EntryCheckForManyNumbers();\r\n let max = numbers [0]; \r\n let min = numbers [numbers.length-1] ;\r\n for (let i = 0; i < numbers.length; i++){\r\n if (max < numbers[i]) {\r\n max = numbers[i];\r\n }\r\n if ( min > numbers[i]) {\r\n min = numbers[i];\r\n }\r\n } \r\n //console.log(numbers);\r\n // console.log(min, max);\r\n return max;\r\n \r\n }", "function LowHighvalue(arr){\n var low = arr[0];\n var high = arr[0];\n for(var i=0;i<arr.length;i++){\n if(low>arr[i]){\n low = arr[i];\n }\n if(high<arr[i]){\n high = arr[i];\n }\n\n }\n console.log(low);\n return high;\n}", "function lowHigh(arr){\nvar lowNum = arr[0];\nvar highNum = arr[0];\n\n\tif (arr.length < 2) {\n\t\tconsole.log(\"The array needs more numbers!\");\n\t} \n\n\telse {\n\t\tfor(var num = 0; num < arr.length; num++) {\n\t\t\tif (arr[num] > highNum){\n\t\t\t\thighNum = arr[num];\n\t\t\t\t}\n\t\t\telse if (arr[num] < lowNum){\n\t\t\t\tlowNum = arr[num];\n\t\t\t}\n\t\t}\n\t}\n\tconsole.log(\"Lowest number: \" +lowNum);\n\treturn highNum;\n}", "function printReturn (array) {  \n var maximum = array[0];\n var minimum = array[0];\n for (var i = 0; i < array.length; i++){  \n if(array[i] > maximum){\n maximum = array[i];\n     } \n if(array[i] < minimum){\n minimum = array[i];\n }\n }\n console.log(minimum);\n console.log(maximum);\n return maximum;\n}", "function Min_Finder() {\r\n let numbers = EntryCheckForManyNumbers();\r\n let max = numbers [0]; \r\n let min = numbers [numbers.length-1] ;\r\n for (let i = 0; i < numbers.length; i++){\r\n if (max < numbers[i]) {\r\n max = numbers[i];\r\n }\r\n if ( min > numbers[i]) {\r\n min = numbers[i];\r\n }\r\n } \r\n //console.log(numbers);\r\n //console.log(min, max);\r\n return min;\r\n }", "function highLow(arr){\n var max = arr[0];\n var min = arr[0];\n for(e in arr){\n if(arr[e] > max){\n max = arr[e];\n }\n if(arr[e] < min){\n min = arr[e];\n }\n }\n console.log(min);\n return max;\n}", "function PLRH(arr){\n var low = arr[0];\n var high = arr[0];\n for(var i = 1; i < arr.length; i++){\n if(arr[i] > high){\n high = arr[i];\n }\n if(arr[i] < low){\n low = arr[i];\n }\n }\n console.log(low);\n return high;\n }", "function func(arr) {\n var min = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] < min) {\n min = arr[i];\n }\n }\n console.log(min);\n\n var max = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n }\n return max;\n}", "function secondLowHigh(array) {\n var sortedArray = array.sort(function(a,b){\n return a-b\n });\n\n var secondLowest = sortedArray[1]; \n var secondHighest = sortedArray[sortedArray.length - 2];\n\n console.log(secondLowest);\n console.log(secondHighest);\n}", "function minAndMax(array) {\n\tvar smallest = array[0];\n\tvar largest = array[0];\n\tfor (var i=0; i < array.length; i++) {\n\t\tif (array[i+1] > largest) {\n\t\t\tlargest = array[i+1];\n\t\t}\n\t}\n\tconsole.log(\"The largest number is \" + largest + \".\");\n\tfor (var i=0; i < array.length; i++) {\n\t\tif (array[i+1] < smallest) {\n\t\t\tsmallest = array[i+1];\n\t\t}\n\t}\n\tconsole.log(\"The smallest number is \" + smallest + \".\");\n}", "function findMaxMin() {\n numbers = [8, 6, 1, 3];\n console.log(`This max of the array is: ${Math.max(...numbers)}`);\n console.log(`This min of the array is: ${Math.min(...numbers)}`);\n}", "function findSmallest() {\n var a = arguments;\n if(a.length>0){\n var small=a[0];\n for(var i = 1; i<a.length;i++){\n if(small>a[i]){\n small=a[i];\n }\n }console.log(small)\n }\n else\n return console.log(Number.MIN_VALUE);\n}", "function highAndLowBestPractice(numbers){\n // ...\n numbers = numbers.split(' ').map(Number);\n var max = Math.max.apply(0, numbers);\n var min = Math.min.apply(0, numbers);\n return max + ' ' + min;\n}", "function highAndLow(numbers) {\r\n const arr = numbers.split(\" \"); //The numbers are split into an array\r\n let maxNum = arr[0];\r\n let minNum = arr[0];\r\n //We declare two variables to hold the highest and lowest value respectively\r\n\r\n for (let num of arr) {\r\n //We iterate through each num of the array\r\n if (Number(num) > maxNum) {\r\n maxNum = num;\r\n //If current number is greater than maxNum,it replaces it as the highest one.\r\n }\r\n\r\n if (Number(num) < minNum) {\r\n minNum = num;\r\n //If current number is less than maxNum,it replaces it as the lowest one.\r\n }\r\n }\r\n\r\n return maxNum + \" \" + minNum;\r\n\r\n //The result is returned with the highest and lowest numbers.\r\n}", "function findLargest (myArray) {\n var theLargestThing = myArray[0];\n for ( i = 1; i < myArray.length; i++){\n theLargestThing = largestOfTwo(theLargestThing,myArray[i]);\n }\n return (theLargestThing);\n}", "function higherInteger(highest, lowest){\n return integer.sort(highest-lowest)\n}", "function lowhigh(arr) {\n max = arr[0];\n min = arr[0];\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n if (arr[i] < min) {\n min = arr[i];\n }\n }\n return min, max;\n}", "function findMax(array) {\n}", "function large(arr){\nresult = arr.reduce((largest, elem)=>{\n if(elem > largest){\n return elem;\n }else{\n return largest }\n })\nreturn result;\n}", "function getLargest () {\n var largest = 0;\nfor (var i = 0; i < numbers.length; i++) {\n if (numbers[i] > largest) {\n largest = numbers[i];\n }\n}return largest;\n}", "function penult() {\n var arr = [1,2,3,4,5,6,7,8,9,10]\n var lowHigh = []\n var seclow = arr[1]\n lowHigh.push(seclow)\n var sechigh = arr.length - 1\n lowHigh.push(sechigh)\n return lowHigh\n}", "function SecondGreatLow(arr) { \n\tif (arr.length === 2){\n\t\tif(arr[0] > arr[1]) {\n\t\t\treturn arr[0] + \" \" + arr[1];\n\t\t} else {\n\t\t\treturn arr[1] + \" \" + arr[0];\n\t\t}\n\t} else {\n\t\tvar greatest = Math.max.apply(Math, arr);\n\t\tvar lowest = Math.min.apply(Math, arr);\n\t\tvar newArr = [];\n\t\tfor (var i = 0; i<arr.length; i++) {\n\t\t\tif (arr[i] !== greatest && arr[i] !== lowest){\n\t\t\t\tnewArr.push(arr[i]);\n\t\t\t}\n\t\t}\t\t\n\t\tconsole.log(newArr);\n\t\tif (newArr.length === 1){\n\t\t\treturn newArr + \" \" + newArr;\n\t\t} else {\n\t\t\tvar secondGreatest = Math.max.apply(Math, newArr);\n\t\t\tvar secondLowest = Math.min.apply(Math, newArr);\n\t\t\treturn secondLowest + \" \" + secondGreatest;\n\t\t}\n\t} \n}", "function findMax(array) {\n var highNum= 0; \n for (let i = 0; i < array.length; i++) {\n if (array[i] > highNum) {\n highNum = array[i];\n \n }\n \n }\n return highNum;\n }", "function lowestToHighest(arr) {\n arr.sort();\n return arr;\n}", "function printTheSmallest(numberArray){\n var lowestValue = numberArray[0];\n for (var i = 0; i < numberArray.length; i++){\n if (numberArray[i] < lowestValue) {\n lowestValue = numberArray[i];\n }\n }\n return lowestValue;\n}", "function highAndLow(numbers) {\n numbers = numbers.split(/ /g).map(n => parseInt(n));\n // let highest = numbers[0];\n // let lowest = numbers[0];\n // numbers.forEach(number => {\n // number > highest ? highest = number : number < lowest ? lowest = number : \"\";\n // });\n // console.log(`${highest} ${lowest}`);\n\n return `${Math.max.apply(0, numbers)} ${Math.min.apply(0, numbers)}`;\n}", "function maxMinusMin(arrayOfNumbers){\n //returns the difference of the maximum minus the minimum\n // create a max value, a min value and put into variable to rep max-min\n arrayOfNumbers.sort();// puts in order least to greatest\n var max = arrayOfNumbers[arrayOfNumbers.length-1];\n var min = arrayOfNumbers[0]\n var calcValue = max- min;\n return calcValue\n}", "function solve(args) {\r\n\r\n var length = args.splice(0, 1),\r\n array = args.splice(0, length),\r\n x = args,\r\n \t\tmin = 0,\r\n max = length - 1,\r\n result = -1,\r\n mid;\r\n\r\n while (min <= max) {\r\n mid = min + (max - min) / 2;\r\n mid = Math.floor(mid);\r\n\r\n \tif (+array[mid] > x) {\r\n max = mid - 1;\r\n } else if (+array[mid] < x) {\r\n min = mid + 1;\r\n } else {\r\n result = mid;\r\n break;\r\n }\r\n }\r\n\r\n\tconsole.log(result);\r\n}", "function maxfinder(numbers){\n let max = numbers[0]\n for(i=0; i<numbers.length; i++){\n if(numbers[i]>max){\n max = numbers[i]\n }\n }\n console.log(max)\n}", "function highAndLow(numbers) {\n numbers = numbers.split(\" \").map(Number);\n console.log('numbers:: ', numbers);\n console.log('max and min:: ', `${Math.max(...numbers)} ${Math.min(...numbers)}`);\n return `${Math.max(...numbers)} ${Math.min(...numbers)}`;\n\n\n}", "findSecondHighest() {\n \n }", "function runProgram(input){\n let input_arr = input.trim().split(\"\\n\")\n let array = input_arr[1].trim().split(\" \").map(Number)\n\n let low = 0\n let high = array.length - 1\n let min = array[0]\n while(low <= high){\n let mid = Math.floor(low + ((high - low) / 2))\n if(array[mid] < min){\n min = array[mid]\n high = mid - 1\n }\n else{\n low = mid + 1\n }\n }\n\n console.log(min)\n}", "function exercise2(num) {\n var large = 0;\n\n num.forEach(function(value) {\n if (value > large) {\n large = value;\n }\n });\n return large;\n }", "function findAndPrintMax(arr){\n let max = arr[0];\n for(let i=1; i<arr.length;i++){\n if (max < arr[i]) {\n max = arr[i];\n }\n }\n console.log(max);\n}", "function secLargest(array) {\n var firsLargest = 0\n var arr = array[0];\n for (var i = 0; i < array.length; i++) {\n var element = array[i];\n if (arr < element) {\n firsLargest = arr;\n arr = element\n }\n }\n return firsLargest\n\n}", "function maxOfArray(numbers) {\n numbers.sort((a, b) => b - a);;\n return numbers[0]\n\n\n}", "function highAndLow(numbers) {\n let nums = numbers.split(' ').map(Number)\n let high = nums[0]\n let low = nums[0]\n for (let i = 1; i < nums.length; i++) {\n if (nums[i] > high) {\n high = nums[i]\n }\n if (nums[i] < low) {\n low = nums[i]\n }\n }\n return high + ' ' + low\n}", "function highAndLow(test){\r\n let tempArray = test.split(\" \");\r\n let max = Math.max.apply(null,tempArray);\r\n let min = Math.min.apply(null,tempArray);\r\n return max + \" \"+ min}", "function largest_e(array){\n // Create a function that returns the largest element in a given array.\n // For example largestElement( [1,30,5,7] ) should return 30.\n var max = array[0];\n for(var i=1; i< array.length; i++){\n if (array[i]> max){\n max = array[i];\n }\n }\n return max\n\n}", "function PrintMaxOfArray(arr){\n}", "function ReturnArrayOf_MaxMin() {\r\n let numbers = EntryCheckForManyNumbers();\r\n let max = numbers [0]; \r\n let min = numbers [numbers.length-1] ;\r\n for (let i = 0; i < numbers.length; i++){\r\n if (max < numbers[i]) {\r\n max = numbers[i];\r\n }\r\n if ( min > numbers[i]) {\r\n min = numbers[i];\r\n }\r\n } \r\n let arrayFor_2_values = [];\r\n arrayFor_2_values.push(max);\r\n arrayFor_2_values.push(min);\r\n //console.log(numbers);\r\n //console.log(min, max);\r\n return arrayFor_2_values;\r\n }", "function findLoestValueAraay(numbers2){\n let lowest = numbers2[0];\n for(let j=0;j<numbers2.length;j++){\n const element = numbers2[j];\n if(element<lowest){\n lowest= element;\n }\n\n }return lowest;\n}", "function largestNumber(numbers) {\n\n }", "function findLargest(array) {\n larget = array[0]\n for(i = 1; i < array.length; i++) {\n if(array[i] > larget) {\n larget = array[i]\n }\n }\n return larget\n}", "function locateHigh(array) {\n return array.indexOf(highestNumber(array))\n}", "function findLow() {\n\n}", "function minMax(arr){\n var max = arr[0];\n var min = arr[0];\n for(var i = 1; i < arr.length; i++){\n if(max < arr[i]){\n max = arr[i];\n }\n if(min > arr[i]){\n min = arr[i];\n }\n }\nconsole.log(min)\nconsole.log(max)\n}", "function largest(array){\r\n\treturn Math.max.apply(Math,array);\r\n}", "static getMax2(array) {\n let max = -Infinity;\n for (let i = 0; i < array.length; i++) {\n if (array[i] > max) {\n max = array[i]\n }\n }\n return max\n }", "function findMaxAndMin(array) {\n var i;\n var maxElement = 0;\n var minElement = 0;\n for (i = 0; i < array.length; i++) {\n if (array[i] > maxElement && typeof array[i] == 'number') {\n maxElement = array[i]\n }\n if (array[i] < minElement && typeof array[i] == 'number') {\n minElement = array[i]\n\n\n }\n result = [minElement, maxElement];\n\n }\n return result;\n\n}", "function max(array){\n var tmp = array[0];\n for(var i = 0; i < array.length; i++){\n if (array[i] > tmp){\n tmp = array[i]\n }\n }\n return tmp\n}", "function getHighest($array){\n var biggest = Math.max.apply( null, $array );\n return biggest;\n}", "function abc(arr) {\n var max = arr[0];\n for (var i = 1; i < arr.length; i++) {\n if (max < arr[i]) {\n max = arr[i]\n }\n }\n return max;\n}", "function highAndLow1(numbers){\n numbers = numbers.split(' ');\n return `${Math.max(...numbers)} ${Math.min(...numbers)}`;\n}", "function findMinAndMax(value){\n value.sort(function (a, b) { return a - b });\n console.log(\"Min -> %d\\nMax -> %d\", value[0], value[value.length-1]);\n}", "function findMax(aNums) {\n var iMax = aNums[0];\n\nfor (var iCount = 0; iCount < aNums.length; iCount++) {\n// This part is important because it means the top overall grade will show\n if (iMax < aNums[iCount]) {\n iMax = aNums[iCount];\n }\n}\n return iMax;\n}", "function ex9(){\n\tvar ran = randomInt(100);\n\tconsole.log(\"Estratto: \"+ran);\n\tvar max = Number.MIN_VALUE;\n\tvar temp;\n\tvar array = [];\n\twhile(ran--){\n\t\ttemp = randomInt(100);\n\t\tif(temp > max)\n\t\t\tmax = temp;\n\t\tarray.push(temp);\n\t}\n\tconsole.log(\"Estratti: \"+array);\n\treturn max;\n}", "function s(nums) {\n let lo = 0;\n let hi = nums.length - 1;\n while (lo < hi) {\n const mid = Math.floor((hi + lo) / 2);\n if (nums[mid] > nums[hi]) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n\n return nums[lo];\n}", "function main() {\n arr = readLine().split(' ');\n arr = arr.map(Number);\n let sarr = []\n arr = arr.sort((a, b) => a-b)\n let sum = arr.reduce((accum, val) => accum+val,0)\n console.log(sum - Math.max(...arr), sum - Math.min(...arr))\n\n //console.log(Math.min(...sarr), Math.max(...sarr))\n}", "function findMax(arr){\n //sort the array\n //Math.max\n //array.reduce\n //use for loops and if statements\n //return Math.max(...arr);\n return arr.reduce(function(val, current){\n return Math.max(val, current);\n })\n\n}", "function highAndLow(numbers){\n numbers = numbers.split(' ');\n return `${Math.max(...numbers)} ${Math.min(...numbers)}`;\n}", "function maxProfit(arry) {\n\tvar dupe_arry = arry;\n\tvar n, high, low;\n\tvar max = 0;\n\tvar min = 100;\n\n\tfunction minMax(old_max, high, old_min, low) {\n\t\tif (high > old_max) {\n\t\t\tmax = high;\n\t\t}\n\t\tif (low < old_min) {\n\t\t\tmin = low;\n\t\t}\n\t}\n\n\tfor (i=0; i<dupe_arry.length;i++) {\n\t\t// Compare and find low/high\n\t\tif (dupe_arry[i] < n) {\n\t\t\tlow = dupe_arry[i];\n\t\t\thigh = n;\n\t\t\t// console.log('Low: ' + low + ', High: ' + high);\n\t\t}\n\t\telse if (dupe_arry[i] > n) {\n\t\t\thigh = dupe_arry[i];\n\t\t\tlow = n;\n\t\t\t// console.log('Low: ' + low + ', High: ' + high);\n\t\t}\n\t\telse if (dupe_arry[i] === n) {\n\t\t\t// console.log('Hold up, now! ' + dupe_arry[i] + ' is equal to ' + n);\n\t\t}\n\t\tminMax(max, high, min, low);\n\n\t\t// console.log('last number: ' + n + ' this number: ' + dupe_arry[i]);\n\t\t// console.log('-------');\n\t\t// console.log('new high: ' + max + ' new low: ' + min);\n\t\t// console.log('-------');\n\t\tn = dupe_arry[i];\n\t}\n\tconsole.log(max);\n\tconsole.log(min);\n}", "function find() {\n var array = [4, 6, 9, 7, 5].sort();\n var max = array[array.length - 1]\n var min = array[0]\n var newAr =Array.of(max,min)\n \n\n return newAr;\n}", "function getMax(array) {\r\n let larger = 0;\r\n\r\n if (array.length === 0) return undefined;\r\n\r\n //Version 1 - Simple\r\n for (const item of array) {\r\n larger = item > larger ? item : larger;\r\n }\r\n //return larger;\r\n\r\n //Version 2 - Reduce:\r\n return array.reduce((accumulator, current) => {\r\n const max = current > accumulator ? current : accumulator;\r\n return max;\r\n });\r\n}", "function maxNum(){\nvar largest = 0;\nfor (i=0; i<numbers.length; i++){\n if (numbers[i] > largest){\n largest = numbers[i];\n }\n}return largest;\n}", "function sortForHigh(){ \n// set value of highestScore to the sorted array lowest to highest (b-a)\nhighestScore = scores.sort(function(a,b){return b-a})\n//console log the value of highest score at index 0\nconsole.log('the highest score is', highestScore[0]) \n}", "function largest10(numArr){\n\n\n}", "function biggestInt(array){\n let max = array[0];\n for (var i=0; i<array.length; i++){\n if (max < array[i]) max = array[i];\n }\n return max;\n}", "function showMax (array) {\n let init = 0\n\n for(let i=0; i < array.length; i++) {\n if(array[i] > init) {\n init = array[i]\n }\n }\n\n return init\n}", "function peak(nums){\n for (let i = 0; i < nums.length; i++) {\n let element = nums[i];\n if(element > nums[i+1]){\n return(element)\n }\n }\n}", "function findMinAndMax(array) {\n var minValue = array[0];\n var maxValue = array[0];\n var = i;\n\n for (i = 1; i < array.length; i++) {\n currentElement = array[i];\n\n if (currentElement < minValue) {\n minValue = currentElement;\n\n }\n\n if (currentElement > maxValue) {\n maxValue = currentValue;\n\n }\n\n //i=1:minValue = 3, maxValue = 7\n } //i=2:minValue = 2, maxValue = 7\n //i=3:minValue = 1, maxValue = 7\n //i=4:minValue = 1 maxValue = 8\n //i=5:minValue = 1 maxValue = 8\n\n}", "function findMax(array) {\n maxValue = Math.max.apply(null, array);\n console.log(maxValue);\n}", "function printMaxOfArray(arr){\n var max = 0\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > max){\n max = arr[i]\n }\n }\n return arr\n}", "function maxOfArray(array){\n var highest = 0;\n\n for (var i = 0; i < array.length; i = i + 1){\n if (array[i] > highest){\n // console.log(array[i])\n highest = array[i];\n }\n }\n return highest;\n}", "function minAndMax(arr) {\n//declare max, min variables\n\tlet min = arr[0];\n let max = arr[0];\n let result = [1,2];\n let newArr = [];\n \n//for loop to iterate through given array\n for (let i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n if (arr[i] < min) {\n min = arr[i];\n } else if (arr[i] > max) {\n max = arr[i];\n }\n \n } // end for loop\n result[0] = min;\n result[1] = max;\n return console.log(result);\n \n \n /*\n newArr.push(arr[i]);\n // console.log(newArr);\n if (arr[i] < arr[i + 1]) {\n min = arr[i];\n } else {\n \tmax = arr[i];\n }\n console.log(min);\n\t\t*/\n\n \n}", "function max(arr){\n var highest = 0\n arr.forEach(function(num){\n if (num > highest){\n highest = num\n } \n });\n return highest;\n console.log(highest);\n}", "function max(array){\n var maxNumber = array[0];\n for (var index = 1; index < array.length; index++) {\n if (maxNumber < array[i]){\n maxNumber = array[i];\n }\n }\n return maxNumber;\n}", "function findMax(array) {\n let maxIs = array[0];\n\n for (val of array) {\n if (val > maxIs) {\n maxIs = val\n }\n }\n\n return maxIs;\n\n}", "function max(array){\n\n let maximum = array[0]; \n\n for(let i = 0 ; i < array.length ; i++)\n {\n\n if(array[i] > maximum)\n maximum = array[i];\n }\n\n return maximum ; \n}", "function max(array) {\n //Write your code here\n}", "function searchMaxAndMin(array){\n var max = array[0];\n var min = array[0];\n for (var i = 1; i < array.length; i++){\n if(array[i] > max){\n max = array[i];\n }else if(array[i] < min){\n min = array[i];\n }\n }\n return [min, max]\n }", "function getLargest(){\n var largest = 0;\n for (var i = 0; i < numbers.length; i ++){\n if (numbers[i] > largest){\n largest = numbers[i];\n }\n }\n return largest;\n}", "function max(a, b) {\n if (a > b) {\n console.log(a);\n } else {\n console.log(b);\n }\n}", "function findMax(array) {\n\t\tvar max = array[0];\n\t\tfor (var i = 1; i < array.length; i++) {\n\t\t\tif(max < array[i]){\n\t\t\t\tmax = array[i];\n\t\t\t}\n\t\t};\t\n\t\treturn max;\n\t}", "function recursiveHighLow(data){if(data===undefined){return undefined;}else if(data instanceof Array){for(var i=0;i<data.length;i++){recursiveHighLow(data[i]);}}else {var value=dimension?+data[dimension]:+data;if(findHigh&&value>highLow.high){highLow.high=value;}if(findLow&&value<highLow.low){highLow.low=value;}}}// Start to find highest and lowest number recursively", "function func5(inputArray){\n if(inputArray===[]){\n return 0;\n }\n var result=inputArray[0];\n for(var i=1; i<inputArray.length; i++){\n if(inputArray[i]>result){\n result=inputArray[i];\n }\n }\n return result;\n}" ]
[ "0.7929877", "0.7896344", "0.78954214", "0.7884449", "0.7831158", "0.778653", "0.7725738", "0.76373726", "0.76096904", "0.75935966", "0.75906533", "0.75496036", "0.7508173", "0.74610686", "0.7426895", "0.74267435", "0.7412209", "0.7400254", "0.729726", "0.7286153", "0.72447723", "0.7043492", "0.69864243", "0.69857424", "0.696402", "0.69005996", "0.68539095", "0.6853153", "0.6851574", "0.6815478", "0.6747855", "0.6745182", "0.6724959", "0.6724297", "0.6717774", "0.66931635", "0.6693072", "0.66916853", "0.6688464", "0.66841125", "0.66589326", "0.6653361", "0.6647004", "0.6642859", "0.66268796", "0.6610573", "0.6592632", "0.65884346", "0.6571767", "0.65475017", "0.6543615", "0.6539596", "0.65271294", "0.65182596", "0.65035903", "0.64990634", "0.64875525", "0.6444449", "0.6434342", "0.64303625", "0.64290726", "0.6428114", "0.64204335", "0.64050776", "0.6398139", "0.63967055", "0.6395439", "0.63944954", "0.639219", "0.63852686", "0.63790995", "0.6377878", "0.6375806", "0.6368573", "0.63658863", "0.6363715", "0.6361522", "0.6354132", "0.6349221", "0.63487697", "0.6345498", "0.6344643", "0.6340284", "0.6339522", "0.632803", "0.6322901", "0.63138616", "0.63064957", "0.6303259", "0.6300694", "0.62936276", "0.6293524", "0.62895614", "0.6289336", "0.6288838", "0.62878877", "0.6284517", "0.6282815", "0.62825304", "0.6281892" ]
0.7958875
0
console.log(printLowReturnHigh([2,4,5,3,7,9])); Challenge 3. Print One, Return Another Build a function that takes in an array of numbers. The function should print the secondtolast value in the array, and return the first odd value in the array.
function printOneReturnAnother(arr) { console.log(arr[arr.length - 2]) for(var i = 0; i < arr.length; i++) { if(arr[i] % 2 !== 0) { return arr[i]; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function print1ReturnAnother(arr){\n console.log(\"Second to last value: \" + arr[arr.length - 2]);\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 != 0){\n return arr[i]\n }\n }\n return \"No odd numbers in array\"\n}", "function print2ndLast_return1stOdd(arr){\n console.log(arr[arr.length - 2]);\n for(let i = 0; i < arr.length; i++){\n if(arr[i]%2 == 1) return arr[i];\n }\n}", "function secondLast(arr) {\n console.log(arr[arr.length - 2]); // printing out the second last value\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 == 1) {\n var firstOdd = arr[i];\n return firstOdd; // get out of the function\n }\n }\n}", "function printReturn(array){\n console.log(array[array.length-2]);\n for (var i=0;i<array.length;i++){\n if(array[i] % 2 !== 0){\n return array[i];\n }\n }\n \n }", "function printReturn(arr) {\n console.log(arr[arr.length - 2]);\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 == 1) {\n return arr[i];\n }\n }\n}", "function printOneReturnAnother(arr){\n console.log(arr[arr.length - 2]);\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 1 || arr[i] % 2 == -1){\n return arr[i];\n } else {\n return \"No odds.\";\n }\n }\n}", "function printOneReturnAnother(array){\n let odd = 0;\n for(let i = 0; i < array.length; i++){\n if(array[i] %2!==0){\n odd = array[i];\n break;\n } \n }\n console.log(array[array.length - 2]);\n return odd;\n}", "function printReturn(arr) {\n\n console.log(arr[arr.length - 2]);\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 != 0) {\n return arr[i];\n }\n }\n}", "function printHigh(arr) {\n var low = arr[0]; // 2\n var high = arr[0]; // 2\n\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] < low) {\n low = arr[i];\n } else if (arr[i] > high) {\n high = arr[i];\n }\n }\n console.log(low);\n return high;\n}", "function printOneReturnAnother(array) {\n var oddVal = 0;\n for (var num in array) {\n if (array[num] % 2 !== 0) { // Found odd\n oddVal = array[num];\n console.log(\"oddVal: \" + oddVal);\n break; \n }\n }\n console.log(array[array.length - 2]);\n return oddVal;\n}", "function printReturn(arr) {\n\n console.log(arr[arr.length-2]);\n for (var i = 0; i < arr.length; i++) {\n \n if(arr[i] % 2 !==0) {\n return arr[i];\n }\n }\n}", "function printReturn(arr) {\n\tconsole.log(arr[arr.length-2]);\n\tfor (var i = 0; i <arr.length; i++) {\n\t\tif (arr[i]%2!==0) {\n\t\t\treturn arr[i]\n\t\t} \n\t}\n\t\n}", "function printLow_returnHigh(arr){\n var high = arr[0];\n var low = arr[0];\n\n for(let i = 1; i < arr.length; i++){\n if(high < arr[i]) high = arr[i];\n if(low > arr[i]) low = arr[i];\n }\n console.log(\"Low\", low);\n return high;\n}", "function printLowReturnHigh(arr){\n var low = arr[0];\n var high = arr [0];\n for (var i = 0; i < arr.length; i++){\n if(arr[i] > high){\n high = arr[i];\n }\n if(arr[i] < low){\n low = arr[i];\n }\n }\n console.log(low);\n return high;\n}", "function oneAnother(arr){\nvar oddNumber = arr[0];\n\n\tif (arr.length < 2) {\n\t\tconsole.log(\"The array needs more numbers!\");\n\t} \n\n\telse {\n\t\tfor (var num = 0; num < arr.length; num++) {\n\t\t\tif (arr[num] % 2 == 0) {\n\t\t\t}\n\t\t\telse {\n\t\t\t\toddNumber = arr[num];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tconsole.log(arr[arr.length-2]);\n\treturn oddNumber;\n}", "function printLowReturnHigh(arr){\n var low = arr[0]\n var high =arr[0] \n for(var i = 0; i <= arr.length; i++){\n if(arr[i] > high){\n high = arr[i]\n }\n if(arr[i] < low){\n low = arr[i]\n }\n }\n console.log(low)\n return high\n}", "function printReturn(arr)\n{\n console.log(arr[arr.length-2])\n for(i in arr)\n {\n if(i % 2 == 1)\n {\n return i\n }\n }\n}", "function func(arr) {\n console.log(arr[arr.length - 2]);\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 == 1) {\n return arr[i];\n }\n }\n}", "function printReturn(arr){\n let odd = arr[0]\n let i = 0\n while (odd % 2 == 0){\n odd = arr[i]\n i++\n }\n \n console.log(arr.length-2)\n return odd\n}", "function returnanother(arr){\n \n console.log(arr[arr.length-2]);\n for(var i=0;i<arr.length;i++){\n if(arr[i]%2!=0){\n x=(arr[i]);\n return x;\n }\n\n }\n \n}", "function penult() {\n var arr = [1,2,3,4,5,6,7,8,9,10]\n var lowHigh = []\n var seclow = arr[1]\n lowHigh.push(seclow)\n var sechigh = arr.length - 1\n lowHigh.push(sechigh)\n return lowHigh\n}", "function printLowReturnHigh(arr) {\n var lowest = arr[0];\n var hightest = arr[0];\n for(var i = 0; i < arr.length; i++) {\n if(lowest > arr[i]) {\n lowest = arr[i];\n }\n if(hightest < arr[i]) {\n hightest = arr[i];\n }\n }\n console.log(lowest);\n return hightest;\n}", "function printlow(arr){\n var low=arr[0];\n var high=arr[0];\n for(var i=0;i<arr.length;i++){\n if(arr[i]<low){\n low=arr[i];\n }else{\n high=arr[i];\n }\n }\n console.log(low);\n return high;\n\n}", "function lowHigh(arr)\n{\n var lowNum=arr[0]\n var highNum=arr[0]\n for(var i=1; i<arr.length; i++)\n {\n if(arr[i]<lowNum)\n {\n lowNum=arr[i]\n }\n if(arr[i]>highNum)\n {\n highNum=arr[i]\n }\n }\n console.log('Low num is ' + lowNum)\n return(highNum)\n}", "function secondLowHigh(array) {\n var sortedArray = array.sort(function(a,b){\n return a-b\n });\n\n var secondLowest = sortedArray[1]; \n var secondHighest = sortedArray[sortedArray.length - 2];\n\n console.log(secondLowest);\n console.log(secondHighest);\n}", "function doStuff(arr){\n console.log(arr[arr.length-2]);\n var firstOdd = \"No odd numbers\"\n for(e in arr){\n if(Math.abs(arr[e] % 2) == 1){\n firstOdd = arr[e];\n return firstOdd;\n }\n }\n}", "function secondToLast(arr){\n if (arr.length < 2){\n return null;\n }\n return console.log(arr[arr.length-2])\n}", "function secondtolast(arr) {\n for (var i = 0; i < arr.length - 1; i++) {\n if (arr[i] % 2 !== 0)\n return (arr[i])\n }\n}", "function PoRa(arr){\n console.log(arr[arr.length-2]);\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 === 1){\n return arr[i];\n }\n }\n}", "function twoNums(array){\n console.log(array[0] + array.pop());\n}", "function printAndReturn(arr)\n{\n console.log(arr[0]);\n return arr[1]\n}", "function returnFirstEvenNumber(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 0) {\n\t\t\t\treturn array[i];\n\t\t\t}\n\t\t}\n\t}", "function printReturn(arr){\n console.log(arr[0]);\n return (arr[1]);\n}", "function returnSecondHalf(array) {\n\t\t// var length = array.length / 2;\n\t\t// var result = [];\n\n\t\t// for (var i = length; i < array.length; i++) {\n\t\t// \tresult.push(array[i]);\n\t\t// }\n\t\t// return result;\n\n\t\treturn numbers.slice(numbers.length / 2);\n\t}", "function lowHigh(arr){\nvar lowNum = arr[0];\nvar highNum = arr[0];\n\n\tif (arr.length < 2) {\n\t\tconsole.log(\"The array needs more numbers!\");\n\t} \n\n\telse {\n\t\tfor(var num = 0; num < arr.length; num++) {\n\t\t\tif (arr[num] > highNum){\n\t\t\t\thighNum = arr[num];\n\t\t\t\t}\n\t\t\telse if (arr[num] < lowNum){\n\t\t\t\tlowNum = arr[num];\n\t\t\t}\n\t\t}\n\t}\n\tconsole.log(\"Lowest number: \" +lowNum);\n\treturn highNum;\n}", "function SecondGreatLow(arr) { \n\tif (arr.length === 2){\n\t\tif(arr[0] > arr[1]) {\n\t\t\treturn arr[0] + \" \" + arr[1];\n\t\t} else {\n\t\t\treturn arr[1] + \" \" + arr[0];\n\t\t}\n\t} else {\n\t\tvar greatest = Math.max.apply(Math, arr);\n\t\tvar lowest = Math.min.apply(Math, arr);\n\t\tvar newArr = [];\n\t\tfor (var i = 0; i<arr.length; i++) {\n\t\t\tif (arr[i] !== greatest && arr[i] !== lowest){\n\t\t\t\tnewArr.push(arr[i]);\n\t\t\t}\n\t\t}\t\t\n\t\tconsole.log(newArr);\n\t\tif (newArr.length === 1){\n\t\t\treturn newArr + \" \" + newArr;\n\t\t} else {\n\t\t\tvar secondGreatest = Math.max.apply(Math, newArr);\n\t\t\tvar secondLowest = Math.min.apply(Math, newArr);\n\t\t\treturn secondLowest + \" \" + secondGreatest;\n\t\t}\n\t} \n}", "function printAndReturn(arr) {\n console.log(arr[0]);\n return arr[1];\n}", "function returnAnother(arr){\n var arr2 =[];\n \n for (var i=0;i<arr.length;i++){\n if(arr[i]%2==1){\n arr2.push(arr[i]);\n }\n }\n console.log(arr[arr.length-2]);\n return arr2[0];\n}", "function printlowreturnhigh(arr){\n var min = arr[arr.length - 1];\n var max = arr[arr.length - 1];\n for(var i = arr.length - 1; i >= 0; i--){\n if(min > arr[i]){\n min = arr[i];\n }\n if(max < arr[i]){\n max = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function SecondGreatLow(arr) {\n\n // Use the sort function and pass in a callback to sort from smallest to largest\n\n arr = arr.sort(function(a, b) {\n return a - b;\n });\n\n // Loop through each item in the array and check if the adjacent array item is the same.\n for (var i = arr.length - 1; i > 0; i--) {\n if (arr[i] == arr[i - 1]) {\n // If it is, we use the .splice method to remove it.\n arr.splice(i, 1);\n }\n }\n\n if (arr.length > 2) {\n // If our array is longer than two items, we return the 2nd and 2nd to last item in the array.\n return arr[1] + \" \" + arr[arr.length - 2];\n } else if (arr.length == 2) {\n // If our array is exactly two items long, we return the 2nd and the first item\n return arr[1] + \" \" + arr[0];\n } else {\n // If our array is only one item, we return the only element twice.\n return arr[0] + \" \" + arr[0];\n }\n\n}", "findSecondHighest() {\n \n }", "function LowHighvalue(arr){\n var low = arr[0];\n var high = arr[0];\n for(var i=0;i<arr.length;i++){\n if(low>arr[i]){\n low = arr[i];\n }\n if(high<arr[i]){\n high = arr[i];\n }\n\n }\n console.log(low);\n return high;\n}", "function PrintLowReturnhigh(arr) {\n\tvar min=arr[0], max=arr[0];\n\tfor (var i = 0; i <arr.length; i++) {\n\t\tif (arr[i]>max) {\n\t\t\tmax=arr[i];\n\t\t} \n\t\tif (arr[i]<min) {\n\t\t\tmin=arr[i];\n\t\t}\n\t}\n\tconsole.log(min);\n\treturn max;\n}", "function returnOdds(array) {\n}", "function findOutlier(integers){\r\n var oddArray = [];\r\n var evenArray = [];\r\n integers.forEach(function(elem){\r\n if (elem % 2 ==0) {\r\n return evenArray.push(elem);\r\n }\r\n return oddArray.push(elem);\r\n });\r\n if (oddArray.length === 1) {\r\n return oddArray[0];\r\n } else if (evenArray.length === 1) {\r\n return evenArray[0];\r\n} else {\r\n console.log(\"This is not the problem as I understand it\"):\r\n return false;\r\n}\r\n\r\n}", "function SecondGreatLow(arr) { \n\n // first we create a unique array by using the filter function\n // we check to see if the index of the current element in the array \n // is equal to the first index of the element, if so then add the\n // element to the new array\n var unique = arr.filter(function(elem, index, self) {\n return self.indexOf(elem) === index;\n });\n\n // sort the unique array in ascending order\n var sorted = unique.sort(function(a, b) {\n return a - b;\n });\n\n // return the second smallest and largest elements\n // but also check to make sure there is more than 1\n // element in the array\n if (sorted.length < 2) { \n return sorted[0] + \" \" + sorted[0]; \n } else {\n return sorted[1] + \" \" + sorted[sorted.length - 2];\n }\n \n}", "function SecondGreatLow(arr) { \n let num = [];\n arr.forEach(function(el) {\n if(num.indexOf(el) === -1){\n return num.push(el);\n }\n });\n \n num.sort((a, b) => {\n return a-b;\n });\n \n if (num.length < 2) { \n return num[0] + \" \" + num[0]; \n } else {\n return num[1] + \" \" + num[num.length - 2];\n } \n}", "function secondToLast(arr){\n console.log('Second to Last');\n if(arr.length < 2){\n return 'null';\n } else{\n var value = arr[arr.length -2];\n return value;\n }\n}", "function printLowReturnHigh(array) {\n var lowestVal = array[0];\n var highestVal = array[0];\n\n for (var num in array) {\n if (array[num] > highestVal) {\n highestVal = array[num];\n } \n else if (array[num] < lowestVal) {\n lowestVal = array[num];\n }\n }\n console.log(\"Lowest value: \" + lowestVal);\n return highestVal;\n}", "function printAndReturn(value1,value2){\n\tvar printReturnArray = [value1,value2];\n\n\tconsole.log(printReturnArray[0]);\n\treturn (printReturnArray[0]);\n\n}", "function PLRH(arr){\n var low = arr[0];\n var high = arr[0];\n for(var i = 1; i < arr.length; i++){\n if(arr[i] > high){\n high = arr[i];\n }\n if(arr[i] < low){\n low = arr[i];\n }\n }\n console.log(low);\n return high;\n }", "function SecondGreatLow(arr) { \n arr = arr.sort(function (a, b) {return a - b;});\n\n if (arr.length < 3) {\n return arr[1] + \" \" + arr[0];\n }\n\n result = [];\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] !== arr[i+1]) {\n result.push(arr[i]);\n }\n }\n return result[1] + \" \" + result[result.length - 2];\n}", "function oddNumbers() {\n var a = arguments;\n var k=0;\n var number = [];\n for(var i = 0; i < a.length; i++) {\n if(a[i]%2!=0){\n number[k]=a[i];\n k++;\n }\n }\n for(i=0;i<number.length;i++) {\n for(var j =0; j<number.length-i;j++) {\n if(number[j]>number[j+1]) {\n var temp = number[j];\n number[j] = number[j+1];\n number[j+1] = temp;\n }\n }\n }\n console.log(number);\n}", "function printLowReturnHigh(arr){\n let min = 0;\n let max = 0;\n for(let i = 0; i < arr.length; i ++){\n if(arr[i] > max){\n max = arr[i];\n }\n if(arr[i] < arr[i] + 1){\n min = arr[i]; \n }\n }\n console.log(min);\n return max; \n}", "function findOdd(A) {\n var sortedArray = A.sort(function(a,b){return a-b});\n console.log(\"sortedArray = \" + sortedArray);\n var i = 0;\n while (i < sortedArray.length){\n var a = sortedArray.lastIndexOf(sortedArray[i]);\n if (a%2!=0){\n i++\n }\n else{\n console.log(\"sortedArray[i] = \" + sortedArray[i]);\n return sortedArray[i];\n }\n }\n }", "function firstAndLast(array){\n for(var i = 0; i < array.length; i++){\n if(array.length % 2 === 0){\n return array[0] + array[array.length - 1];\n } else{\n return array[0] - array[array.length - 1];\n }\n }\n}", "function array() {\n var arr = [6, 14];\n console.log(arr[0]);\n return arr[1];\n}", "function printFirstTwoNames(array) {\n console.log(array[0])\n console.log(array[1])\n}", "function getMiddle(list) {\n list= [10,30,50,70,90,110];\n let middleNumber= 0;\n numLength =list.length;\n if(numLength%2===0){\n middleNumber=(list[numLength/2-1]+list[numLength/2])/2;\n } else{ \n answer =list[(numLength-1)/2];\n }\n document.getElementById(\"showArray\").innerHTML= middleNumber; \n return middleNumber;\n \n}", "function s(nums) {\n let lo = 0;\n let hi = nums.length - 1;\n while (lo < hi) {\n const mid = Math.floor((hi + lo) / 2);\n if (nums[mid] > nums[hi]) {\n lo = mid + 1;\n } else {\n hi = mid;\n }\n }\n\n return nums[lo];\n}", "function printOdd(start,end){\n if(start>end){\n return \n }\n else{\n if(start%2!==0){\n console.log(start)\n }\n \n return printOdd(start+1,end)\n }\n \n }", "function middleOfArray(arr){\r\n\tvar length =arr.length\r\n\tif(length%2==1){\r\n\t\tvar n=(arr.length-1)/2;\r\n\t\tconsole.log(arr[n]);\r\n\t}\r\n\telse{\r\n\t\tvar n=length/2\r\n\t\tconsole.log(arr[n-1],arr[n]);\r\n\t}\r\n}", "function returnFirstHalf(array) {\n\t\t// var length = array.length / 2;\n\t\t// var result = [];\n\n\t\t// var i = 0;\n\t\t// while(i < length) {\n\t\t// \tresult.push(array[i]);\n\t\t// \ti++;\n\t\t// }\n\t\t// return result;\n\n\t\treturn array.slice(0, numbers.length / 2);\n\n\t}", "function returnFirstOddNumber(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 1) {\n\t\t\t\treturn array[i];\n\t\t\t}\n\t\t}\n\t}", "function question0 (array) {\n for (var i = 0; i < array.length; i++){\n\n if (array[i] %2 ===0){\n console.log(array[i])\n }\n }\n}", "function second(value){\n return value[1];// returns second value sequence\n}", "function processOddNumbers(arr) {\n\tconsole.log(arr\n\t\t\t.filter((x, i) => i % 2 !== 0)\n\t\t\t.map(x => x * 2)\n\t\t\t.reverse()\n\t\t\t.join(' '));\n}", "function selectLastEvenNumber(myArr, call) {\n let lasteven = -1;\n for (let i = 0; i < myArr.length; i++) {\n if (myArr[i] % 2 === 0) {\n lasteven = myArr[i]\n }\n }\n if (lasteven != -1) {\n call(lasteven)\n }\n}", "function displayEvenNumbers(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 0) {\n\t\t\t\tconsole.log(array[i]);\n\t\t\t}\n\t\t}\n\t}", "function increment2nd(arr) {\n\nfor(var i=0; i<arr.length;i++){\n\n if(i%2!=0){\n arr[i] = arr[i]+1\n // console.log(arr[arr.indexOf(arr[i])]+1);\n }\n}\n return arr;\n}", "function evenLast(numbers) {\n return numbers.length != 0 ? [...numbers.filter((x, i) => i % 2 == 0)].reduce((sum, num) => sum + num) * numbers[numbers.length - 1] : 0;\n}", "function findOdd(arr) {\n // Your code here\n}", "function incrementsecond(arr){\n for(var i=0;i<arr.length;i++){\n if(i % 2 != 0){\n arr[i] = arr[i] + 1;\n console.log(\"the value is \" + arr[i] + \" and the index is \" + i);\n }\n }\n return arr\n}", "function printReturn(arr) {\n\n var max = arr[0];\n var min = arr[0];\n\n for (var i = 1; i < arr.length; i++) {\n if (arr[i] > max) {\n max = arr[i];\n }\n if (arr[i] < min) {\n min = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function highof2Pair(passArray){\n if(passArray[2] === passArray[3]){\n return passArray[2];\n }\n else{\n return passArray[4];\n }\n }", "function findOutlier(integers) {\n let oddNumbers = 0\n let evenNumbers = 0\n let result = 0\n for (let i = 0; i < integers.length; i++) {\n if (integers[i] % 2 === 0) {\n evenNumbers++\n } else oddNumbers++\n }\n console.log(`odd: ${oddNumbers} and even: ${evenNumbers}`)\n if (evenNumbers === 1) {\n for (let j = 0; j < integers.length; j++) {\n if (integers[j] % 2 === 0) {\n result = integers[j]\n }\n }\n } else {\n for (let q = 0; q < integers.length; q++) {\n if (integers[q] % 2 !== 0) {\n result = integers[q]\n }\n }\n }\n return result\n}", "function second(arr) {\n arr.sort((a, b) => a - b)\n return `${arr[1]}, ${arr[arr.length - 2]}`\n}", "function findOutlier(integers){\n //your code here\n var odd = [];\n var even = [];\n \n function remainder(num){\n return num%2;\n }\n \n var numbers = integers.map(remainder)\n \n for(var i = 0; i < numbers.length; i++){\n if (numbers[i] === 0){\n even.push(integers[i]);\n } else {\n odd.push(integers[i]);\n }\n };\n return even.length==1 ? even[0] : odd[0];\n}", "function lowhighvalue(arr) {\n var lowest = arr[0];\n var highest = arr[0];\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < lowest){\n lowest = arr[i];\n }\n if (arr[i] > highest){\n highest = arr[i];\n }\n }\n console.log(lowest);\n return highest;\n}", "function secondLargest(arr){\n console.log('Sedond Largest');\n var max = 0;\n var second_max = 0;\n if(arr[0] > arr[1]){\n max = arr[0];\n second_max = arr[1];\n } else if(arr[1] > arr[0]){\n second_max = arr[0];\n max = arr[1];\n } else if( arr.length < 2){\n return 'null';\n }\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > max){\n second_max = max;\n max = arr[i];\n }\n }\n return second_max;\n}", "function lowHigh(arr) {\n var min = arr[0];\n var max = arr[0];\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < min) {\n min = arr[i];\n } else if (arr[i] > max) {\n max = arr[i];\n }\n }\n console.log(min);\n return max;\n}", "function evenOdd1(arr){\n for(let i = 0; i < arr.length - 2; i++){\n if ((arr[i] % 2 == 0) && (arr[i+1] % 2 == 0) && (arr[i+2] % 2 == 0)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - Even more so!`)\n } else if ((arr[i] % 2 == 1) && (arr[i+1] % 2 == 1) && (arr[i+2] % 2 == 1)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - That's odd!`)\n }\n }\n}", "function getNumber (array) {\nvar result1, result2, count = 0;\n for (var i = 0; i < array.length; i++) {// 1 // 5 \n if (array[i] % 2 === 0) { // 1 % 2 != 0 // 5 % 2 != 0 //4 % 2 == 0\n result1 = array[i]; // resultEven = 4 \n count++;\n } else { \n result2 = array[i]; // resultOdd = 1 // resultOdd = 5\n }\n }\n switch (count) {\n case 1: console.log(result1); break;\n default: console.log(result2); break;\n }\n}", "function collectOddValues(arr){\n let result = [];\n\n// result is out of scope of helper so it wont reset\n\n function helper(helperInput){\n if(helperInput.length === 0){\n return\n }\n\n if(helperInput[0] % 2 !== 0){\n result.push(helperInput[0])\n }\n console.log(helperInput)\n \n helper(helperInput.slice(1))\n }\n\n helper(arr)\n\n return result\n}", "function findOutlier(integers) {\n let evenNumbers = integers.filter(a => { return (a % 2) == 0 })\n let oddNumbers = integers.filter(a => { return (a % 2) != 0 })\n\n return (evenNumbers.length > 1) ? (oddNumbers[0]) : (evenNumbers[0])\n \n}", "function s(nums) {\n let lo = 0;\n let hi = nums.length - 1;\n while (lo < hi) {\n const mid = Math.floor((hi + lo) / 2);\n if (nums[mid] > nums[hi]) {\n lo = mid + 1;\n } else if (nums[mid] === nums[hi]) {\n hi--;\n } else {\n hi = mid;\n }\n }\n return nums[lo];\n}", "function collectOddValue(arr){\n let result = [];\n\n function helper(helperInput){\n if(helperInput.length === 0) return;\n\n if(helperInput[0] % 2 !== 0){\n result.push(helperInput[0]);\n }\n\n helper(helperInput.slice(1));\n \n\n }\n\n helper(arr);\n\n}", "function oddarr(arr)\r\n{ var arr=[];\r\n\tfor(var i=1;i<=50;i++)\r\n\t{\r\n\t\t\tif(i%2!==0)\r\n\t\t{\r\n\t\t\tarr.push(i);\t\r\n\t\t}\r\n\t}\r\nconsole.log(\"Odd numbers\",arr);\r\n}", "function valueGreaterThanSecondGeneralized(){\n var result = []\n var secondValue = arr[1]\n if(arr.length < 1){\n return null;\n }\n for(var i = 0); i < arr.length; i ++){\n if(arr[i] > secondValue){\n console.log(arr[i]);\n count ++;\n }\n }\n console.log(count);\n return result\n\n }", "function oddValues(arr){\n let result = []\n function helper(helperInput){\n if (helperInput.length === 0){\n return \n }\n if (helperInput[0] % 2 !== 0){\n result.push(helperInput[0])\n }\n helper(helperInput.slice(1))\n }\n helper(arr)\n return result\n}", "function displayNumbers(evenNumbers) {\r\n for (let i = 0; i < evenNumbers.length; i++) {\r\n console.log(evenNumbers[i]);\r\n }\r\n }", "function showFirstAndLast(arr){\n \nvar arrStr=[]; \narr.forEach(z => arrStr.push(z[0]+z[z.length-1])); \n\nreturn arrStr ; \n\n\t\n\n\n\n\n}", "function forth(value){\n return value[3];// returns second value sequence\n}", "function getstrongestnumber() {\n alert(\"This function returns the even number that is the strongest in the interval\");\n n = parseInt(prompt(\"Please, write the number\", \"2\"), 10);\n m = parseInt(prompt(\"Please, write the number\", \"8\"), 10);\n alert(\"You printed next interval: \" + \"[\" + n + \", \" + m + \"]\");\n console.log(\"You printed next interval: \" + \"[\" + n + \", \" + m + \"]\");\n INT_MAX = 1000;\n if (1 <= n && m <= INT_MAX) {\n let strongnessarray = [];\n let strongnesszero = [];\n for (number = n; number <= m; number++) {\n let remainder = \"\";\n remainder = number % 2;\n if (remainder == 0 && number != 1) {\n let i = \"\";\n i = 1;\n result = number / 2;\n resultremainder = result % 2;\n if (result == 1 || resultremainder > 0) {\n //alert(\"number \\\"\" + number + \"\\\" is even; number has strongness \" + i);\n strongnessarray.push({number: number, strongness: i});\n } else {\n do {\n result = result / 2;\n resultremainder = result % 2;\n i++; \n if (result == 1 || resultremainder > 0) {\n strongnessarray.push({number: number, strongness: i});\n //alert(\"number \\\"\" + number + \"\\\" is even; number has strongness \" + i);\n break;\n }\n } while (i < 30);\n }\n } else {\n //alert (\"number \\\"\" + number + \"\\\" is odd; number has strongness 0\");\n strongnesszero.push({number: number, strongness: 0});\n } \n }\n console.log(\"Odd numbers in the interval: \");\n console.log(strongnesszero);\n strongnessarray.sort((a, b) => a.strongness - b.strongness);\n console.log(\"Even numbers in the interval: \");\n console.log(strongnessarray);\n quantity = strongnessarray.length;\n index = strongnessarray.length - 1;\n console.log(\"Quantity even numbers in the interval: \" + quantity);\n strongness = strongnessarray[index].strongness;\n number = strongnessarray[index].number;\n let numbers = [];\n for (i in strongnessarray) {\n if (strongnessarray[i].strongness === strongness) {\n numbers.push(strongnessarray[i].number); \n }\n }\n quantity = numbers.length;\n if (quantity == 1) {\n console.log(\"Quantity of the strongest even numbers in the interval: \" + quantity);\n console.log(\"The strongest even number in the interval [\" + n + \", \" + m + \"]\" + \" is number: \" + numbers[0] + \" (strongness: \" + strongness + \")\");\n alert(\"The strongest even number in the interval [\" + n + \", \" + m + \"]\" + \" is number: \" + numbers[0] + \" (strongness: \" + strongness + \")\");\n } else if (quantity >= 2) {\n console.log(\"Quantity of the strongest even numbers in the interval: \" + quantity + \" => \");\n console.log(numbers);\n numbers.sort((a, b) => a - b);\n console.log(\"The smallest strongest even number in the interval [\" + n + \", \" + m + \"]\" + \" is number: \" + numbers[0] + \" (strongness: \" + strongness + \")\");\n alert(\"The smallest strongest even number in the interval [\" + n + \", \" + m + \"]\" + \" is number: \" + numbers[0] + \" (strongness: \" + strongness + \")\");\n }\n } else {\n alert(\"Issue with interval, check constraints\");\n }\n}", "function oddOrEven(array) {\n if(array.length === 0 ){\n return 'even'\n }\n \n let arraySum = array.reduce(( a, n) => a+n)\n if( arraySum % 2 === 0 ){\n return 'even'\n } else{\n return 'odd'\n }\n \n}", "function oddOrEven(array) {\n // enter code here\n const sum = array.reduce((curr, acc) => acc + curr, 0);\n\n return sum % 2 === 0 ? 'even' : 'odd';\n}", "function findOutlier(integers) {\n var arrEven = [];\n var arrOdd = [];\n for (var i = 0; i < integers.length; i++) {\n if (integers[i] % 2 != 0) {\n arrEven.push(integers[i])\n } else {\n arrOdd.push(integers[i])\n }\n }\n return arrEven.length == 1 ? arrEven[0] : arrOdd[0];\n}", "function oddOrEven(array) {\n const even = 'even'\n const odd = 'odd'\n \n if (array.length < 1 || (array[0] === 0 && array.length === 1)){\n return even\n } \n const sumArr = Math.abs(array.reduce((a,b) => a + b))\n \n if (sumArr%2 === 1) {\n return odd\n } else {\n return even\n }\n }", "function second_largest () {\n var arr = [3,1,82,19,47,4.7,-2, 32, -9];\n var temp = 0;\n for (var i = 0; i<arr.length; i++) {\n for (var j = 0; j < arr.length; j++) {\n if (arr[i] < arr[j]) {\n temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n }\n }\n }\n var k = arr.length;\n console.log(arr);\n console.log(arr[k - 2]);\n\n}", "function secondHighest(array) {\n\tvar retval;\n\tvar sortable = array.slice(0);\n\n\tsortable.sort(function(a, b) {\n\t\treturn b - a;\n\t})\n\t\n\tarray.forEach(function(n, idx) {\n\t\tif (n === sortable[1])\n\t\t\tretval = idx\n\t})\n\n\treturn retval;\n}" ]
[ "0.7642936", "0.7624414", "0.7436052", "0.7420006", "0.74071157", "0.7366025", "0.7361987", "0.730998", "0.7307953", "0.727087", "0.7248014", "0.7241695", "0.72221017", "0.7147316", "0.7132317", "0.70374286", "0.7017233", "0.6997892", "0.69757503", "0.69545424", "0.692844", "0.6920273", "0.69086194", "0.68711984", "0.68686247", "0.68351275", "0.68342316", "0.67867154", "0.67380315", "0.6731585", "0.6664139", "0.6661983", "0.66313565", "0.6621034", "0.6605973", "0.66000223", "0.6596186", "0.6577873", "0.6532654", "0.6495413", "0.6484098", "0.64481497", "0.6376389", "0.6343368", "0.63401544", "0.63323236", "0.6328847", "0.6291862", "0.62854975", "0.6265845", "0.62627757", "0.62505", "0.62356853", "0.62314403", "0.621851", "0.6213595", "0.62004364", "0.6193155", "0.618836", "0.61869055", "0.6173572", "0.6165728", "0.61377674", "0.6130564", "0.6124924", "0.61122113", "0.60961646", "0.6085475", "0.6074311", "0.6065484", "0.6065061", "0.60603267", "0.6055664", "0.60456955", "0.604226", "0.6037811", "0.6013127", "0.6009472", "0.60083693", "0.5998539", "0.5980706", "0.5978402", "0.5971921", "0.5968649", "0.5967696", "0.59658897", "0.5963304", "0.59593153", "0.59509325", "0.5949244", "0.59417564", "0.5941572", "0.5936992", "0.5934035", "0.5927852", "0.59245366", "0.59211856", "0.5921094", "0.5919102", "0.5918465" ]
0.733342
7
console.log(printOneReturnAnother([2,4,1,5,3])); Challenge 4. Double Vision Given an array (similar to saying 'takes in an array'), create a function that returns a new array where each value in the original array has been doubled. Calling double([1,2,3]) should return [2,4,6] without changing the original array.
function doubleVal(arr) { var newArr = []; for(var i = 0; i < arr.length; i++) { newArr[i] = arr[i] * 2; } return newArr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function doubleVision(array){\n let newArr = [];\n for(let i = 0; i < array.length; i++){\n newArr.push(array[i] * 2);\n }\n array = newArr;\n return array;\n}", "function doubleVision(arr) {\n var double = [];\n for (var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * 2;\n double.push(arr[i]);\n }\n return double\n}", "function doubleVision(arr){\n\tvar singleArray = arr;\n\tvar doubleArray = [];\n\n\tfor(var num = 0; num < arr.length; num++) {\n\t\tdoubleArray.push((singleArray[num])*2);\n\t}\n\n\tconsole.log(\"Original Array: \" +singleArray);\n\tconsole.log(\"Doubled Array: \" +doubleArray);\n}", "function double(array) {\n var returnArray;\n for (index = 0; index < a.length; ++index) {\n returnArray[0] = array[0]*2;\n }\n return returnArray;\n}", "function doubleVision(arr){\n var newArr = []\n for(var i = 0; i < arr.length; i++){\n newArr.push(arr[i] * 2)\n }\n return newArr\n}", "function doubleVision(array){\n for(var i=0;i<array.length;i++){\n array[i] = array[i] * 2;\n console.log(array[i]);\n }\n\n}", "function double(arr){\n newArr = []\n for (let i = 0; i < arr.length; i++){\n newArr.push(arr[i]*2)\n }\n return newArr\n}", "function doubleVision(array) {\n var newDoubleArray = [];\n\n for (var num in array) {\n newDoubleArray[num] = array[num] * 2;\n }\n\n return newDoubleArray;\n}", "function double(arr) {\n let newArr = [];\n for(let i = 0; i < arr.length; i++) {\n newArr.push(2 * arr[i]);\n }\n return newArr;\n}", "function double(arr) {\n let newArr = [];\n for (let i = 0; i < arr.length; i++) {\n newArr.push(2 * arr[i]);\n }\n return newArr;\n}", "function double(arr) {\n let newArr = [];\n for(let i = 0; i < arr.length; i++) {\n newArr.push(2 * arr[i]);\n }\n\n return newArr;\n}", "function double(arr){\n for (i=0; i<arr.length; i++){\n arr[i] = arr[i]*2\n }\n return arr\n}", "function double(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i ++){\n newArr.push(arr[i]*2);\n }\n return newArr;\n}", "function double(arrayx) {\n arrayx = arrayx.map(x => x * 2 );\n return arrayx;\n }", "function double(arr){\n\nlet result = arr.map((elem)=>{\n return elem * 2\n})\nreturn result;\n}", "function double(arr) {\n\n for (var i=0;i<arr.length;i++) {\n arr[i] = arr[i]*2;\n }\n return arr;\n }", "function double(arr) {\n\tlet newArr = [];\n\tfor(let i=0; i< arr.length; i++) {\n\t\tnewArr.push( 2 * (arr[i] ));\n\t}\n\treturn newArr;\n}", "function double(arr) {\n let newArr = [];\n // one new arr\n for (let i = 0; i < arr.length; i++) {\n newArr.push(2 * arr[i]);\n // multiples each item and pushes it to the new array\n }\n return newArr;\n}", "function doubleArr(arr) {\n var newArr = [];\n for (var i = 0; i < arr.length; i++) {\n newArr.push(arr[i] * 2);\n }\n return newArr;\n}", "function double(arr) {\n let results = []\n for (let i = 0; i < arr.length; i++) {\n results.push(arr[i]*2)\n }\n return results\n }", "function doubleNumbers(arr){\n return arr.map(function (num){\n return num * 2\n }) \n}", "function arrayDouble2(arr){\n let answer = [];\n for(let i=0; i<arr.length;i++){\n answer.push(arr[i]*2);\n }\n return answer;\n}", "function doubleArray (array) {\n return array.map( item=>{return item*2});\n}", "function double(arr)\n{\n for(i in arr)\n {\n arr[i]=arr[i]*2\n }\n return arr\n}", "function doubleArr(arrFirst) {\n var arrDuble = [];\n for (var i = 0; i < arrFirst.length; i++) {\n arrDuble[arrDuble.length] = arrFirst[i] * 2;\n } return arrDuble;\n}", "function double(array) {\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\tarray[i] *= 2;\r\n\t}\r\n}", "function doubleNumbers(arr){\r\n const result = arr.map(function(num){\r\n return num * 2;\r\n });\r\n return result;\r\n }", "function seeDouble(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(arr[i],arr[i]);\n }\n document.getElementById(\"4\").innerHTML = newArr;\n return newArr;\n}", "function doubleAndReturnArgs(arr, ...nums){\n nums.map( val => {\n const double = val * 2;\n arr.push(double);\n })\n return arr;\n}", "function doubleAndReturnArgs(arr, ...args) {\n let doubled = args.map((n) => {\n return n * 2;\n });\n let newArr = [...arr, ...doubled];\n return newArr;\n}", "function doubleArrayValues(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] *= 2;\n }\n return array;\n}", "function doubleAll(numbers){\n //create a new array\n var double = [];\n //loop through each element in array\n each(numbers, function(el){\n //push the double element into array\n double.push(el + el);\n });\n //return array\n return double;\n}", "function doubleArrayValues(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] *= 2;\n }\n return array;\n}", "function doubleArrayValues(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] *= 2;\n }\n return array;\n}", "function doubleArray(array) {\n return array.map((el) => {\n return el * 2;\n });\n }", "function doubleArrayValues(array) {\n for (let i=0; i<array.length; i++) {\n array[i] *= 2;\n }\n return array;\n}", "function doubleArrayValues(array) {\n for (let i=0; i<array.length; i++) {\n array[i] *= 2;\n }\n return array;\n}", "function doubleIt(originalNum) {\n return originalNum * 2;\n // doubleIt2(originalNum);\n}", "function DouV(arr){\n var newarr = [];\n for(var i = 0; i < arr.length; i++){\n newarr.push(arr[i] * 2);\n }\n console.log(newarr);\n}", "function doubleNumbers(arr) {\n\n const result = arr.map(function(num) {\n return num + num;\n }\n )\n return result;\n}", "function doubleArrayValues(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] *= 2;\n }\n return array;\n }", "function doublevalue(){\n var newarr=[];\n for(var i=0;i<arr.length;i++){\n arr[i]=arr[i]*2;\n newarr.push(arr[i]);\n }\n console.log(newarr);\n console.log(arr);\n}", "function valueDouble(arr){\n for (var i =0;i<arr.length;i++){\n arr[i]=arr[i]*2;\n }\n return arr;\n}", "function doubleValues(arr){\n let newArr = [];\n arr.forEach(function(value) {\n newArr.push(value * 2);\n });\n return newArr;\n }", "function squareDance (arr) {\n var newArr = []\n for (var i = 0; i < arr.length; i++) {\n newArr[i] = arr[i] * arr[i]\n }\n return newArr\n}", "function double_all(arr) {\n var ret = Array(arr.length);\n for (var i = 0; i < arr.length; ++i) {\n ret[i] = arr[i] * 2;\n }\n return ret;\n}", "function doubleTrouble(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(arr[i]);\n newArr.push(arr[i]);\n }\n arr = newArr;\n return arr;\n}", "function double_all(arr) {\n var ret = Array(arr.length);\n for (var i = 0; i < arr.length; ++i) {\n ret[i] = arr[i] * 2;\n }\n return ret;\n}", "function double_all(arr) {\n var ret = Array(arr.length);\n for (var i = 0; i < arr.length; ++i) {\n ret[i] = arr[i] * 2;\n }\n return ret;\n}", "function DoubleTrouble(arr){\n let arr2=[];\n for(let i=0; i< arr.length; i++){\n arr2.push(arr[i]);\n arr2.push(arr[i]);\n }\n return arr2;\n}", "function doubleOddNumbers(arr) {}", "function double_all(arr) {\n if (!arr.length) { //constant\n return []; //constant\n }\n return [arr[0] * 2, ...double_all(arr.slice(1))]; \n}", "function newArr (firstnum, secondnum){\n return firstnum * secondnum;\n}", "function arrayReturn(array) {\n let returnArry = [];\n for (let i = 0; i < array.length; i++) {\n const element = array[i];\n if (element%2 !== 0) {\n let getOddDouble = element*2;\n returnArry.push(getOddDouble);\n }\n }return returnArry;\n}", "function doubleIt(num){\n var result = num*2;\n //console.log(result);\n return result;\n}", "function multTwo(array){\n return array.map((value) => value *2)\n }", "function doubleTrouble(arr){\n arr.length *= 2;\n for(var i = arr.length -1; i > 0; i -= 2){\n arr[i] = arr[0.5 * (i - 1)];\n arr[i -1] = arr[i];\n }\n return arr\n }", "function doubleAndReturnArgs(arr, ...args){\n let arr3 = [];\n for(let i = 0; i<args.length; i++){\n args[i] = args[i]*2;\n arr3.push(args[i]);\n }\n return [...arr, ...arr3];\n}", "function mapquest(arr) {\n\n // create an empty array for the new array with the doubled values\n\n // loop through the input array\n\n // for each value in arr, double it, and assign it to a new variable\n\n // push this new value to the newArr\n\n // once complete, return the newArry\n}", "function arraySquare(arr) {\n arr = [1,1,117]\n for(var x = 0; x < arr.length; x++){\n arr[x] = arr[x] * arr[x];\n }\n return arr;\n // console.log(arr);\n}", "function doubleT(arr){\n newArr = []\n for(var i=0;i<arr.length;i++){\n newArr.push(arr[i])\n newArr.push(arr[i])\n }\n return newArr\n}", "function doublenum() {\n let x = numArray.map(Element => Element * 2);\n return x;\n }", "function improved(array) {\n var prev = new Array(array.length);\n var next = new Array(array.length);\n\n var prev_index = 0;\n addPrevious(prev, array);\n addNext(next, array);\n\n array = multiply(prev, next);\n console.log(array);\n}", "function doublingNumbers(arr) {\n const result = arr.map(function(num) {\n return num * 2;\n });\n return result;\n}", "function doubleValues(num) {\n // console.log(num);\n num.forEach((element) => {\n element += element;\n return element;\n });\n \n}", "function double_all(arr) {\n if (!arr.length) {\n return [];\n }\n return [arr[0] * 2, ...double_all(arr.slice(1))];\n}", "function adouble(arr){\n\nresult = arr.reduce((total ,elem)=>{\n return total += elem * 2\n},0)\nreturn result\n}", "function squareEachNumber(numbers) {\n var newArray =[];\n for (var i=0; i<numbers.length; i++){\n var multiplied = numbers[i]*numbers[i];\n newArray.push(multiplied);\n }\n console.log(newArray);\nreturn newArray;\n}", "function double_all(arr) {\n if (!arr.length) {\n return [];\n }\n return [arr[0] * 2, ...double_all(arr.slice(1))];\n}", "function copyArrayAndMultiplyBy2(array) {\n const output = [];\n for (let i = 0; i < array.length; i++)\n output.push(array[i] * 2);\n return output;\n}", "function doubleList(list) {\n let output = [];\n for (let i = 0, l = list.length; i < l; i += 1) {\n let doubled = list[i] * 2;\n output.push(doubled);\n }\n return output;\n}", "function array() {\n var arr = [6, 14];\n console.log(arr[0]);\n return arr[1];\n}", "function squareArr(arr){\n var newarr = [];\n for(var i = 0; i < arr.length; i++){\n newarr.push(arr[i]*arr[i]);\n }\n console.log(newarr);\n}", "function multiplyByTwo(arr) {\n arr = arr.map(function (a) {\n return a*2;\n })\n return arr;\n}", "function modifyArray(nums) {\n let tempNum = nums;\n\n for (let i = 0; i < nums.length; i++){\n if (nums[i] % 2 == 0 ) {\n tempNum[i] = (nums[i] * 2);\n } else {\n tempNum[i] = (nums[i] * 3);\n\n }\n }\n\n return(tempNum);\n \n}", "function doubleFor(array) {\n let newArray = []\n for(let i = 0; i < array.length; i++) {\n for(let j = i + 1; j < array.length; j++) {\n console.log(i, j)\n \n }\n }\n return newArray\n \n}", "function doubleData() { // doubleData(); is the closure, the inner function that can access data\n for (var i = 0; i < data.length; i++) {\n doubledArr.push( Math.floor( data[i] * 2 ));\n }\n return doubledArr;\n }", "function doublesAndIndex(nums) {\n return nums.map(function (number,index){\n ((number * 2 ) * index)\n })\n}", "function swapHalves(array1){\n\n var outArray = [];\n\n if (array1.length % 2 !== 0) {\n console.log(\"Sorry, for this function, the given array needs an even number of elements.\")\n } else {\n for (i = (array1.length/2); i < array1.length; i++) {\n outArray.push(array1[i])\n }\n for (i = 0; i < (array1.length/2); i++) {\n outArray.push(array1[i])\n }\n console.log(outArray)\n }\n \n}", "function multiplyByTwo(arr) {\n let newArray = [];\n for (let i = 0; i < arr.length; i++) {\n newArray.push(arr[i] * 2);\n }\n return newArray;\n}", "function multiplyByTwo(array) {\n let newArray = []\n\n for(const number of array) {\n newArray.push(number * 2)\n }\n\n return newArray\n}", "function multiplyArray (array){ //function multipleArray return array \n let multiply = 1 //let multiply return value higher than 1\n for (i = 0; i <array.length; i++) { \n multiply *= array[i] // multiple each number in the index and provide the total\n }\n \n return (multiply) //return the total of each number in the index to multiply\n}", "function manualProductArray(arr) {\n const newArray = [];\n newArray.push(arr[1] * arr[2] * arr[3] * arr[4]);\n newArray.push(arr[0] * arr[2] * arr[3] * arr[4]);\n newArray.push(arr[1] * arr[0] * arr[3] * arr[4]);\n newArray.push(arr[1] * arr[2] * arr[0] * arr[4]);\n newArray.push(arr[1] * arr[2] * arr[3] * arr[0]);\n return console.log(newArray);\n}", "function func9(inputArray){\n for(var i=0; i<inputArray.length; i++){\n inputArray[i]*=inputArray[i];\n }\n return inputArray;\n}", "function doubleOddNumbers(arr){\n let newValue = []\n let oddNums = []\n return arr.filter( (number, index) => {\n return index % 2 !== 0;\n })\n .map((value) => {\n return value * 2\n })\n // return newValue\n}", "function squareIt() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tnewArray.push(oldArray[i] * oldArray[i]);\n\t}\n}", "function mathsGetHarder(numOne, numTwo, numThree) {\n console.log('numOne is ' + numOne);\n console.log('numTwo is ' + numTwo);\n console.log('numThree is ' + numThree);\n var oneTimesTwo = numOne * numTwo;\n var twoOverThree = numTwo / numThree;\n var sum = numOne + numTwo + numThree;\n var results = [sum, oneTimesTwo, twoOverThree];\n return results;\n // return [sum, oneTimesTwo, twoOverThree];\n}", "function squares(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] = array[i] * array[i];\n \n }\n return array;\n}", "function returnSecondHalf(array) {\n\t\t// var length = array.length / 2;\n\t\t// var result = [];\n\n\t\t// for (var i = length; i < array.length; i++) {\n\t\t// \tresult.push(array[i]);\n\t\t// }\n\t\t// return result;\n\n\t\treturn numbers.slice(numbers.length / 2);\n\t}", "function doubler(arr){\n var darr = [];\n for(e in arr){\n darr[e] = arr[e] * 2;\n }\n return darr;\n}", "function scalethearray(arr,y){\n for(var i=0;i<arr.length;i++){\n arr[i]=arr[i]*y\n }\n return arr;\n}", "function doubleTrouble(arr){\n var newArray = [];\n for (var i=0; i<arr.length; i++) {\n newArray.push(arr[i], arr[i])\n }\n return newArray;\n}", "function maps(arr) {\n const doubled = arr.map(num => num * 2)\n return doubled\n}", "function arrayMultiplyAgain(num, arr) {\n const newArr = arr.map(item => item * num)\n return newArr\n}", "function multiplyArray(testArray){ //eslint-disable-line\n // the first element is the product of the numbers in the array,\n // numbers = testArray[0]...testArray[2]\n // product function returns array, value is stored at first element\n var productIndex0Index1 = multiply(testArray[0], testArray[1]); //returns array, value is stored at first element\n var productToArray = multiply(productIndex0Index1[0], testArray[2]); //returns array, value is stored at first element\n console.log('productIndex0Index1 array: ', productIndex0Index1);\n console.log('productToArray array:', productToArray);\n// the second element is a string = 'The numbers 2,3,4 have a product of 24.'\n var returnIndex1Element = 'The numbers ' + testArray[0] + ',' + testArray[1] + ',' + testArray[2] + ' have a product of ' + productToArray[0] + '.';\n console.log('returnIndex1Element is: ', returnIndex1Element);\n// returns an array [product, string]\n return [productToArray[0], returnIndex1Element];\n}", "function square(arr){\n for(var i=0; i<arr.length;i++){ \n arr[i]=arr[i]*arr[i]; \n } \n return arr;\n}", "function squares(arr){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i]*arr[i];\n }\n return arr;\n}", "function squareValues(squareArray) {\r\n var length = squareArray.length;\r\n for (var i = 0; i < length; i++) {\r\n squareArray[i] *= squareArray[i];\r\n }\r\n console.log(\"\\n\\nSquare the Values: [1, 5, 10, -2]\")\r\n console.log((squareArray))\r\n}", "function getData() {\n var doubledArr = [];\n var data = [\"2\", \"4\", \"6\", \"8\", \"10\"]; // the local variable data declared in getData();\n\n function doubleData() { // doubleData(); is the closure, the inner function that can access data\n for (var i = 0; i < data.length; i++) {\n doubledArr.push( Math.floor( data[i] * 2 ));\n }\n return doubledArr;\n }\n return doubleData();\n}", "function elementsTimesTwo(element){\n //returns an array with each value multiplied by 2\n var newElement = [];//note, believe this isn't needed, could just return element w/out need to push\n for (let i = 0; i < element.length; i++) {\n element[i] *= 2;\n newElement.push(element[i]);\n }\n return newElement;\n}" ]
[ "0.77172464", "0.7579092", "0.7492879", "0.7491129", "0.7439699", "0.7303694", "0.7303283", "0.7300281", "0.7295633", "0.72907454", "0.727625", "0.72680783", "0.72368765", "0.72162324", "0.7143058", "0.7113988", "0.70902026", "0.70765805", "0.6991664", "0.69311833", "0.691632", "0.6901176", "0.6870445", "0.68629706", "0.6830426", "0.68248504", "0.68166006", "0.67918783", "0.67723477", "0.667548", "0.6655877", "0.6626916", "0.6609158", "0.6599259", "0.65973216", "0.6587794", "0.6587794", "0.6527534", "0.65050995", "0.64769715", "0.6420135", "0.6406381", "0.6394681", "0.6394131", "0.6341782", "0.6335828", "0.6308929", "0.62789094", "0.62789094", "0.6264607", "0.626117", "0.6243135", "0.6242097", "0.62372744", "0.62253267", "0.6222085", "0.61699915", "0.6165684", "0.61629415", "0.6149818", "0.61398864", "0.61210537", "0.6119291", "0.60793185", "0.6070645", "0.6048408", "0.60438526", "0.6038693", "0.60102636", "0.5974942", "0.59681803", "0.59543693", "0.59510195", "0.5937424", "0.5875372", "0.5873146", "0.5867411", "0.5849731", "0.58436084", "0.5838145", "0.58300495", "0.5821923", "0.5816898", "0.5812532", "0.58053416", "0.5803722", "0.57984173", "0.57869697", "0.5779645", "0.57791626", "0.57786345", "0.57760733", "0.57537174", "0.575043", "0.5749146", "0.57446074", "0.5735536", "0.5735185", "0.57325083", "0.5727942" ]
0.65322644
37
console.log(doubleVal([1,2,3])); Challenge 5 Count Positives Given an array of numbers, create a function to replace the last value with the number of positive values found in the array. Example, countPositives([1,1,1,1]) changes the original array to [1,1,1,3] and returns it.
function countPositives(arr) { var count = 0; for(var i = 0; i < arr.length; i++) { arr[i] > 0 ? count++ : false; } arr[arr.length - 1] = count; return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function countPositives(array){\n let positiveCount = 0;\n for(var i = 0; i < array.length; i++){\n if(array[i] > 0){\n positiveCount++;\n }\n array[array.length - 1] = positiveCount;\n }\n return array;\n}", "function countPositives(array){\n let counter = 0;\n for(let i = 0; i < array.length; i++){\n if(array[i] > 0){\n counter = counter + 1;\n }\n array[array.length - 1] = counter;\n }\n return array;\n}", "function countPositives(arr){\n var positives = 0\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n positives +=1\n }\n }\n arr[arr.length-1] = positives\n console.log(arr)\n}", "function countPositives(arr){\n\nvar positiveArray = arr;\nvar counter = 0;\n\n\tfor(var num = 0; num < positiveArray.length; num++) {\n\t\tif (positiveArray[num] > 0){\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tpositiveArray[positiveArray.length-1] = counter;\n\nconsole.log(positiveArray);\n\n}", "function countPositivesAndReplace(array) {\n var positivesCounter = 0;\n\n for (var num in array) {\n if (array[num] > 0) {\n positivesCounter++;\n }\n }\n \n array[array.length - 1] = positivesCounter;\n return array;\n}", "function countPositives(arr){\n var count = 0;\n for(var i=0;i<arr.length;i++){\n if(arr[i]>0){\n count = count + 1;\n }\n }\n arr[arr.length-1] = count;\n return arr;\n}", "function countPositives(arr){\n var count = 0\n for(var i = 0; i < arr.length; i++){\n if(arr[i] >= 0){\n count++\n }\n }\n arr[arr.length-1] = count\n return arr\n}", "function countPositives(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n count++\n }\n }\n arr[arr.length-1] = count\n return arr\n}", "function countPositives(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n count ++;\n }\n }\n arr[arr.length - 1] = count;\n return arr;\n}", "function CountPositives(arr) {\n var counter = 0;\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n counter++;\n }\n }\n arr[arr.length - 1] = counter;\n return arr;\n }", "function countPositive(arr){\n var count = 0\n for (var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n count++\n }\n }\n arr[arr.length - 1] = count\n return arr\n}", "function countPositive(arr){\n var count = 0;\n for(var i =0; i < arr.length; i++){\n if(arr[i] > 0){\n count++;\n }\n }\n arr[arr.length-1] = count;\n console.log(arr);\n}", "function countPositives(arr) {}", "function countPositives(positiveValues){\n var positiveCount = 0;\n for (let i = 0; i < positiveValues.length; i++) {\n if (positiveValues[i] > 0){\n positiveCount++\n }\n }\n return positiveCount;\n}", "function countPositives(arr) {\n var countPositives = 0;\n\n for(var i=0;i<arr.length;i++){\n if(arr[i]>=0){\n countPositives = countPositives+arr[i];\n }\n }\n\n arr.pop(arr[arr.length-1]);\n arr.push(countPositives);\n\n return arr;\n\n}", "function bePositive(arr){\nvar positiveArr = []\n\nfor ( var i=0; i< arr.length; i++){\n if(arr[i] < 0){\n var newInd = arr[i] * -1;\n \n positiveArr.push(newInd);\n } else {\n positiveArr.push(arr[i]) \n }\n }\n \nreturn positiveArr\n}", "function countNegatives(negativeValues){\n var negativeCount = 0;\n for (let i = 0; i < negativeValues.length; i++) {\n if (negativeValues[i] < 0){\n negativeCount++\n }\n }\n return negativeCount;\n}", "function countpos(array){\n var count = 0\n for(var i=0;i<array.length;i++){\n if(array[i] > 0){\n count = count + 1;\n } \n }\n array[array.length-1] = count;\n console.log(array);\n}", "function positive(arr) {\n var pos = 0;\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n pos++;\n }\n (arr[arr.length - 1]) = pos;\n }\n return arr;\n}", "function countPositivesSumNegatives(input) {\n // 0) if the array is empty or null, return an empty array\n if (input === null || input.length === 0) {\n let emptyArray = []\n return emptyArray\n }\n \n // 1) count the positive numbers\n // -- start the counter at zero\n let counter = 0\n // -- go through each number one at a time\n // -- start an index at 0 \"INITIALIZER\"\n // -- the number to work with is the element at position \"index\" \"CODE INSIDE THE BRACES\"\n // -- use that number \"CODE INSIDE THE BRACES\"\n // -- when done with the number, increment the index by one \"INCREMENTER\"\n // -- see if we went past the end of the array. If so, stop \"COMPARISON\"\n // -- otherwise go back to the step \"use that number\"\n for(let index = 0; index < input.length; index++) {\n // -- if that number is positive, add one to a counter\n if (input[index] > 0) {\n counter++\n }\n }\n // -- our answer is that counter\n\n // 2) sum the negative numbers\n // -- start a sum at 0\n let sum = 0\n // -- go through each number one at time\n for(let index = 0; index < input.length; index++) {\n // -- if that number is negative, add the number to sum\n let element = input[index]\n if (element < 0) {\n sum += element\n }\n }\n // -- our answer is that sum\n \n return [counter, sum];\n}", "function countP(arr) {\n var sum = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n sum++;\n }\n }\n\n arr[arr.length - 1] = sum;\n\n return arr;\n}", "function noNeg(arr){\n var positiveArr = []\n\nfor ( var i=0; i< arr.length; i++){\n if(arr[i] < 0){\n var newInd = arr[i] * 0;\n \n positiveArr.push(newInd);\n } else {\n positiveArr.push(arr[i]) \n }\n }\n \nreturn positiveArr\n}", "function signFlipCount(array){\n var count = 0;\n for(var i = 1; i < array.length; i++){\n var prev = array[i-1];\n var curr = array[i];\n //if (prev < 0 && curr > 0 || prev > 0 && curr < 0)\n if(Math.sign(curr) * Math.sign(prev) < 0){\n count +=1;\n }\n }\n return count;\n}", "function countPositivesSumNegatives(arr) {\n let count = 0;\n let sum = 0;\n if (arr == null || arr.length == 0 ) return [];\n for (let i = 0; i < arr.length; i++){\n if (arr[i] > 0) count++;\n else if (arr[i] < 0) sum += arr[i];\n }\n return [count, sum];\n}", "function positiveNumbers(posArray) {\n\n}", "function negativeValues(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n console.log(arr); //or: return arr;\n}", "function sumPos(array) {\n for (var i = 0; i < array.length; i ++) {\n if (array[i] > 0) {\n array [i] *= 2;\n }\n }\n return array;\n}", "function countpositives(arr){\n var count=0;\n for(var i=0;i<arr.length;i++){\n if(arr[i]>0){\n count+=1;\n }\n arr.pop();\n arr.push(count);\n }\n return arr;\n}", "function countPositivesSumNegatives(input) {\r\n\tif (!input || input.length < 1) return [];\r\n\treturn [input.filter(val => val > 0).length, input.filter(val => val < 0).reduce((acc, cur) => acc + cur, 0)];\r\n}", "function countPositivesSumNegatives(input) {\n let result\n if (input == null || input.length == 0 || input == [] || input == undefined) {\n return result = []\n } else {\n const neg = input.filter(x => x < 0).reduce((a, b) => a + b)\n const pos = input.filter(x => x > 0).length\n result = [pos, neg]\n return result\n }\n\n}", "function countPos(arr){\n var count = 0;\n for(e in arr){\n if(arr[e] > 0){\n count++;\n }\n }\n arr[arr.length-1] = count;\n return arr;\n}", "function firstDuplicateValue(array) {\n for (let value of array) {\n let absVal = Math.abs(value) \n // if value at index is NEGATIVE\n if (array[absVal - 1] < 0) {\n // ensure returned value is not negative\n return absVal;\n }\n // if value at index is NOT negative\n else {\n // set value at index to be negative\n array[absVal - 1] *= -1;\n }\n }\n return -1;\n }", "function posCountNegSum (arrayc) {\n\tlet count = 0;\n\tfor (let int = 0; int < arrayc.length -1; int++) {\n\t\tif (arrayc[int] > 0) {\n\t\t\tcount++\n\t\t}\n\t\t else if (arrayc[int] < 0)\n\t\t{\n\t\t\treturn arrayc[int] + arrayc[int +1];\n\t\t}\n\t}\n\treturn count;\n}", "function noNegatives(arr) {\n for (var idx = 0; idx < arr.length; idx++) {\n if (arr[idx] < 0) {\n arr[idx] = 0;\n }\n }\n console.log(arr);\n}", "function countPosi(x) {\n var count = 0\n for ( var i = 0 ; i<x.length ; i++ ) {\n if (x[i]>0) {\n count++\n }\n } return count\n}", "function negatives(array) {\n for (let i = 0; i < array.length; i++) {\n if(array[i] < 0) { \n array[i] = 0;\n }\n }\n return array;\n}", "function negative(arr){\n let newArr=[]\n for (let i = 0; i < arr.length; i++){\n if (arr[i] > 0){\n newArr.push(arr[i]*-1)\n }\n else {\n newArr.push(arr[i])\n }\n }\n return newArr\n}", "function positives(arr) {\n let result = [];\n each(arr, function(num) {\n Math.sign(num) ? result.push(num) : undefined;\n })\n return result;\n}", "function plusMinus(arr) {\n let countPos = 0;\n let countNeg = 0;\n let countZero = 0;\n arr.forEach(num => {\n (num > 0) ? countPos++ : \n (num < 0) ? countNeg++ :\n countZero++;\n })\n console.log((countPos / arr.length).toFixed(6) + '\\n' +\n (countNeg / arr.length).toFixed(6) + '\\n' + \n (countZero / arr.length).toFixed(6));\n}", "function sumPositiveNumbers(array) {\n // let sum = 0;\n // for (let element of array) {\n // if (element > 0) {\n // sum += element;\n // }\n // }\n // return sum;\nreturn array.filter((item)=>item>0).reduce((accumulator, currentValue)=>accumulator+currentValue,0);\n}", "function sumPositive(array) {\n let array2 = [];\n for(val of array) {\n if(val > 0) {\n array2.push(val);\n }\n }\n return array2;\n}", "function positiveNumnbers(arr) {\n positives = [];\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] >= 0) {\n positives.push(arr[i]);\n }\n }\n console.log(positives);\n}", "function negatives(arr) {\n for (var i=0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] = 0;\n }\n }\n return arr;\n}", "function negativevalues(arr)\r\n{\r\n\tfor(var i=0;i<arr.length;i++)\r\n\t{\r\n\t\tif (arr[i]<0)\r\n\t\t{\r\n\t\t\tarr[i]=0;\r\n\t\t}\r\n\t}\r\n\r\n\t\tconsole.log (\"Removing negatives\",arr);\r\n}", "function sumPositive(array){\n var sum = 0;\n for(i=0; i < array.length; i ++){\n if (array[i] > 0) {\n sum = sum + array[i] \n }\n }\n return sum\n}", "function plusMinus(arr) {\n let negatives = 0;\n let positives = 0;\n let zeros = 0;\n arr.forEach(el => {\n if(el < 0) negatives++;\n if(el>0) positives++;\n if(el===0) zeros++;\n });\n function printRes(numberType) {\n console.log(numberType/arr.length);\n }\n printRes(positives);\n printRes(negatives);\n printRes(zeros);\n}", "function solution(A) {\n // write your code in JavaScript (Node.js 8.9.4)\n // [1,0] . [0,1]\n let f = A[0];\n let count = 0;\n let getOCount = getCount(A, 1);\n let getZCount = getCount(A, 0);\n console.log(getOCount + \" \" + getZCount);\n if (getOCount >= getZCount) {\n for (let i = 0; i < A.length - 1; ++i) {\n if (A[i] === A[i + 1]) {\n if (A[i] === 1) {\n A[i + 1] = 0;\n } else {\n A[i + 1] = 1;\n }\n count++;\n }\n }\n } else {\n for (let i = 0; i < A.length - 1; ++i) {\n if (A[i] === A[i + 1]) {\n if (A[i + 1] === 1) {\n A[i] = 0;\n } else {\n A[i] = 1;\n }\n count++;\n }\n }\n }\n return count;\n}", "function sumPositive(array){\n var sum = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] >= 0) {\n sum += array[i];\n }\n }\n return sum;\n}", "function plusMinus(arr) {\r\n var posN = 0;\r\n var negN = 0;\r\n var zerN = 0;\r\n\r\n for (var x = 0; x < arr.length; x++) {\r\n if (arr[x] > 0) {\r\n posN += 1;\r\n } else if (arr[x] < 0) {\r\n negN += 1;\r\n } else {\r\n zerN += 1;\r\n }\r\n }\r\n console.log((posN/arr.length).toFixed(6));\r\n console.log((negN/arr.length).toFixed(6));\r\n console.log((zerN/arr.length).toFixed(6));\r\n}", "function countPositivesSumNegatives(input) {\n\tif (!input || input.length === 0) return [];\n\t// filter out the positives and get the length\n\tlet positive = input.filter((element) => element > 0).length;\n\t// filter out the negatives and total them up\n\tlet negative = input.filter((element) => element < 0).reduce((sum, ele) => sum + ele, 0);\n\t// return the new array\n\treturn [positive, negative];\n}", "function sumPositive(array) {\n var sum = 0;\n for (var i = 0; i < array.length; i++) {\n var element = array[i];\n if (element > 0) {\n sum += element;\n }\n }\n return sum;\n}", "function replaceNegNum(arr) {\n var negNum = arr.map(function(elem){\n if (elem<0){\n elem = 0;\n }\n return elem;\n });\n return negNum; \n}", "function sumOfPositiveNumbers(array) {\n var sum = 0\n for (var i = 0; i < array.length; i++) {\n var element = array[i];\n if (element > 0) {\n sum += element\n }\n }\n return sum\n}", "function firstDuplicateValue(array) {\n // Since all of the values are between 1 and N. \n for(let i = 0; i < array.length; i++) {\n\t\tlet map_index = Math.abs(array[i]) - 1; \n\t\tif(array[map_index] < 0) return map_index + 1;\n\t\telse array[map_index] *= -1; \n\t}\n\treturn -1; \n}", "function countPositivesSumNegatives(input) {\n if (input == null || input.length == 0) return []\n\n var positive = 0\n var negative = 0\n\n for (var i = 0, l = input.length; i < l; ++i) {\n if (input[i] > 0) ++positive\n else negative += input[i]\n }\n\n return [positive, negative]\n}", "function positiveSum(arr){\nreturn arr\n .filter(positivenumbers => positivenumbers > 0)\n .reduce((a,b) => a + b, 0);\n}", "function count(array){\n if(array.length === 1)\n return 1;\n else{\n array.pop();\n return 1 + count(array);\n }\n}", "function countPositivesSumNegatives(input) {\n if (!input || input.length === 0) {\n return []\n }\n\n let positives = input.filter(x => x > 0)\n let negatives = input.filter(x => x < 0)\n\n return [positives.length, negatives.reduce((sum, x) => sum + x, 0)]\n}", "function getPositives2(arr){\n arr.filter(isPositive).forEach(function(entry) {console.log(entry);});\n}", "function count(xs) {\n return foldp(function(x, y) {\n return x + 1\n }, 0, xs)\n}", "function positiveSum(arr) {\n let sum = 0\n arr.map( num => num > 0 ? sum += num : null)\n return sum\n }", "function sumZeroForMethod(arr) {\n let i = 0;\n for (let j = 0; j < arr.length; j++) {\n if (arr[i] !== arr[j]) {\n i++;\n arr[i] = arr[j];\n }\n }\n\n return i + 1;\n}", "function zeroOutNegativeNums(arr){\n for (let i =0; i<arr.length;i++){\n if (arr[i] < 0) {\n arr[i] = 0; \n }\n }\n return arr;\n}", "function determineMissingVal(array){\n for(var i=0; i<array; i++)\n if(i + 1 !== i + 1){\n return (i + 1)\n }\n }", "function negativeNumbers (arr){\n for (var i=0; i<arr.length; i++){\n if(arr[i]<0){\n arr[i]=0;\n }\n }\n\n return arr;\n}", "function positives (arr){\n var positiveNums = []\n var negativeNums = []\n for ( let i = 0 ; i < arr.length ; i ++){\n if ( arr[i] > 0){\n positiveNums.push(arr[i])\n }\n negativeNums.push(arr[i])\n }\n return positiveNums\n }", "function posSum(array){\n var sum= 0;\n var post=0;\n if(array.length===0){\n return 0;\n }\n if ( array[0]>0){\n post=array.splice(0,1)[0]\n }else{\n post=0;\n array.splice(0,1)\n }\n return sum+post+posSum(array)\n}", "function sumPositiveNumbers(array) {\n\tlet i;\n\tlet sum=0;\n\tfor(i=0;i<array.length;i++){\n\t\tif(array[i]>=0){\n\t\tsum+=array[i]\n\t\t}\n\n\t}\n\treturn sum;\n}", "function posSum(array){\n\tif (array.length===0){\n\t\treturn 0\n\t}else {\n\t\tif(array[0] <0) {\n\t\treturn 0 +posSum(array.splice(1))\n\t}\n\treturn array[0]+posSum(array.splice(1))\n}\n}", "function removeNegatives (array) {\n if(!(array instanceof Array)) {return 'Please pass an array.'};\n let copyTo;\n let negativeCount = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] < 0) {\n negativeCount++;\n copyTo = i;\n break;\n };\n };\n if (negativeCount > 0) {\n for (let j = i + 1; j < array.length; j++) {\n if (array[j] < 0) {\n negativeCount++;\n } else {\n array[copyTo] = array[j];\n copyTo++;\n };\n };\n array.length -= negativeCount;\n };\n return array;\n}", "function positiveSum(arr) {\n return arr.reduce((r, a) => (a > 0 ? r + a : r), 0);\n}", "function solution(A) {\n // write your code in JavaScript (Node.js 8.9.4)\n if (A.length === 1) {\n return 1;\n }\n\n let left = 0;\n let right = 0;\n for (let i = 0; i < A.length; i++) {\n if (A[i] >= 0) {\n left = i;\n right = i;\n break;\n } else {\n A[i] *= -1;\n }\n }\n\n let lastVal = A[left];\n let nextVal = lastVal;\n let count = 1;\n while (left >= 0 && right < A.length) {\n if (A[left] !== A[right] && lastVal !== nextVal) {\n count++;\n }\n\n if (left > 0 && A[left] < A[right]) {\n lastVal = A[left];\n left--;\n nextVal = A[left];\n } else if (right < A.length - 1 && A[right] < A[left]) {\n lastVal = A[right];\n right++;\n nextVal = A[right];\n } else if (left > 0) {\n lastVal = A[left];\n left--;\n nextVal = A[left];\n } else if (right < A.length - 1) {\n lastVal = A[right];\n right++;\n nextVal = A[right];\n } else {\n break;\n }\n }\n\n return count;\n}", "function solution(A) { \n var len = A.length,\n arr = [],\n value, i;\n \n for(i = 0; i < len; i++){\n value = A[i];\n if(value > 0){\n arr[value] = true;\n }\n }\n for(i = 1; i < arr.length; i++){\n if(typeof arr[i] === \"undefined\"){\n return i;\n }\n }\n return i;\n}", "function outlookNegative(arr) {\n\tvar newArr = [];\n\tnum = 0;\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (arr[num] > 0) {\n\t\t\tnewArr.push(arr[num] * -1);\n\t\t} \n\t\telse {\n\t\t\tnewArr.push(arr[num]);\n\t\t}\n\t}\n\n\tconsole.log(newArr);\n\treturn newArr;\n}", "function positiveSum(arr) {\n\treturn arr.filter(val => val > 0).reduce((acc, cur) => acc + cur, 0);\n}", "function plusMinus(arr) {\n // Write your code here\n let length = arr.length\n let positiveCount = 0\n let negativeCount = 0\n let zeroCount = 0\n \n for(let i =0; i < length; i++){\n if (arr[i] > 0){\n positiveCount ++\n }\n else if (arr[i] < 0){\n negativeCount ++\n }\n else if (arr[i] == 0){\n zeroCount ++\n }\n }\nlet negRatio = (positiveCount/length)\nlet posRatio = (negativeCount/length)\nlet zeroRatio = (zeroCount/length)\n\nconsole.log(negRatio.toFixed(6))\nconsole.log(posRatio.toFixed(6))\nconsole.log(zeroRatio.toFixed(6))\n}", "function arrayChange(inputArray) {\n let c = 0;\n for(let i=0; i < inputArray.length; i++){\n if(inputArray[i] >= inputArray[i+1]){\n let dif = inputArray[i] - inputArray[i + 1];\n inputArray[i + 1] = inputArray[i] + 1;\n c += dif+1;\n }\n }\n \n return c;\n}", "function perspectiva(arrayNegativo) {\n for (let i = 0; i < arrayNegativo.length; i++) {\n if ( arrayNegativo[i] < 0 ) {\n console.log(\"Encontrado Negativo: \", arrayNegativo[i])\n } else {\n console.log(\"Encontrado Positivo: \", arrayNegativo[i])\n arrayNegativo[i] = arrayNegativo[i] * -1\n }\n }\n for (let x = 0; x < arrayNegativo.length; x++) {\n console.log(\"Posicion en el Array #[\"+(x)+\"]: \", arrayNegativo[x]) \n }\n return arrayNegativo\n}", "function increaseArr(arr) {\n let index;\n for(let i = 0; i < arr.length; i++) {\n if(arr[i+1] - arr[i] < 0) {\n index = i;\n break;\n } else {\n index = -1;\n }\n }\n return index;\n }", "function outlookNegative(arr){\n var newArr = []\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n newArr.push(arr[i] * -1)\n }else{\n newArr.push(arr[i])\n }\n }\n return newArr\n}", "function Negativa(x) {\n for (i = 0; i < x.length; i++) {\n x[i] = x[i] * -1;\n if (x[i] > 0) {\n x[i] = x[i] * -1;\n }\n }\n return (x);\n\n}", "function countPositivesSumNegatives(input) {\n if (!input || input == \"\") {\n return []\n }\n let count = 0\n let sum = 0\n for (let i = 0; i < input.length; i++) {\n if (input[i] > 0) {\n count += 1\n }\n if (input[i] < 0) {\n sum += input[i]\n }\n }\n\n return [count, sum]\n}", "function positiveSum(array) {\n // Initiate a total sum variable\n // Loop through the array of numbers\n // If the number is positive, add to the running sum\n var total = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] > 0) {\n total += array[i];\n }\n }\n return total;\n}", "function countPositivesSumNegatives(input) {\n if (input == null || input.length == 0)\n return [];\n \n var positive = 0;\n var negative = 0;\n \n for (var i=0, l=input.length; i<l; ++i)\n {\n if (input[i] > 0)\n ++ positive;\n else\n negative += input[i];\n }\n \n return [positive, negative];\n}", "function arrayOfIntegers(arr){\n let positives=0;\n let negatives=0;\n let result = [];\n if (arr==null || arr==[]){\n console.log(\"#3: []\");\n }else{\n for (let i=0;i<arr.length;i++){\n if(arr[i]>0){\n positives++;\n }else if(arr[i]<0){\n negatives+=arr[i];\n }\n result[0]=positives;\n result[1]=negatives;\n }\n console.log(\"#3: \" + result);\n }\n}", "function positiveSum(arr) {\n var summation = 0;\n for(i=0; i<arr.length; i++){\n if(arr[i] > 0){\n summation += arr[i];\n }\n }\n return summation; \n}", "function positiveSum(arr) {\r\n return arr.filter( x => {\r\n if(x >= 0) return x;\r\n }).reduce( (a, b) => {\r\n return a + b;\r\n }, 0);\r\n}", "function negit(arr){\n newArr = [];\n for(e in arr){\n if(arr[e] <= 0){\n newArr[e] = arr[e];\n } else{\n newArr[e] = arr[e]*-1;\n }\n }\n return newArr;\n}", "function plusMinus(arr) {\n const n = arr.length\n const precision = 6\n\n const plus_count = arr.filter(x => x > 0).length;\n const negative_count = arr.filter(x => x < 0).length;\n const zero_count = arr.filter(x => x == 0).length;\n\n console.log((plus_count/n).toFixed(precision))\n console.log((negative_count/n).toFixed(precision))\n console.log((zero_count/n).toFixed(precision))\n}", "function positiveSum(arr) {\ntotal = 0;\n for (i = 0; i < arr.length; i++) {\n if(arr[i] > 0) {\n total += arr[i];\n}\n}\nreturn total;\n}", "function getPositives(ar)\n{\n temp=[]\n for(x of arr){\n if(x>=0)\n temp.push(x)\n }\n return temp\n}", "function positiveSum(arr) {\n\tlet sum = 0;\n\n\tarr.forEach(n => {\n\t\tif (n > 0) sum += n;\n\t});\n\n\treturn sum;\n}", "function multiplyPositiveElementsInArray(arr) {\n \n for (let i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n arr[i] = arr[i] * 2;\n }\n }\n return arr;\n}", "function countConsOnes(input){\n let prevMax = 0, curCount = 0;\n\n input.map(num =>{\n if(num == 0){\n if(curCount > prevMax){\n prevMax = curCount;\n }\n curCount = 0;\n }else{\n curCount++;\n }\n });\n\n return prevMax > curCount ? prevMax : curCount; \n}", "function plusMinus(arr) {\n var positive = 0\n var negative = 0\n var zero = 0\n for (var i = 0; i < arr.length; i++){\n if (arr[i] < 0) {\n negative++\n } else if (arr[i] > 0) {\n positive++\n }\n else if (arr[i] === 0) {\n zero++\n }\n }\n return(positive/arr.length + \"\\n\" + negative/arr.length + \"\\n\" + zero/arr.length)\n}", "function positiveSum(arr) {\n\t// // filter the arr for positive numbers\n\t// const positive = arr.filter((element) => element > 0)\n\t// // sum up positive array and return it\n\t// return positive.reduce((prev, next) => prev + next, 0);\n\treturn arr.filter((ele) => ele > 0).reduce((prev, next) => prev + next, 0);\n}", "function ex_1_I(a) {\n var tot = 0;\n for(i = 0; i < a.length; ++i) {\n var x = a[i];\n if (x > 0) {\n tot += x;\n } else {\n return tot;\n }\n }\n return tot;\n}", "function zeroNegVals(arr){\n for(var i = 0; i < arr.length; i++){\n if (arr[i] < 0){\n arr[i] = 0\n }\n }\n return arr\n}", "function replaceWithZero(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n return arr;\n}", "function negative(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] *= -1;\n }\n }\n return arr\n}" ]
[ "0.74466234", "0.74009466", "0.73136145", "0.72132874", "0.721074", "0.7201334", "0.7177056", "0.7167274", "0.7138698", "0.7105847", "0.70584285", "0.70579547", "0.69307995", "0.6858204", "0.67553943", "0.663731", "0.6604273", "0.6490382", "0.641734", "0.63671535", "0.63666505", "0.63412416", "0.63280195", "0.6300458", "0.6249642", "0.62320733", "0.6193809", "0.61367154", "0.6121012", "0.6120674", "0.6062781", "0.60558826", "0.60345465", "0.60230905", "0.601535", "0.6006206", "0.5996072", "0.5995536", "0.5992144", "0.59823513", "0.5967994", "0.5954608", "0.59525704", "0.59360176", "0.59324235", "0.59175694", "0.5908028", "0.5905428", "0.58960295", "0.5892693", "0.5887719", "0.58670366", "0.5863902", "0.58513606", "0.58457744", "0.58384824", "0.5834612", "0.58237994", "0.5818801", "0.5817807", "0.5815632", "0.5805534", "0.58053887", "0.58012164", "0.5799083", "0.5796866", "0.57967067", "0.57885766", "0.57848305", "0.577128", "0.57624257", "0.57600564", "0.5753708", "0.57403076", "0.5735334", "0.5732672", "0.57150906", "0.5713677", "0.57079357", "0.5707384", "0.57061696", "0.5692835", "0.5692179", "0.56920373", "0.5688661", "0.5686045", "0.56844914", "0.5682507", "0.5680335", "0.56780213", "0.56749827", "0.5671768", "0.5666806", "0.566399", "0.56624347", "0.56529427", "0.565158", "0.56488764", "0.5646825", "0.56436634" ]
0.6948823
12
console.log(countPositives([1,1,1,1])); Challenge 6 Evens and Odds Create a function that accepts an array. Every time that array has three odd values in a row, print "That's odd!". Every time the array has three evens in a row, print "Even more so!".
function evensOdds(arr) { var evenCount = 0; var oddCount = 0; for(var i = 0; i < arr.length; i ++) { if(arr[i] % 2 === 0) { evenCount++; oddCount = 0; evenCount >= 3 ? console.log("Even more so!") : false; } if(arr[i] % 2 !== 0) { oddCount++; evenCount = 0; oddCount >= 3 ? console.log("That's odd!") : false; } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function oddsAndEvens(array){\n let odds = 0;\n let evens = 0;\n for (let i = 0; i < array.length; i++){\n if(array[i] %!2 == 0){\n odds ++;\n evens = 0;\n if(odds > 2){\n console.log(\"That's odd!\");\n }\n } else {\n evens ++;\n odds = 0;\n if(evens > 2){\n console.log(\"Even more so!\");\n }\n }\n }\n}", "function countPositives(arr) {}", "function evensAndOdds(arr){\n var evens = 0\n var odds = 0\n for(var i = 0; i < arr.length; i++){\n if (arr[i] % 2 === 0){\n odds = 0\n evens++\n if(evens === 3){\n evens = 0\n console.log(\"Even more so!\")\n }\n }else{\n evens = 0\n odds++\n if( odds === 3){\n odds = 0\n console.log(\"That's odd!\")\n }\n }\n }\n return arr\n}", "function evens_odds(arr){\n var odds = 0;\n var evens = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i]%2 == 1){\n odds++; evens = 0;\n if(odds == 3){\n console.log(\"That's an odd!\");\n odds = 0;\n }\n }\n else if(arr[i]%2 == 0){\n evens++; odds = 0;\n if(evens == 3){\n console.log(\"Even more so!\");\n evens = 0;\n }\n }\n }\n}", "function findEvensAndOdds(array){\n let oddCount = 0;\n let evenCount = 0;\n for(var i = 0; i < array.length; i++){\n // determine odd values\n if(array[i] % 2 !== 0){\n // determine three in a row\n oddCount++\n evenCount = 0;\n }\n // determine even values \n else { // determine three in a row\n // increment the evenCount\n evenCount++\n oddCount = 0;\n }\n // check the count to see if three in a row - even\n if(evenCount === 3){\n // if the count is equal to 3, reset count to 0\n evenCount = 0;\n console.log(\"Even more so!\");\n }\n // check the count to see if three in a row - odd\n if(oddCount === 3){\n oddCount = 0;\n console.log(\"That's odd!\");\n }\n }\n // return the array\n return array;\n}", "function HowManyEvens (evenArray){\n let count = 0\n\n for (let i = 0; i < evenArray.length; i++){\n if (evenArray[i] % 2 === 0){\n count += 1\n }\n }\n return count\n}", "function evensAndOdds(arr) \n {\n var evenCounter = 0;\n var oddCounter = 0;\n for (var i = 0; i < arr.length; i++) \n {\n if (arr[i] % 2 === 0) \n {\n evenCounter++;\n oddCounter=0;\n }\n if (arr[i] % 2 === 1) \n {\n oddCounter++;\n evenCounter=0;\n }\n if(evenCounter ==3)\n {\n console.log(\"Even more so!\");\n evenCounter = 0;\n }\n if(oddCounter ==3)\n {\n console.log(\"That's odd!\");\n oddCounter = 0;\n }\n }\n }", "function evenandodds(arr){\n var countodds=0;\n var countevens=0;\n for (var i=0;i<arr.length;i++){\n if(arr[i]%2!==0){\n countodds+=1;\n countevens=0;\n \n }\n else if(arr[i]%2==0){\n countevens+=1;\n countodds=0;\n \n }\n// console.log(countodds);\n \nif (countodds==3){\n console.log(\"That's odd\");\n countodds=0;\n}else if(countevens===3){\n console.log(\"Even More so\");\ncountevens=0;\n}\n }\n\n}", "function countOdds (numbers) {\n var i;\n var count = 0;\n for (i = 0; i < numbers.length; i++) {\n if (numbers[i] %2 === 1) {\n count++;\n }\n }\n return count;\n}", "function countOdds(arr) {\n var numberOfOdds = 0;\n\n arr.forEach(function (element) {\n if (element % 2 !== 0) {\n numberOfOdds++;\n }\n });\n\n return numberOfOdds;\n}", "function evensOdds(array){\n\n for(var i = 0; i < array.length; i++){\n if(array[i] % 2 !== 0){\n if(array[i + 1] % 2 !== 0){\n if(array[i + 2] % 2 !==0){\n console.log( \"That's odd\");\n } \n }\n }\n if(array[i] % 2 == 0){\n if(array[i + 1] % 2 == 0){\n if(array[i + 2] % 2 ==0){\n console.log( \"Even more so!\");\n } \n }\n }\n }\n}", "function countEvens(countedValues){\n // returns the number of even numbers\n var counted = 0;// tried empty array [], but first value is undefined bc no starting point\n for (let i = 0; i < countedValues.length; i++) {\n if (countedValues[i] % 2 === 0) {\n counted++;\n }\n }\n return counted;\n}", "function how_many_even(arr) {\n let count = 0;\n for (let i = 0; i < arr.length; i++) {\n if (is_even(arr[i]) == true) {\n\n count++;\n }\n }\n return count;\n}", "function countOdds(countedValues){\n // returns the number of even numbers\n var counted = 0;// tried empty array [], but first value is undefined bc no starting point\n for (let i = 0; i < countedValues.length; i++) {\n if (countedValues[i] % 2 === 1) {\n counted++;\n }\n }\n return counted;\n}", "function evenOdd(arr) {\n\n var oddCount = 0;\n var evenCount = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 != 0) {\n evenCount = 0;\n oddCount++;\n if (oddCount == 3) {\n console.log(\"That's odd!\");\n }\n\n } else if (arr[i] % 2 == 0) {\n oddCount = 0;\n evenCount++;\n if (evenCount == 3) {\n console.log(\"Even more so!\");\n }\n }\n }\n}", "function how_many_even(arr){\n let cnt = 0;\n for(let i = 0; i < arr.length; i++){\n if(is_even(arr[i])){\n cnt++;\n }\n }\n return cnt;\n}", "function EvenOddPrints(arr){\n var count =0\n}", "function EaO(arr){\n var oCount = 0;\n var eCount = 0;\n for(var i=0; i<arr.length; i++){\n if(Math.abs(arr[i]%2) == 1){\n oCount++;\n eCount = 0;\n } else if(Math.abs(arr[i]%2) == 0){\n oCount = 0;\n eCount++;\n } else {\n oCount = eCount = 0;\n }\n\n if(oCount > 2){\n console.log(\"That's odd!\");\n }\n if(eCount > 2){\n console.log(\"Even more so!\");\n }\n }\n // return undefined\n}", "function evensOfOdds(arr) {\n var totalOdds = 0;\n var totalEvens = 0;\n for(i=0;i<arr.length;i++){\n if(arr[i]%2==0){\n totalEvens+=arr[i];\n }\n if(arr[i]%2==1){\n totalOdds+=arr[i];\n }\n } \n if(totalOdds>totalEvens){\n return \"odd are larger\"\n }\n if(totalOdds<totalEvens){\n return \"even are larger\"\n }\n // your code here\n}", "function how_many_even(arr) {\n var count = 0;\n for (var i = 0; i < arr.length; i++) {\n if (is_even(arr[i])) {\n count++;\n }\n }\n return count;\n}", "function evensAndOdds(array) {\n var evensCounter = 0;\n var oddsCounter = 0;\n var response;\n\n for (var num in array) {\n if (array[num] % 2 === 0) { // Even number found\n evensCounter++;\n }\n else {\n oddsCounter++;\n }\n\n if (evensCounter === 3) {\n response = \"That's odd!\";\n break;\n }\n else if (oddsCounter === 3) {\n response = \"Even more so!\";\n break;\n }\n }\n\n return response;\n}", "function countPositives(array){\n let counter = 0;\n for(let i = 0; i < array.length; i++){\n if(array[i] > 0){\n counter = counter + 1;\n }\n array[array.length - 1] = counter;\n }\n return array;\n}", "function countOddsAndEvens(arr) {\n return arr.reduce((acc, num) => {\n console.log(`evens: ${acc.evens}, odds: ${acc.odds} num: ${num}`)\n if (num % 2 === 0) {\n acc.evens += 1\n return acc\n } else {\n acc.odds += 1\n return acc\n }\n }, {\n odds: 0,\n evens: 0\n })\n}", "function oddsAndEvens(arr) {\n for (let i = 0; i < arr.length; i++) {\n (arr[i] % 2 === 0) ? (arr[i]--) : (arr[i]++);\n }\n return arr;\n}", "function how_many_even(arr) {\n var p = [];\n for (i = 0; i < arr.length; i++) {\n if (p % 2 == 0) {\n p.push(arr[i]);\n }\n }\n return p.length;\n}", "function solve(a) {\n\tlet evens = [];\n\tlet odds = [];\n\tlet nums = a.filter(el => {\n\t\treturn typeof el === \"number\";\n\t});\n\tnums.forEach(num => {\n\t\tif (num % 2 === 1) {\n\t\t\todds.push(num);\n\t\t} else {\n\t\t\tevens.push(num);\n\t\t}\n\t});\n\treturn evens.length - odds.length;\n}", "function printNumEvenElements(arr){\r\n var j = 0;\r\n for(var i=0; i<arr.length; i++){\r\n if(arr[i]%2===0){\r\n j++;\r\n }\r\n }\r\n return j;\r\n}", "function howManyEvens(n) {\n let count = 0;\n const str = `${n}`;\n const arr = str.split('');\n\n for (const num of arr) {\n if (num % 2 === 0) {\n count++;\n }\n }\n // console.log(`even count is ${count}`)\n return count;\n}", "function iqTest(numbers){\n const numbersArray = numbers.split(' ').map(Number)\n const evens = numbersArray.filter(number => number % 2 === 0)\n const odds = numbersArray.filter(number => number % 2 !== 0)\n return evens.length > odds.length ? numbersArray.indexOf(odds[0]) + 1 : numbersArray.indexOf(evens[0]) + 1\n}", "function isEven(arr){\n //declare your count\n // loop and inside it...\n if (\"_your_condition_here\"){\n count++\n }\n return count\n}", "function How_many_even(arr){\nvar newarr = [];\nvar count = 0;\nfor(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 === 0){\n newarr.push(arr[i]);\n count++;\n }\n}\nreturn count;\n}", "function oddsAndEvens (nums){\n for(var i = 0; i < nums.length; i++)\n if (nums[i] % 2 === 0){\n evens.push(nums[i]);\n }\n else{\n odds.push(nums[i]);\n }\n \n}", "function returnOdds(array) {\n}", "function countPositives(array){\n let positiveCount = 0;\n for(var i = 0; i < array.length; i++){\n if(array[i] > 0){\n positiveCount++;\n }\n array[array.length - 1] = positiveCount;\n }\n return array;\n}", "function evenOdd1(arr){\n for(let i = 0; i < arr.length - 2; i++){\n if ((arr[i] % 2 == 0) && (arr[i+1] % 2 == 0) && (arr[i+2] % 2 == 0)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - Even more so!`)\n } else if ((arr[i] % 2 == 1) && (arr[i+1] % 2 == 1) && (arr[i+2] % 2 == 1)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - That's odd!`)\n }\n }\n}", "function oddsAndEvens(nums){\n var odds = [];\n var evens = [];\n for(var i = 0; i < nums.length; i++){\n if(nums[i] % 2 === 0){\n evens.push(nums[i]);\n }\n else{\n odds.push(nums[i]);\n }\n }\n return odds;\n}", "function countSheeps(arrayOfSheep) {\n let count=0;\n for (let i=0;i<=arrayOfSheep.length;i++) {\n if (arrayOfSheep[i] === true) {\n count++;\n }\n }\n return count;\n}", "function ideas(array_ideas) {\n \n let good = 0\n for (let i = 0; i < array_ideas.length; i++) {\n if (array_ideas[i] == 'good' && ++good > 2) {\n return 'I smell a series'\n } \n }\n return good ? 'Publis!' : 'Fail!'\n}", "function countSheep(arrayOfSheep) {\n let sheep = 0\n for (let i = 0; i < arrayOfSheep.length; i++) {\n if (arrayOfSheep[i] === true) {\n sheep += 1\n }\n }\n return sheep\n}", "function how_many_even(arrIn){\n let returnNumber = 0;\n for (var i = 0; i < arrIn.length; i ++) {\n if (is_even(arrIn[i])) {returnNumber ++;};\n };\n return returnNumber; \n}", "function countPositives(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n count ++;\n }\n }\n arr[arr.length - 1] = count;\n return arr;\n}", "function countSheeps(arrayOfSheep) {\n // TODO May the force be with you\n\n// counter\n let count = 0\n\n console.log(arrayOfSheep)\n\n// loop through the array\n for(let i = 0; i < arrayOfSheep.length; i++)\n {\n\n console.log(\"i\", i)\n\n// false = count not increasing\n if(findTheSheep(arrayOfSheep[i]))\n {\n\n count = count\n\n// anything else, count increases\n }else{\n\n count++\n\n }\n\n }\n return count;\n}", "function countPositives(arr){\n let count = 0;\n for(let i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n count++\n }\n }\n arr[arr.length-1] = count\n return arr\n}", "function countPositives(arr) {\n var count = 0;\n for(var i = 0; i < arr.length; i++) {\n arr[i] > 0 ? count++ : false;\n }\n arr[arr.length - 1] = count; \n return arr;\n}", "function solve(a){\n var even = 0\n var odd = 0\n for ( let i = 0 ; i<a.length ; i++){\n if ( typeof(a[i]) === \"number\"){\n if (a[i] %2 ===0){\n even ++\n }else{\n odd ++\n }\n }\n }\n return (even-odd);\n }", "function oddCount(n){\n \n return [...Array(n).keys()].filter(i => i%2 !==0).length\n }", "function hasOdds(oddSeq){\n // returns true if there are any odd numbers in the sequence\n // looks like boolean value return\n var hasOddNumbers = [];\n for (let i = 0; i < oddSeq.length; i++) {\n if (oddSeq[i]%2 === 1){\n return true;\n }\n }\n return false;\n}// previous problem helped solve this one problem# 71", "function countSheeps(arrayOfSheeps) {\n var trueCount = 0;\n for(var i = 0; arrayOfSheeps.length; i++) {\n if(arrayOfSheeps[i] === true) {\n trueCount++;\n }\n return trueCount;\n }\n}", "function countPositives(arr){\n var count = 0;\n for(var i=0;i<arr.length;i++){\n if(arr[i]>0){\n count = count + 1;\n }\n }\n arr[arr.length-1] = count;\n return arr;\n}", "function evens(arr) {\n let result = [];\n each(arr, function(num) {\n num % 2 === 0 ? result.push(num) : undefined;\n });\n return result;\n }", "function getEvens(array) {\n var returnOdds = [];\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] % 2 == 0) {\n returnOdds.push(array[i]);\n }\n }\n return returnOdds;\n}", "function countSheep(arrayOfSheep){\n let count = 0;\n for(let i = 0; i<arrayOfSheep.length; i++){\n arrayOfSheep[i] && count++;\n }\n return count;\n}", "function evenOccurrence (arr) {\n // Write your code here, and\n // return your final answer.\n var c = 0\n \n for (var i = 0; i < arr.length; i++){\n c = 0\n //equal or not\n for(var j= 0; j< arr.length; j++){\n if (arr[j] === arr[i])\n c++\n }\n //even occ\n if (c%2 === 0){\n return arr[i]\n }\n }\n return null\n}", "function question0 (array) {\n for (var i = 0; i < array.length; i++){\n\n if (array[i] %2 ===0){\n console.log(array[i])\n }\n }\n}", "function iqTest(numbers){\n const even = [], odd = [];\n numbers = numbers.split(' ').map( x => { return parseInt(x) });\n numbers.map(function(x){\n if(x % 2 == 0)\n even.push(numbers.indexOf(x) + 1)\n else\n odd.push(numbers.indexOf(x) + 1)\n })\n return even.length > odd.length ? odd[0] : even[0]\n}", "function solve(nums) {\n\tlet counter = 0;\n\tfor (let i = 0; i < nums.length; i++) {\n\t\tlet val = nums[i].toString();\n\t\tif (parseInt(val.length) % 2 !== 0) {\n\t\t\tcounter++;\n\t\t}\n\t}\n\treturn counter;\n}", "function evenOddSums() {}", "function iqTest(numbers){\n var OddArrPosition = [];\n var EvenArrPosition = [];\n\n var newArr = numbers.split(\" \") ;\n\n var result= newArr.map(EvenOrOdd);\n function EvenOrOdd(i) {\n if (i % 2 === 0) {\n OddArrPosition.push(newArr.indexOf(i))}\n else {EvenArrPosition.push(newArr.indexOf(i))}\n }\n\n if (OddArrPosition.length == 1){\n var odd = OddArrPosition.join()\n return parseInt(odd)+1;\n }\n else{ var even = EvenArrPosition.join()\n return parseInt(even)+1}\n}", "function evensAndOdds(num) {\n let evenCount = 0;\n let OddCount = 0;\n if (num > 0) {\n for (let i = 0; i <= num; i++) {\n i % 2 === 0 ? (evenCount += 1) : (OddCount += 1);\n }\n }\n console.log(\n `The number of odds are ${OddCount} \\nThe number of even counts are ${evenCount}`\n );\n}", "function iqTest(numbers){\n \n let oddValueFound = 0;\n let oddValueIndex = 0;\n let evenValueFound = 0;\n let evenValueIndex = 0;\n\n\n //place a space at the beginning of the string\n numbers = numbers.split(' ');\n\n //loop through the array to looking for odd / even values\n for(var i = 0; i<numbers.length; i++){\n\n //if the number is even and we already found an odd\n if(numbers[i] % 2 == 0){\n evenValueFound++;\n evenValueIndex = i+1;\n }else{\n oddValueFound++;\n oddValueIndex = i+1;\n }\n }\n //if nothing was found return the first value (that was the answer)\n if(oddValueFound == 1){\n return oddValueIndex;\n }else{\n return evenValueIndex;\n }\n}", "function counOfSquares (arr) {\nlet count = 0;\nfor (let i = 0; i <arr.length; i ++) {\nif ({} .toString.call (arr [i]) === \"[object Number]\")\nif (Math.sqrt (arr [i])% 1 === 0)\ncount ++;\n}\nreturn count;\n}", "function oddCount(num) {\n let count = []\n for (let i = 0; i < num; i++) {\n if (i % 2 === 1) {\n count.push(i)\n }\n }\n return count.length\n}", "function countPositives(arr){\n var count = 0\n for(var i = 0; i < arr.length; i++){\n if(arr[i] >= 0){\n count++\n }\n }\n arr[arr.length-1] = count\n return arr\n}", "function evensAndOdds(number) {\n let even = [];\n let odd = [];\n for (let i = 0; i <= number; i++) {\n if(i % 2 == 0){\n even.push(i);\n }\n else{\n odd.push(i);\n }\n }\n console.log(`even Numbers: ${even.length}`);\n console.log(`odd Numbers: ${odd.length}`);\n }", "function evens(arr) {\n let result = arr.filter(function (num, i, array) {\n return num % 2 === 0;\n });\n return result;\n}", "function iqTest(numbers){\n numbers = numbers.toString().split(' ');\n let odd =[];\n let even= [];\n for(let i=0; i<numbers.length;i++){\n if(numbers[i]%2===0){\n even.push(numbers[i]);\n }\n else{\n odd.push(numbers[i]);\n }\n }\n let num = (even.length===1)?even[0]:odd[0];\n return numbers.indexOf(num)+1;\n}", "function displayOddNumbers(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 1) {\n\t\t\t\tconsole.log(array[i]);\n\t\t\t}\n\t\t}\n\t}", "function hasOdd(array) {\n var length = array.length;\n if (length % 2 == 1) {\n return true;\n } else return false;\n}", "function incrementOdds(arr){\n for(var i=0;i<arr.length;i++){\n if(i%2!==0){\n arr[i]=(arr[i])+1;\n console.log(arr[i]);\n }\n }\n return arr;\n}", "function sumOfEvensAndOddsInArray(number) {\n let sumOfEvens = 0;\n let sumOfOdds = 0;\n for (let i = 0; i <= number; i++) {\n if (i % 2 == 0) {\n sumOfEvens += i;\n } else {\n sumOfOdds += i;\n }\n }\n console.log([sumOfEvens, sumOfOdds]);\n}", "function onlyPositiveOdds(numbs){\n //returns an array containing all the positive evens from the sequence\n var PositiveOddOnly = [];// empty array to store requested values in\n for (let i = 0; i < numbs.length; i++) {\n if (isPositive(numbs[i]) && isOdd(numbs[i])){//CALLING OLDER FUNCTIONS\n PositiveOddOnly.push(numbs[i]);// if check is good, pass into empty array\n }\n }\n return PositiveOddOnly;// show us empty array\n}", "function findOdd(array) {\n let result;\n\n array.forEach(number => {\n if (array.filter(curValue => curValue === number).length % 2 === 1) {\n result = number;\n };\n });\n return result;\n}", "function evenOdd2(arr){\n var len = arr.length - 2,\n i = 0\n while (i < len){\n if ((arr[i] % 2 == 0) && (arr[i+1] % 2 == 0) && (arr[i+2] % 2 == 0 )){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - Even more so!`)\n i += 3\n } else if ((arr[i] % 2 == 1) && (arr[i+1] % 2 == 1) && (arr[i+2] % 2 == 1 )){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - That's odd!`)\n i += 3\n } else {\n i += 1\n }\n }\n}", "function CountPositives(arr) {\n var counter = 0;\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n counter++;\n }\n }\n arr[arr.length - 1] = counter;\n return arr;\n }", "function countPositives(positiveValues){\n var positiveCount = 0;\n for (let i = 0; i < positiveValues.length; i++) {\n if (positiveValues[i] > 0){\n positiveCount++\n }\n }\n return positiveCount;\n}", "function evens(array){\n\tvar newArray= [];\n\tfor (var i = 0; i < array.length; i++){\n\t\tif (array[i]%2 === 0){\n\t\t\tnewArray === newArray.push(array[i]);\n\n\t\t}\n\t}\n return newArray;\n}", "function oddOnesOut(array) {\n const tally = elementCount(array);\n const evensInArr = [];\n\n for(const key in tally) {\n if(tally[key] % 2 === 0) evensInArr.push(key);\n }\n\n return evensInArr;\n}", "function isNice(arr){\nlet flag = true;\nif (arr.length<1){\n flag = false}\n arr.forEach(function(i) {\n if ((arr.includes(i + 1))||(arr.includes(i - 1))) {\n } else {\n flag = false}\n })\n return flag\n}", "function findOdd(a) { \n for (var i = 0; i <a.length; i++ ){\n var current = a[i]; \n var result = 0;\n for (var y =0; y<a.length; y++){\n result = (current === a[y] ? result+1 : result); \n }\n console.log(current + \" -- \" + result);\n if (result % 2 == 1 || result == 1){\n return current;\n }\n }\n}", "function onlyPositiveEvens(numbs){\n //returns an array containing all the positive evens from the sequence\n var PositiveOnly = [];// empty array to store requested values in\n for (let i = 0; i < numbs.length; i++) {\n if (numbs[i] > 0 && numbs[i]%2 === 0){//checking if positive and even\n PositiveOnly.push(numbs[i]);// if check is good, pass into empty array\n }\n }\n return PositiveOnly;// show us empty array\n}", "function oddArr(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (i % 2 == 1) {\n arr[i] += 1;\n console.log(arr[i]);\n }\n }\n return arr;\n}", "function countPositives(arr){\n var positives = 0\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n positives +=1\n }\n }\n arr[arr.length-1] = positives\n console.log(arr)\n}", "function findOdd(array) {\n //happy coding!\n for (let i = 0; i < array.length; i++) {\n let counter = 0;\n\n for (let j = 0; j < array.length; j++) {\n if (array[i] === array[j]) {\n counter++;\n }\n }\n\n if (counter % 2 !== 0) {\n return array[i];\n }\n }\n}", "function evens(arr) {\n // let finalArr =[];\n // for (let i=0; i< arr.length; i++){\n // if(arr[i] % 2 === 0){\n // finalArr.push(arr[i])\n // }\n // }\n // return finalArr\n\n return arr.filter((e) => e%2 === 0)\n\n}", "function countSheeps(arrayOfSheep) {\n return arrayOfSheep.filter(el => el===true).length\n }", "function countTrue(array) {\n let count = 0;\n for (let element of array) {\n if (element) {\n count++;\n }\n }\n return count;\n}", "function evens() {\n for (let i = 0; i < 101; i++) {\n if ((i % 2) === 0) {\n console.log(i); \n } \n }\n}", "function findOdd(arr) {\n // Your code here\n}", "function hasEvens(evenSeq){\n // returns true if there are any even numbers in the sequence\n // looks like boolean value return\n var hasEvenNumbers = [];// thought i would need but ended up not\n for (let i = 0; i < evenSeq.length; i++) {\n if (evenSeq[i]%2 === 0){\n return true;\n }\n }\n return false;\n}", "function countPositives(arr){\n\nvar positiveArray = arr;\nvar counter = 0;\n\n\tfor(var num = 0; num < positiveArray.length; num++) {\n\t\tif (positiveArray[num] > 0){\n\t\t\tcounter++;\n\t\t}\n\t}\n\n\tpositiveArray[positiveArray.length-1] = counter;\n\nconsole.log(positiveArray);\n\n}", "function exercise3(num) {\n var hasEven = false;\n\n num.forEach(function(value) {\n if (value % 2 === 0) {\n hasEven = true;\n }\n });\n return hasEven;\n }", "function punteggio () {\n for (var j = 0; j < casualArray.length; j++) {\n if (casualArray.includes(guessArray[j])) {\n risultato++\n }\n }\n document.write (\"Il tuo punteggio è: \" + risultato);\n}", "function getNumber (array) {\nvar result1, result2, count = 0;\n for (var i = 0; i < array.length; i++) {// 1 // 5 \n if (array[i] % 2 === 0) { // 1 % 2 != 0 // 5 % 2 != 0 //4 % 2 == 0\n result1 = array[i]; // resultEven = 4 \n count++;\n } else { \n result2 = array[i]; // resultOdd = 1 // resultOdd = 5\n }\n }\n switch (count) {\n case 1: console.log(result1); break;\n default: console.log(result2); break;\n }\n}", "function chekOddElements(array) {\n\n if (array.length % 2 == 1) {\n return true;\n }\n return false;\n\n}", "function returnOdds(arr) {\n var oddArr = [];\n for (var i = 1; i <= arr; i += 2) {\n oddArr.push(i)\n };\n return oddArr\n}", "function double23(array){\n var counter1=0;\n var counter2=0;\n \nfor (var i=0; i<array.length; i++){ \n\n if (array[i]==2){\n counter1++;\n \n }else if(array[i]==3){\n counter2++;\n }\n}\nif (counter1==2||counter2==2 ){\nconsole.log(\"true\")\n \n}else{\n console.log(false)\n }\n }", "function findOdd(arr) {\n let n = 0;\n\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n n ^= num;\n }\n\n return n;\n}", "function gameOfThrones(s) {\n s = s.split('').sort();\n var currentCounter = 0;\n var currentCounterChar = '';\n var odds = 0;\n for(var i =0; i < s.length; i++) {\n console.log(s[i])\n if(s[i]==currentCounterChar) currentCounter++;\n else {\n if(currentCounter % 2 != 0) odds++;\n currentCounterChar = s[i];\n currentCounter = 1;\n console.log(odds);\n if(odds>1) return \"NO\";\n }\n }\n if(odds>1) return \"NO\";\n\n return \"YES\";\n\n}", "function countSheeps(arrayOfSheep) {\n return arrayOfSheep.filter(function(value) {\n return value === true;\n }).length;\n}", "function oddsEvens(inputList) {\n var returnList = [];\n for (var i = 0; i < inputList.length; i++) {\n if (inputList[i] % 2 === 1) {\n returnList.push(inputList[i]);\n }\n }\n return returnList;\n}" ]
[ "0.7476276", "0.7471004", "0.743693", "0.7427957", "0.73168045", "0.72451955", "0.7240907", "0.7191294", "0.71418107", "0.71052617", "0.70968753", "0.70245314", "0.69521034", "0.69327223", "0.6863222", "0.6854219", "0.68385756", "0.6825421", "0.6818481", "0.67447007", "0.6707642", "0.6691914", "0.668925", "0.66800034", "0.6673678", "0.66689473", "0.66448456", "0.6624854", "0.6611732", "0.6579605", "0.6565104", "0.6534735", "0.6523797", "0.6518964", "0.6518885", "0.65184844", "0.6507605", "0.65047276", "0.6502249", "0.6497033", "0.645367", "0.6451169", "0.64348966", "0.6411814", "0.6403511", "0.6391472", "0.63889927", "0.63705856", "0.6369459", "0.63557976", "0.6343967", "0.63281846", "0.63221085", "0.6316685", "0.6315724", "0.62923306", "0.62914616", "0.62848234", "0.62772375", "0.6274923", "0.6271776", "0.6268945", "0.6263522", "0.6255151", "0.6243746", "0.62175316", "0.62006336", "0.6195765", "0.61863357", "0.6175837", "0.6167804", "0.61593896", "0.6159073", "0.61571383", "0.6155811", "0.6149511", "0.61447203", "0.6135572", "0.6131156", "0.6114945", "0.6109353", "0.610181", "0.6079303", "0.6055857", "0.60493475", "0.6049217", "0.60474855", "0.6043362", "0.6041755", "0.6036183", "0.60328025", "0.6024625", "0.60102266", "0.600758", "0.60060495", "0.600595", "0.59750986", "0.59627354", "0.59596735", "0.59547555" ]
0.7266939
5
evensOdds([2,1,3,5,4,6,4]); Challenge 7 Increment the Seconds Given an array of numbers arr, add 1 to every other element, specifically those whose index is odd (arr[1], arr[3], arr[5], etc). Afterward, console.log each array value and return arr.
function incrementTheSeconds(arr) { for(var i = 1; i < arr.length; i +=2) { arr[i] = arr[i] + 1; } for(var j = 0; j < arr.length; j++) { console.log(arr[j]); } return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function incrementOdds(arr){\n for(var i=0;i<arr.length;i++){\n if(i%2!==0){\n arr[i]=(arr[i])+1;\n console.log(arr[i]);\n }\n }\n return arr;\n}", "function incrementOdds(arr){\n for(let i = 1; i<arr.length; i+=2){\n arr[i] = arr[i]+1\n }\n return arr\n}", "function oddsAndEvens(arr) {\n for (let i = 0; i < arr.length; i++) {\n (arr[i] % 2 === 0) ? (arr[i]--) : (arr[i]++);\n }\n return arr;\n}", "function oddArr(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (i % 2 == 1) {\n arr[i] += 1;\n console.log(arr[i]);\n }\n }\n return arr;\n}", "function evensAndOdds(arr){\n var evens = 0\n var odds = 0\n for(var i = 0; i < arr.length; i++){\n if (arr[i] % 2 === 0){\n odds = 0\n evens++\n if(evens === 3){\n evens = 0\n console.log(\"Even more so!\")\n }\n }else{\n evens = 0\n odds++\n if( odds === 3){\n odds = 0\n console.log(\"That's odd!\")\n }\n }\n }\n return arr\n}", "function EvenOdd(arr){\n let result = arr[0];\n\n for(let i = 1; i <= arr.length - 1; i++){\n if(i % 2 == 0){\n result += arr[i];\n } else {\n result *= arr[i];\n }\n }\n \n return result;\n}", "function incrementSeconds(arr){\n for(var i = 0; i < arr.length; i++){\n if(i % 2 != 0){\n arr[i] += 1\n }\n console.log(arr[i])\n }\n return arr\n}", "function AddtoOdd(arr){\n for(var i=0;i<arr.length;i++){\n if(arr[i]%2==1){\n arr[i]= arr[i] +1;\n \n \n }\n console.log(arr[i]);\n \n }\n return arr;\n}", "function incrementSeconds(arr) {\n for (var num in arr) {\n if (num % 2 !== 0) { // Every odd index\n console.log(\"index: \" + num + \" incremented [\" + arr[num] + \"->\" + (arr[num]++));\n }\n }\n return arr;\n}", "function evensOdds(array){\n\n for(var i = 0; i < array.length; i++){\n if(array[i] % 2 !== 0){\n if(array[i + 1] % 2 !== 0){\n if(array[i + 2] % 2 !==0){\n console.log( \"That's odd\");\n } \n }\n }\n if(array[i] % 2 == 0){\n if(array[i + 1] % 2 == 0){\n if(array[i + 2] % 2 ==0){\n console.log( \"Even more so!\");\n } \n }\n }\n }\n}", "function incrementSec(arr) {\n\n for (var i = 0; i < arr.length; i++) {\n if (i % 2 != 0) {\n arr[i]++;\n }\n }\n console.log(arr);\n return (arr);\n}", "function evenOddSums(arr) {\r\n const newArr = [0,0]\r\n\r\n arr.forEach(e =>{\r\n e % 2 === 0\r\n ? newArr[0] += e\r\n : newArr[1] += e\r\n })\r\nreturn newArr\r\n}", "function evens_odds(arr){\n var odds = 0;\n var evens = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i]%2 == 1){\n odds++; evens = 0;\n if(odds == 3){\n console.log(\"That's an odd!\");\n odds = 0;\n }\n }\n else if(arr[i]%2 == 0){\n evens++; odds = 0;\n if(evens == 3){\n console.log(\"Even more so!\");\n evens = 0;\n }\n }\n }\n}", "function evenOdd1(arr){\n for(let i = 0; i < arr.length - 2; i++){\n if ((arr[i] % 2 == 0) && (arr[i+1] % 2 == 0) && (arr[i+2] % 2 == 0)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - Even more so!`)\n } else if ((arr[i] % 2 == 1) && (arr[i+1] % 2 == 1) && (arr[i+2] % 2 == 1)){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - That's odd!`)\n }\n }\n}", "function oddsAndEvens(array){\n let odds = 0;\n let evens = 0;\n for (let i = 0; i < array.length; i++){\n if(array[i] %!2 == 0){\n odds ++;\n evens = 0;\n if(odds > 2){\n console.log(\"That's odd!\");\n }\n } else {\n evens ++;\n odds = 0;\n if(evens > 2){\n console.log(\"Even more so!\");\n }\n }\n }\n}", "function incrementSeconds(arr){\n for(var i = 1; i < arr.length; i+=2){\n arr[i] += 1;\n }\n console.log(arr);\n return arr;\n}", "function Increment(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (i % 2 == 1) {\n arr[i] = arr[i] + 1;\n }\n }\n for (var i = 0; i < arr.length; i++) {\n console.log(arr[i]);\n }\n return arr;\n}", "function oddUpEvenDown(array) {\r\n var outputArray = [];\r\n for(var i = 0; i < array.length; i++) {\r\n if(array[i] % 2 === 1) {\r\n var newValue1 = array[i] + 1;\r\n outputArray.push(newValue1)\r\n\r\n } else {\r\n var newValue2 = array[i] - 1;\r\n outputArray.push(newValue2);\r\n }\r\n }\r\n return outputArray;\r\n}", "function incrementTheSeconds(arr){\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (num % 2 == 1) {\n\t\t\tarr[num] = arr[num] +1;\n\t\t}\n\t}\n\t\tconsole.log(arr);\n\t\treturn(arr);\n}", "function evensAndOdds(arr) \n {\n var evenCounter = 0;\n var oddCounter = 0;\n for (var i = 0; i < arr.length; i++) \n {\n if (arr[i] % 2 === 0) \n {\n evenCounter++;\n oddCounter=0;\n }\n if (arr[i] % 2 === 1) \n {\n oddCounter++;\n evenCounter=0;\n }\n if(evenCounter ==3)\n {\n console.log(\"Even more so!\");\n evenCounter = 0;\n }\n if(oddCounter ==3)\n {\n console.log(\"That's odd!\");\n oddCounter = 0;\n }\n }\n }", "function returnOdds(arr) {\n var oddArr = [];\n for (var i = 1; i <= arr; i += 2) {\n oddArr.push(i)\n };\n return oddArr\n}", "function evenOddSums (array) {\n\tlet even = 0;\n let odd = 0;\n\n array.forEach((value) => (value % 2 === 0 ? (even += value) : (odd += value)));\n return [even, odd]\n}", "function incrementsecond(arr){\n for(var i=0;i<arr.length;i++){\n if(i % 2 != 0){\n arr[i] = arr[i] + 1;\n console.log(\"the value is \" + arr[i] + \" and the index is \" + i);\n }\n }\n return arr\n}", "function evenOdd(arr) {\n\n var oddCount = 0;\n var evenCount = 0;\n\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] % 2 != 0) {\n evenCount = 0;\n oddCount++;\n if (oddCount == 3) {\n console.log(\"That's odd!\");\n }\n\n } else if (arr[i] % 2 == 0) {\n oddCount = 0;\n evenCount++;\n if (evenCount == 3) {\n console.log(\"Even more so!\");\n }\n }\n }\n}", "function findOdd(a) { \n for (var i = 0; i <a.length; i++ ){\n var current = a[i]; \n var result = 0;\n for (var y =0; y<a.length; y++){\n result = (current === a[y] ? result+1 : result); \n }\n console.log(current + \" -- \" + result);\n if (result % 2 == 1 || result == 1){\n return current;\n }\n }\n}", "function evenOdd2(arr){\n var len = arr.length - 2,\n i = 0\n while (i < len){\n if ((arr[i] % 2 == 0) && (arr[i+1] % 2 == 0) && (arr[i+2] % 2 == 0 )){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - Even more so!`)\n i += 3\n } else if ((arr[i] % 2 == 1) && (arr[i+1] % 2 == 1) && (arr[i+2] % 2 == 1 )){\n console.log(`(${arr[i]}, ${arr[i+1]}, ${arr[i+2]}) - That's odd!`)\n i += 3\n } else {\n i += 1\n }\n }\n}", "function sumOfOdd(a) {\r\n var sum = 0;\r\n for (var i = 0; i < a.length; i++) {\r\n if (a[i] % 2 === 1) {\r\n sum += a[i];\r\n }\r\n }\r\n return sum;\r\n}", "function evenOddSums(arr) {\n\tlet even = 0;\n\tlet odd = 0;\n\tarr.forEach(val => (val % 2 === 0 ? (even += val) : (odd += val)));\n\treturn [even, odd];\n}", "function doubleOddNumbers(arr) {}", "function IncEvOther(arr){\n for(var i=1; i<arr.length; i+=2){\n arr[i]++; \n }\n console.log(arr);\n return arr;\n}", "function incrementSeconds(array1)\n{\n const incrementSeconds = array1.map(x => (x%2==1) ? x + 1 : x);\n console.log(incrementSeconds)\n}", "function sumOfEvensAndOddsInArray(number) {\n let sumOfEvens = 0;\n let sumOfOdds = 0;\n for (let i = 0; i <= number; i++) {\n if (i % 2 == 0) {\n sumOfEvens += i;\n } else {\n sumOfOdds += i;\n }\n }\n console.log([sumOfEvens, sumOfOdds]);\n}", "function findOdd(arr) {\n let n = 0;\n\n for (let i = 0; i < arr.length; i++) {\n let num = arr[i];\n n ^= num;\n }\n\n return n;\n}", "function getOdds(array) {\n var returnOdds = [];\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] % 2 == 1) {\n returnOdds.push(array[i]);\n }\n }\n return returnOdds;\n}", "function oddNumbers(array) {\n var array = [];\n for(var i = 1; i < array.length; i++){\n if(i % 2 !== 0){\n array.push(i);\n }\n }\n return array;\n}", "function doubleOddNumbers(arr){\n return arr.filter(curVal => curVal%2 !==0).map(curVal => curVal*2);\n}", "function increment2nd(arr) {\n\nfor(var i=0; i<arr.length;i++){\n\n if(i%2!=0){\n arr[i] = arr[i]+1\n // console.log(arr[arr.indexOf(arr[i])]+1);\n }\n}\n return arr;\n}", "function findOddNumber(inputArr){\n let arr = []\n for (const interator of inputArr){\n //console.log(interator);\n if (interator % 2 !== 00) {\n arr.push (interator)\n }\n }\n return arr\n}", "function countOdds(arr) {\n var numberOfOdds = 0;\n\n arr.forEach(function (element) {\n if (element % 2 !== 0) {\n numberOfOdds++;\n }\n });\n\n return numberOfOdds;\n}", "function countOdds (numbers) {\n var i;\n var count = 0;\n for (i = 0; i < numbers.length; i++) {\n if (numbers[i] %2 === 1) {\n count++;\n }\n }\n return count;\n}", "function evensOdds(arr) {\n var evenCount = 0; \n var oddCount = 0;\n for(var i = 0; i < arr.length; i ++) {\n if(arr[i] % 2 === 0) {\n evenCount++;\n oddCount = 0;\n evenCount >= 3 ? console.log(\"Even more so!\") : false;\n }\n if(arr[i] % 2 !== 0) {\n oddCount++;\n evenCount = 0;\n oddCount >= 3 ? console.log(\"That's odd!\") : false;\n }\n }\n}", "function collectOdds(arr) {\n let odds = [];\n\n function collector(nums) {\n // edge cases first\n if (nums.length === 0) return;\n // check if first number in array is odd if yes add it to the outer variable\n if (nums[0] % 2 !== 0) {\n odds.push(nums[0]);\n }\n // now cause the recursion to go through every number in the array\n // by slicing out the first number that had already been checked\n collector(nums.slice(1));\n }\n\n // call the recursion function\n collector(arr);\n\n // return the result\n return odds;\n}", "function oddsAndEvens (nums){\n for(var i = 0; i < nums.length; i++)\n if (nums[i] % 2 === 0){\n evens.push(nums[i]);\n }\n else{\n odds.push(nums[i]);\n }\n \n}", "function evenOddSums(arr) {\r\n let evenSum = 0\r\n let oddSum = 0\r\n //iteration using forEach\r\n arr.forEach(num => (num % 2 === 0 ? (evenSum += num) : (oddSum += num)))\r\n return [evenSum, oddSum]\r\n }", "function returnOdds(array) {\n}", "function getOdds(){\n var odds = [];\n for (var i = 0; i < numbers.length; i ++){\n if (numbers[i] % 2 === 1){\n odds = odds.concat(numbers[i]);\n }\n }\n return odds;\n}", "function getOdds(array){\n var oddArray = [];\n array.forEach(function (element) {\n if (element % 2 != 0){\n oddArray.push(element);\n }\n });\n return oddArray;\n}", "function getEvens(array) {\n var returnOdds = [];\n\n for (var i = 0; i < array.length; i++) {\n if (array[i] % 2 == 0) {\n returnOdds.push(array[i]);\n }\n }\n return returnOdds;\n}", "function findEvensAndOdds(array){\n let oddCount = 0;\n let evenCount = 0;\n for(var i = 0; i < array.length; i++){\n // determine odd values\n if(array[i] % 2 !== 0){\n // determine three in a row\n oddCount++\n evenCount = 0;\n }\n // determine even values \n else { // determine three in a row\n // increment the evenCount\n evenCount++\n oddCount = 0;\n }\n // check the count to see if three in a row - even\n if(evenCount === 3){\n // if the count is equal to 3, reset count to 0\n evenCount = 0;\n console.log(\"Even more so!\");\n }\n // check the count to see if three in a row - odd\n if(oddCount === 3){\n oddCount = 0;\n console.log(\"That's odd!\");\n }\n }\n // return the array\n return array;\n}", "function oddsAndEvens(nums){\n var odds = [];\n var evens = [];\n for(var i = 0; i < nums.length; i++){\n if(nums[i] % 2 === 0){\n evens.push(nums[i]);\n }\n else{\n odds.push(nums[i]);\n }\n }\n return odds;\n}", "function evensIndex(array) {\n var arr = [];\n for(var i = 0; i < array.length; i++){\n if (array[i] % 2 === 0){\n arr.push(array[i]);\n }\n }\n return arr;\n}", "function evenOddSums(arr) {\n let evenSum = 0;\n let oddSum = 0;\n \n arr.forEach(num => (num % 2 === 0 ? (evenSum += num) : (oddSum += num)));\n \n return [evenSum, oddSum];\n }", "function doubleOddNumbers(arr) {\n return arr.filter(function(val) {\n return val % 2 !== 0;\n }).map(function(val) {\n return val * 2;\n });\n }", "function findOdd(A) {\n var occurrences = { };\n for (var i = 0; i < A.length; i++) {\n var num = A[i];\n occurrences[num] = occurrences[num] ? occurrences[num] + 1 : 1;\n }\n for (num in occurrences) {\n let count = occurrences[num]\n if (count % 2 == 1) {\n return parseInt(num)\n }\n }\n}", "function evenOddSums(array) {\n let evenSum = 0;\n let oddSum = 0;\n\n array.forEach(number =>\n number % 2 === 0 ? (evenSum += number) : (oddSum += number)\n );\n\n return [evenSum, oddSum];\n}", "function findOdd(array) {\n let result;\n\n array.forEach(number => {\n if (array.filter(curValue => curValue === number).length % 2 === 1) {\n result = number;\n };\n });\n return result;\n}", "function findOdd(arr) {\n let obj = arr.reduce((a, c) => { !a[c] ? a[c] = 1 : a[c]++; return a }, {});\n let keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n if (obj[keys[i]] % 2 !== 0) return Number(keys[i]);\n }\n}", "function isOdd(element, index, array) {\n return (element%2 == 1);\n }", "function findOdd(A) {\n const counts = A.reduce((tracker, e) => {\n tracker[e] = tracker[e] ? tracker[e] + 1 : 1;\n //console.log(tracker[e])\n\n return tracker;\n }, {});\n\n for (key in counts) {\n if (counts[key] % 2)\n return parseInt(key);\n }\n\n return null;\n}", "function sumOddIndicesValues(arr) {\n let sum = 0;\n for (let i = 1; i <= arr.length - 1; i += 2) {\n sum += arr[i];\n }\n return sum;\n}", "function doubleOddNumbers(arr){\n let newValue = []\n let oddNums = []\n return arr.filter( (number, index) => {\n return index % 2 !== 0;\n })\n .map((value) => {\n return value * 2\n })\n // return newValue\n}", "function findOdd(arr) {\n let result = 0\n for(let i = 0; i < arr.length; i++) {\n for(let j = 0; j < arr.length; j++) {\n\n if(arr[i] === arr[j]) {\n result++\n }\n }\n if(result % 2 === 1) {\n return arr[i]\n }\n } \n}", "function evens(arr) {\n let result = [];\n each(arr, function(num) {\n num % 2 === 0 ? result.push(num) : undefined;\n });\n return result;\n }", "function findOdd () {\n var odd = [];\n for (var i = 0; i < numbers.length; i++) {\n if (numbers[i] % 2 != 0) {\n odd.push(numbers[i]);\n }\n } return odd;\n}", "function oddsEvens(inputList) {\n var returnList = [];\n for (var i = 0; i < inputList.length; i++) {\n if (inputList[i] % 2 === 1) {\n returnList.push(inputList[i]);\n }\n }\n return returnList;\n}", "function countOdds(countedValues){\n // returns the number of even numbers\n var counted = 0;// tried empty array [], but first value is undefined bc no starting point\n for (let i = 0; i < countedValues.length; i++) {\n if (countedValues[i] % 2 === 1) {\n counted++;\n }\n }\n return counted;\n}", "function evenOddSums(arr) {\n let evenSum = 0;\n let oddSum = 0;\n\n arr.forEach(num => {\n num % 2 === 0 ? evenSum += num : oddSum += num\n })\n return [evenSum, oddSum]\n}", "function odd(arr){\nresult = arr.reduce((total ,elem)=>{\n if(elem %2 === 1){\n total += elem}\n return total\n},0)\n\nreturn result\n\n}", "function oddOnesOut(array) {\n const tally = elementCount(array);\n const evensInArr = [];\n\n for(const key in tally) {\n if(tally[key] % 2 === 0) evensInArr.push(key);\n }\n\n return evensInArr;\n}", "function doubleOddNumbers(arr) {\n\n var oddNumbers = arr.filter(function (value) {\n return value % 2 !== 0;\n });\n\n return oddNumbers.map(function (value) {\n return value * 2;\n });\n}", "function solve(a){\n var even = 0\n var odd = 0\n for ( let i = 0 ; i<a.length ; i++){\n if ( typeof(a[i]) === \"number\"){\n if (a[i] %2 ===0){\n even ++\n }else{\n odd ++\n }\n }\n }\n return (even-odd);\n }", "function evenOddSums(arr) {\r\n var oddTotal = 0;\r\n var evenTotal = 0;\r\n\r\n arr.forEach((value) => value % 2 === 0 ? evenTotal += value : oddTotal += value);\r\n\r\n return [evenTotal, oddTotal]\r\n}", "function doubleOddNumbers(arr) {\n\treturn arr.filter(function(val){\n\t\treturn val % 2 !== 0;\n\t}).map(function(val){\n\t\treturn val * 2;\n\t})\n}", "function arrayOdd(){\n var odds = [];\n for(var i = 0; i < 50; i++){\n if(i%2 != 0){\n odds.push(i);\n }\n }\n return odds;\n}", "function findOdd(array) {\n //happy coding!\n for (let i = 0; i < array.length; i++) {\n let counter = 0;\n\n for (let j = 0; j < array.length; j++) {\n if (array[i] === array[j]) {\n counter++;\n }\n }\n\n if (counter % 2 !== 0) {\n return array[i];\n }\n }\n}", "function evenOddSums() {}", "function oddValues(arr){\n let newArr = [];\n for(let i = 0; i < arr.length; i++){\n if(arr[i] %2!==0){\n newArr.push(arr[i]);\n }\n }\n return newArr;\n}", "function collectOddValue(arr){\n let result = [];\n\n function helper(helperInput){\n if(helperInput.length === 0) return;\n\n if(helperInput[0] % 2 !== 0){\n result.push(helperInput[0]);\n }\n\n helper(helperInput.slice(1));\n \n\n }\n\n helper(arr);\n\n}", "function onlyOddNumbers(arrayOfOddNumbers){\n var oddNumbers = [];\n for (let i = 0; i < arrayOfOddNumbers.length; i++) {\n if (isOdd(arrayOfOddNumbers[i])){\n // initial if argument arrayOfOddNumbers[i]%2 === 1, think it can work but have to figure it out this way\n oddNumbers.push(arrayOfOddNumbers[i]);\n }\n }\n return oddNumbers;\n}", "function sumOdds(){\n var sum=0;\n for(var cont=1;cont<=5000;cont+=2){\n sum=sum+cont;\n }\n console.log(sum);\n}", "function evens(array){\n\tvar newArray= [];\n\tfor (var i = 0; i < array.length; i++){\n\t\tif (array[i]%2 === 0){\n\t\t\tnewArray === newArray.push(array[i]);\n\n\t\t}\n\t}\n return newArray;\n}", "function sumOfTheOddNumbers(arrayNr) {\n\tvar sum=0;\n\tfor(let i=0; i<arrayNr.length; ++i) {\n\t\tif(arrayNr[i]%2!=0) sum=sum+arrayNr[i];\n\t}\n\treturn sum;\n}", "function oddNumbers(){\n var odd = [];\n for (i=0; i<numbers.length; i++){\n if (numbers[i] % 2 !== 0){\n odd.push(numbers[i]);\n }\n }return odd;\n}", "function displayOddNumbers(array) {\n\t\tfor (let i = 0; i < array.length; i++) {\n\t\t\tif (array[i] % 2 === 1) {\n\t\t\t\tconsole.log(array[i]);\n\t\t\t}\n\t\t}\n\t}", "function evenandodds(arr){\n var countodds=0;\n var countevens=0;\n for (var i=0;i<arr.length;i++){\n if(arr[i]%2!==0){\n countodds+=1;\n countevens=0;\n \n }\n else if(arr[i]%2==0){\n countevens+=1;\n countodds=0;\n \n }\n// console.log(countodds);\n \nif (countodds==3){\n console.log(\"That's odd\");\n countodds=0;\n}else if(countevens===3){\n console.log(\"Even More so\");\ncountevens=0;\n}\n }\n\n}", "function oddArray(arr){\n var odd =[];\n for(var z=0;z<arr.length;z++){\n if(z%2!==0)\n {\n odd.push(arr[z]);\n }\n }\n return odd;\n}", "function arrayOdd() {\n var oddArray = [];\n for (var i = 1; i <= 50; i+=2) {\n oddArray.push(i);\n }\n return oddArray;\n}", "function arrOdd(){\n var output = [];\n for(var i = 1; i <= 50; i = i+2){\n output.push(i);\n }\n return output;\n}", "function firstOdd(n) {\n var tot = 0;\n for(i = 0; i < n; ++i) {\n tot += 1 + 2 * i;\n }\n return tot;\n}", "function collectOdds(arr) {\n let newArr = []\n\n if (arr.length === 0) {\n return newArr\n }\n\n if (arr[0] % 2 !== 0) {\n newArr.push(arr[0])\n }\n newArr = newArr.concat(collectOdds(arr.slice(1)))\n}", "function processOddNumbers(arr) {\n\tconsole.log(arr\n\t\t\t.filter((x, i) => i % 2 !== 0)\n\t\t\t.map(x => x * 2)\n\t\t\t.reverse()\n\t\t\t.join(' '));\n}", "function oddIndexed() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tif (i % 2 !== 0) {\n\t\t\tnewArray.push(oldArray[i] * 2);\n\t\t}\n\t\telse {\n\t\t\tnewArray.push(oldArray[i]);\n\t\t}\n\t}\n}", "function oddElements(array) {\n let newArray = []\n for (i=0; i<array.length; i++) {\n if (array[i]*10 % 2 !==0) {\n newArray.push(array[i])\n }\n }\n return newArray;\n}", "function arrayOddNumbers(oddArray) {\r\n for (var i = 0; i <= 256; i++) {\r\n if (i % 2 == 1) {\r\n oddArray.push(i);\r\n }\r\n }\r\n console.log(\"\\n\\nBuild Array with Odds between 1 and 255\")\r\n console.log(oddArray)\r\n}", "function collectOddValues(arr) {\n let result = [];\n function helper(helperInput) {\n if(helperInput.length === 0) {\n return;\n } \n if(helperInput[0] % 2 !== 0) {\n result.push(helperInput[0])\n }\n helper(helperInput.slice(1));\n }\n helper(arr);\n return result;\n}", "function evenNumbers (arr) {\n var newArr = [];\n \n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 === 0) {\n newArr.push(arr[i]);\n }\n }\n return newArr;\n }", "function collectOddValues(arr) {\n let result = [];\n\n function helper(helperArr) {\n if(helperArr.length === 0) return;\n if(helperArr[0] % 2 !== 0) {\n result.push(helperArr[0]);\n }\n helper(helperArr.slice(1));\n }\n helper(arr);\n return result;\n}", "function oddSum(values){\n var sum = 0;\n for (var i = 0; i < values.length; i++) {\n if (values[i] % 2 === 1) {\n sum += values[i];\n }\n }\n return sum;\n }", "function veryOdd(arrayOfNums) {\n let oddArray = [];\n\n for (let i = 0; i < arrayOfNums.length; i++){\n\n if(arrayOfNums[i] % 2){ // ODD b/c copiedArray[i] % 2 == 1, ie. TRUE\n oddArray.push(arrayOfNums[i]);\n }\n }\n \n return oddArray;\n}", "function oddValues(arr){\n let result = []\n function helper(helperInput){\n if (helperInput.length === 0){\n return \n }\n if (helperInput[0] % 2 !== 0){\n result.push(helperInput[0])\n }\n helper(helperInput.slice(1))\n }\n helper(arr)\n return result\n}" ]
[ "0.84182847", "0.83399564", "0.80222166", "0.79890007", "0.78708595", "0.7870181", "0.78565407", "0.782215", "0.7808198", "0.7667304", "0.76460713", "0.7604281", "0.7527105", "0.74929553", "0.74545234", "0.74070275", "0.74004036", "0.7364648", "0.73496246", "0.7333455", "0.7317637", "0.73027164", "0.7289139", "0.72276556", "0.72141916", "0.72104317", "0.720727", "0.72051644", "0.7197989", "0.71861285", "0.7183041", "0.7182013", "0.71380115", "0.71318054", "0.71272147", "0.7113797", "0.7110012", "0.7052524", "0.70497304", "0.70320517", "0.7030461", "0.70009595", "0.6993249", "0.6993234", "0.6987809", "0.6985876", "0.6979902", "0.6977934", "0.6975583", "0.69749975", "0.6964668", "0.69513154", "0.6932172", "0.6928993", "0.6927655", "0.6926742", "0.6925969", "0.6922548", "0.69204366", "0.6920318", "0.6911265", "0.69061536", "0.69058037", "0.69019264", "0.690031", "0.68913734", "0.68889755", "0.688738", "0.6881595", "0.68803054", "0.6872736", "0.6864569", "0.68627757", "0.6860653", "0.6857076", "0.6847115", "0.683784", "0.6832614", "0.68237615", "0.6820082", "0.6816071", "0.6813812", "0.6810302", "0.68033695", "0.68030125", "0.68023276", "0.6795171", "0.6794656", "0.67925715", "0.67914164", "0.67878634", "0.678567", "0.6785168", "0.6779671", "0.6778518", "0.6777727", "0.67769456", "0.6773803", "0.6773019", "0.6769014" ]
0.7381368
17
console.log(incrementTheSeconds([2,4,2,5,4,3])); Challenge 8 Previous Lengths You are passed an array (similar to saying 'takes in an array' or 'given an array') containing strings. Working within that same array, replace each string with a number the length of the string at the previous array index and return the array. For example, previousLengths(["hello", "dojo", "awesome"]) should return ["hello", 5, 4]. Hint: Can for loops only go forward?
function previousLengths(arr) { for(var i = arr.length - 1; i > 0; i--) { arr[i] = arr[i - 1].length; } return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function previousLengths(arr){\n for(let i = arr.length - 1; i > 0; i--){\n arr[i] = arr[i - 1].length // Loop 1 - arr[2] = arr[1]\n }\n return arr\n }", "function previousLengths(array) {\n for (var i = array.length - 1; i >= 0; i--) {\n console.log(\"array[\" + i + \"]: \" + array[i]);\n \n // if the i === 0, just stop\n if (i !== 0) {\n var element = array[i - 1];\n console.log(\"length of previous value: \" + element.length)\n array[i] = element.length;\n }\n }\n return array;\n}", "function previousLengths(arr){\n for(i=arr.length-1; i>0; i--){\n arr[i] = arr[i-1].length;\n }\n return arr;\n}", "function previousLengths(arr){\n for(var i=0;i<arr.length-1;i++){\n arr[i+1]=arr[i].length;\n }\n return arr;\n\n}", "function previouslengths(arr){\n \n for(var i=arr.length-1;i>0;i--){\n arr[i]=arr[i-1].length;\n }\n return arr;\n}", "function incrementTheSeconds(arr) {\n for(var i = 1; i < arr.length; i +=2) {\n arr[i] = arr[i] + 1; \n }\n for(var j = 0; j < arr.length; j++) {\n console.log(arr[j]);\n }\n\n return arr;\n}", "function incrementSeconds(arr){\n for(var i = 1; i < arr.length; i+=2){\n arr[i] += 1;\n }\n console.log(arr);\n return arr;\n}", "function previous(arr){\n for( var i = arr.length - 1; i >= 0; i--){\n arr[i] = string //what is string length?\n }\n}", "function getLengthsPart2(puzzleInput){\n // \"Once you have determined the sequence of lengths to use, add the following lengths to the end of the sequence:\"\n var sequenceToAdd = \"17, 31, 73, 47, 23\";\n\n // For example, if you are given 1,2,3, your final sequence of lengths should be 49,44,50,44,51,17,31,73,47,23\n var a = [];\n \n puzzleInput.split(\"\").forEach(character => {\n a.push(character.charCodeAt(0));\n });\n\n sequenceToAdd.split(\",\").forEach(character => {\n a.push(+character);\n });\n\n return a;\n}", "function runLength(string) {\n var output = [];\n var counter = 1;\n if (string === '' || string === null) {\n return string;\n }\n for (var i = 0; i < string.length; i++){\n if(string[i] === string[i+1]){\n counter++;\n }\n output.push(counter + string[i]);\n }\n counter = 1;\n }", "function incrementTheSeconds(arr){\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (num % 2 == 1) {\n\t\t\tarr[num] = arr[num] +1;\n\t\t}\n\t}\n\t\tconsole.log(arr);\n\t\treturn(arr);\n}", "function runLength( str ) {\n\tvar counter = 1,\n\t\tnewStr = \"\";\n\n\tfor ( var i = 0; i < str.length; i++ ) {\n\t\tif ( str[i] === str[i + 1] ) {\n\t\t\tcounter++;\n\t\t} else {\n\t\t\tnewStr += ( counter + str[i] );\n\t\t\tcounter = 1;\n\t\t}\n\t}\n\treturn newStr;\n}", "function change(x,times){\n for(let i =0; i < x.length; i++){\n for(let j =1; j<= times; j++){\n if(i>=j && i<x.length-j){\n x[i]--\n } \n }\n }return x\n}", "function incrementSeconds(arr){\n for(var i = 0; i < arr.length; i++){\n if(i % 2 != 0){\n arr[i] += 1\n }\n console.log(arr[i])\n }\n return arr\n}", "function songLength(songArray) {\n var playlist = 0;\n for (var i = 0; i < songArray.length; i++) {\n //does songArray.length = 60?\n //\n }\n}", "function arrayChange(inputArray) {\n let steps = 0;\n \n for (let i = 0; i < inputArray.length - 1; i++) {\n while (inputArray[i] >= inputArray[i + 1]) {\n inputArray[i+1] += 1;\n steps += 1;\n }\n }\n return steps;\n}", "function listLengthOfAllWords(array) {\n for (let j = 0; j < array.length; j++) {\n array[j] = array[j].length ;\n };\n return array\n}", "function stringsLength(array) {\n\n for (i = 0; i < array.length; i++) {\n \n numArray.push(strLength(array[i]));\n }\n return numArray;\n}", "function incrementSeconds(array1)\n{\n const incrementSeconds = array1.map(x => (x%2==1) ? x + 1 : x);\n console.log(incrementSeconds)\n}", "function arrayChange(inputArray) {\n let c = 0;\n for(let i=0; i < inputArray.length; i++){\n if(inputArray[i] >= inputArray[i+1]){\n let dif = inputArray[i] - inputArray[i + 1];\n inputArray[i + 1] = inputArray[i] + 1;\n c += dif+1;\n }\n }\n \n return c;\n}", "function improved(array) {\n var prev = new Array(array.length);\n var next = new Array(array.length);\n\n var prev_index = 0;\n addPrevious(prev, array);\n addNext(next, array);\n\n array = multiply(prev, next);\n console.log(array);\n}", "function reverseWords2(string) {\n let stringArray = string.split(' ');\n\n stringArray = stringArray.map((function length(currentValue) {\n if (currentValue.length >= 5) {\n return currentValue.split('').reverse().join('');\n } else {\n return currentValue;\n }\n }));\n return console.log(stringArray.join(' '));\n}", "function modifyStrings(strings, modify) {\n // YOUR CODE BELOW HERE //\n \n // inputs an array, containing string. a function that modifies strings, BUT NOT ARRAYS\n //outputs return an array, where all of its contents have been modified individually by the function\n \n //should increment over array strings, taking each value in it and applying the modify function to it, placing the results in a new array\n //should return the new array\n let newArray = [];\n for (let i = 0; i< strings.length; i++){\n newArray.push(modify(strings[i]));\n \n }\n return newArray;\n \n \n // YOUR CODE ABOVE HERE //\n}", "function runLengthEncoding(string) {\n // create list 'chars' to store result; no concatenating with a string as it isn't as efficient\n let chars = []\n // create variable 'length' to keep track of runs starting at 1\n let length = 1\n // loop through string starting at second character\n for (let i = 1; i < string.length; i++) {\n // if character is not the same as previous OR length is equal to 9\n if (string[i] !== string[i - 1] || length === 9) {\n // add 'length' to 'chars' + previous 'char'\n chars.push(length, string[i - 1])\n // reset length to 0 as next line will increment it by one regardless, \n // handling both cases of inside this conditional and outside \n // of the conditional for characters that are the same\n length = 0\n }\n // increment 'length', as character is the same as previous \n length++\n }\n // handle last element by adding 'length' + 'char' to 'chars'\n chars.push(length, string[string.length - 1])\n // join 'chars' into string and return\n return chars.join('')\n}", "function num_lost_words(pre_set_word_array_array, min_length){\n let lost_options = 0;\n for(let pre_set_word_array of pre_set_word_array_array){\n let lost_len = min_length - pre_set_word_array.length;\n lost_options += Math.pow(letters.length,lost_len);\n }\n return lost_options;\n }", "function runLengthEncoding(string) {\n let encodedArr = [];\n let count = 1;\n\n for (let i = 1; i < string.length + 1; i++) {\n let currentChar = string[i];\n let prevChar = string[i - 1];\n\n if (count === 9 || currentChar !== prevChar) {\n encodedArr.push(count, prevChar);\n count = 0;\n }\n count++;\n }\n\n return encodedArr.join('');\n}", "function upArray(arr){ \n\n \n if(arr.length == 0) {\n return null; \n }\n \n if(arr.length > 16) {\n val = arr[arr.length - 1];\n arr[arr.length - 1] = val + 1; \n return arr; \n }\n \n for(var i = 0; i < arr.length; i++) {\n if(arr[i] < 0 || arr[i].toString().length > 1) {\n return null; \n }\n }\n \n var strings = \"\";\n arr.map(function(item) {\n strings += item;\n });\n \n\n var newValue = (parseInt(strings) + 1).toString(); \n console.log(newValue); \n var output = [];\n \n for(var i = 0; i < newValue.length; i++) {\n output.push(parseInt(newValue.charAt(i))); \n }\n \n return output; \n \n}", "function incrementInteger(array){\n array[array.length - 1] += 1;\n return array;\n}", "function solveDay10Part1(input){\n input.lengths.forEach(length =>{\n // Reverse the order of that length of elements in the list, starting with the element at the current position.\n reverseSubArray(input.array, input.currentPosition, length);\n\n // Move the current position forward by that length plus the skip size.\n input.currentPosition += length + input.skipSize; \n\n // Increase the skip size by one.\n input.skipSize++;\n });\n\n var solution = +input.array[0] * +input.array[1];\n\n return solution;\n}", "function evenLengthedStrings(strings) {\n let sum = 0;\n numbers = [];\n\n\n\n for (let i = 0; i < strings.length; i++) {\n strings.push(numbers);\n \n if (numbers % 2) {\n strings.splice();\n return string;\n\n }\n }\n\n\n\n //console.log(strings)\n}", "function Length_Finder(array){\r\n var array = array; // sets the parameter to array\r\n var longest_word = \"\"; // empty string to store what the longest word is\r\n var comparer = \"\"; // empty string to allow for more words to fall into\r\n\r\n for (var i = array.length - 1; i >= 0; i--) {\r\n if (longest_word.length < array[i].length) {\r\n longest_word = array[i]; // if the length of longest word is less then the word currently at the loops index then replace that word\r\n }\r\n };\r\n // another loop to determine if there are more words that are the same length as the longest_word but not the same word\r\n for (var i = array.length - 1; i >= 0; i--) { \r\n if (longest_word != array[i] && longest_word.length == array[i].length) {\r\n comparer += \", \" + array[i]; // if the length of longest word is less then the word currently at the loops index then replace that word\r\n }\r\n };\r\n console.log(longest_word + comparer + \" are/is the largest!\"); // prints longest word\r\n}", "function getMultipleLengths(arrayOfStrings){\n\tlet strLengths = [];\n\tfor(let i = 0; i < arrayOfStrings.length; i++){\n\tstrLengths.push(arrayOfStrings[i].length);\n\t}\n\treturn strLengths;\n}", "function incrementSeconds(arr) {\n for (var num in arr) {\n if (num % 2 !== 0) { // Every odd index\n console.log(\"index: \" + num + \" incremented [\" + arr[num] + \"->\" + (arr[num]++));\n }\n }\n return arr;\n}", "function exSelf(array) {\n //two for loops and a counter\n // first for loop starting from begining\n // second start from end\n let products = new Array(array.length);\n let counter = 1;\n for ( let i = 0 ; i < array.length ; i ++ ){\n products[i] = counter;\n counter *= array[i];\n }\n\n //SECERET WHEN DECREMENTING:\n // products[j] *= counter\n // counter *= array[j];\n\n counter = 1;\n for ( let j = array.length - 1 ; j >= 0 ; j -- ){\n products[j] *= counter\n counter *= array[j];\n }\n\n return products\n\n}", "function imperativeLengths(states) {\n let lengths = [];\n states.forEach(function(state) {\n lengths[state] = state.length; \n });\n return lengths;\n}", "function incrementSec(arr) {\n\n for (var i = 0; i < arr.length; i++) {\n if (i % 2 != 0) {\n arr[i]++;\n }\n }\n console.log(arr);\n return (arr);\n}", "static change(array) {\n let change = [];\n array.reduce(function (accumulator, currentValue, currentIndex, array) {\n if (currentIndex === 0) {\n accumulator = currentValue;\n }\n change.push(currentValue - accumulator);\n return currentValue;\n }, array[0]);\n return change;\n }", "function alternatingCharacters(s) {\nlet originalArr = s.split('');\n let newArr = [originalArr[0]];\n for (let i = 1; i < originalArr.length; i++) {\n if (originalArr[i] !== originalArr[i-1]) {\n newArr.push(originalArr[i]);\n }\n }\n return originalArr.length - newArr.length;\n}", "function runLengthEncoding(str) {\n\tvar count = 1;\n\tvar strArr = [];\n\tfor (var i = 0; i < str.length; i++) {\n\t\tif (str[i] === str[i+1]) {\n\t\t\tcount++;\n\t\t} else {\n\t\t\tstrArr.push(count + str[i]);\n\t\t\tcount = 1;\n\t\t}\n\t}\n\treturn strArr.join(\"\");\n}", "function sortByLength (array) {\n var temp = \"\";\n for (var i = 0; i < array.length ; i++){\n var j = i;\n while(j > 0 && array[j-1].length > array[j].length){\n temp = array[j]\n array[j] = array[j-1];\n array[j-1] = temp;\n j--\n }\n }\n return array;\n}", "function runLengthEncoder(list) {\n\tvar runLengthEncodedList = [];\n\tvar unit = [];\n\tfor (var i = 0; i < list.length; i++) {\n\t\t// counter set to 1 because there will always be at least 1 of each unit.\n\t\tvar runLengthCounter = 1;\n\t\twhile(list[i] == list[i + 1]) {\n\t\t\ti++;\n\t\t\trunLengthCounter++;\n\t\t}\n\t\tif(runLengthCounter > 1) {\n\t\t\tunit.push(list[i])\n\t\t\tunit.push(runLengthCounter)\n\t\t} else {\n\t\t\tunit.push(list[i])\n\t\t\tunit.push(runLengthCounter)\n\t\t}\n\t\tvar coupledUnitCounter = unit.splice(0,2)\n\t\trunLengthEncodedList.push(coupledUnitCounter)\n\n\t}\n\tconsole.log(\"EX 7: list with run-length encoded is: \")\n\tconsole.log(runLengthEncodedList)\n}", "function almostIncreasingSequence(sequence){\n\n}", "function totalLetters (string) {\n var length=0;\n for (var i=0; i < string.length; i++){\n length = length + string[i].length;\n }\n console.log(length);\n}", "function kookaCounter3(laughing) {\n const laughingArray = laughing.split('a')\n let count = 0\n\n for (let i = 0; i < laughingArray.length; i++) {\n if (laughingArray[i] !== laughingArray[i + 1]) {\n count++\n }\n }\n return count - 1\n}", "function reverseOrder(str) {\n const array = str.split(' ');\n let string = '';\n\n for (let i = array.length -1; i >= 0; i--) {\n string = string + array[i];\n string = string + ' ';\n }\n console.log(array.length);\n \n return string;\n}", "function longestLength(array) {\r\n// start with an empty current longest\r\n\tvar currentLongest = \"\";\r\n\t// iterate over the array\r\n\tfor (var i = 0; i < array.length; i++) {\r\n\t\t// IF the string is longer than current longest\r\n\t\tif (array[i].length > currentLongest.length) {\r\n\t\t\t// THEN it becomes the current_longest \r\n\t\t\tcurrentLongest = array[i];\r\n\t\t}\r\n\t}\r\n\r\n\t// RETURN the length of the current longest\r\n\treturn currentLongest.length;\r\n}", "function looper (len) {\n\tvar results = [];\n\tfor (var i = 0; i < len -1; i+=2){\n\t\tresults.push(i);\n\t};\n\treturn results.map(function(element){\n\t\treturn element * 3;\n\t})\n}", "function calcute_num_operations(seq) {\n //console.log(seq, seq.length, seq.split(\"*\").length)\n return seq.length - (seq.split(\"*\").length - 1)\n}", "function IncEvOther(arr){\n for(var i=1; i<arr.length; i+=2){\n arr[i]++; \n }\n console.log(arr);\n return arr;\n}", "function ChangingSequence(arr) {\n//Is it increasing? If so, then pass arr to the increaseArr function.\n if ((arr[1] - arr[0]) > 0) {\n return increaseArr(arr);\n }\n//Is it decreasing? If so, then pass arr to the decreaseArr function.\n if ((arr[1] - arr[0]) < 0) {\n return decreaseArr(arr);\n }\n\n/*This will return the index of the last point where the numbers were increasing.\nIf the numbers just keep increasng and the pattern doesn't change, then -1 will\nbe returned.*/\n function increaseArr(arr) {\n let index;\n for(let i = 0; i < arr.length; i++) {\n if(arr[i+1] - arr[i] < 0) {\n index = i;\n break;\n } else {\n index = -1;\n }\n }\n return index;\n }\n\n /*This will return the index of the last point where the numbers were decreasing.\n If the numbers just keep decreasing and the pattern doesn't change, then -1 will \n be returned.*/\n function decreaseArr(arr) {\n let index;\n for(let i = 0; i < arr.length; i++) {\n if(arr[i+1] - arr[i] > 0) {\n index = i;\n break;\n } else {\n index = -1;\n }\n }\n return index;\n }\n\n}", "function dualLetterReduce(t, i, index, arr) {\n const innerT = t;\n if (arr[index] && arr[index + 1]) {\n if (innerT.every((z) => z.word !== `${arr[index]}${arr[index + 1]}`)) {\n innerT.push({ word: `${arr[index]}${arr[index + 1]}`, times: 1 });\n } else {\n const indy = t.findIndex(\n (x) => x.word === `${arr[index]}${arr[index + 1]}`\n );\n innerT[indy].times += 1;\n }\n }\n return innerT;\n }", "function incrementLength() {\n let length = _length.get( this );\n length++;\n _length.set( this, length );\n}", "function repeatedString(s, n) {\n /*while the string length is less than n, we want to concatenate the string on itself\n then we want to slice it at n\n then we make a new array and slice on each letter\n then we have an aCount and a for loop that says if array[i] === 'a' then aCount incerments\n then we return aCount\n */\n\n /*second way...\n do the loop first, see what a count is\n divide n by sting.length\n multiply by aCount?\n */\n let aCount = 0\n for (let i = 0; i < s.length; i++) {\n if (s[i] === 'a')\n aCount++\n }\n return Math.round(aCount * (n / s.length))\n //something here... possibly with modulo remainder, to add... 16/23 passed\n\n\n}", "function getStrLengthInArray(arr){\n // let len=0;\n // arr.forEach( (val,idx)=>{\n // len += val.length;\n // } )\n // return len;\n\n return arr.reduce( (p, v) => p + v.length , 0);\n}", "function accum(s) {\n\t// capitalize string\n\ts = s.toUpperCase()\n\t// convert string to array\n\tvar newArray = s.split('');\n\t// new variable for storing result\n\tvar result = '';\n\tfor (var i = 0; i < newArray.length; i++) {\n\t\t// return character + character repeated position times \n\t\t//(if position is 0, repeat 0 times, if 1, repeat 1 times)\n\t\t// add -\n\t\tresult += newArray[i] + newArray[i].toLowerCase().repeat(i) + '-';\n\t}\n\t// return result and chop off the last -\n\treturn result.slice(0,result.length-1);\n}", "function getStringLengthArr(array) {\n var stringLengthArr = [];\n\n if (array) {\n for (a of array) {\n if (!stringLengthArr.includes(a.length)) {\n stringLengthArr.push(a.length);\n };\n };\n }\n\n return stringLengthArr;\n}", "function marsExploration(s) {\n // Write your code here\n let expectedWords = s.length / 3;\n let expectedString = '';\n let changedLetters = 0;\n\n for (let x = 0; x < expectedWords; x++) {\n expectedString += 'SOS';\n }\n console.log('es', expectedString)\n for (let y = 0; y < s.length; y++){\n if (s[y] != expectedString[y]) {\n changedLetters++;\n }\n }\n\n return changedLetters;\n}", "function PrevArray(seed, seed_size) {\n let arr = [];\n let startNumber;\n for (let i = seed_size; i > 0; i--) {\n\t\tif (i==seed_size)\n\t\t\tstartNumber = seed - i;\n\t\t//console.log(\"i\", i);\n\t\tarr.push(seed - i);\n\t\tconsole.log(seed-i)\n\t\t\n }\n return [arr, startNumber];\n}", "function findIncreasingSequences2(arr) {\n if (arr.length === 1) return 1;\n for (let i = 1; i < arr.length; i++) {\n if (arr[i] < arr[i - 1]) {\n return 1 + findIncreasingSequences(arr.slice(i + 1));\n }\n }\n}", "function changeArray(array1, array2){\r\n\tvar diff = [];\r\n\tfor(var i=0; i<59; i++){\r\n\t\tdiff[i] = array1[i] - array2[i];\r\n\t}\r\n\treturn diff;\r\n}", "function countEmUp(arr){\n var allSpices = spices.join(\"\");\n return allSpices.length;\n}", "function longestIncreasingSubsequence(array) {\n // Write your code here.\n let sequences = new Array(array.length);\n let lengths = array.map(x => 1);\n let maxId = 0;\n for(let i =0 ; i< array.length; i++) {\n for(let j=0; j< i; j++) {\n if(array[j] < array[i] && lengths[j] + 1 > lengths[i]) {\n lengths[i] = lengths[j] + 1;\n sequences[i] = j;\n }\n }\n if(lengths[i] >= lengths[maxId]) {\n maxId = i;\n }\n }\n \n return buildSequence(array, sequences, maxId);\n}", "function countPositives(array){\n let counter = 0;\n for(let i = 0; i < array.length; i++){\n if(array[i] > 0){\n counter = counter + 1;\n }\n array[array.length - 1] = counter;\n }\n return array;\n}", "function generateRandomArray(length) {\n\t\n// generally figure out how to generate a randomize string of varying length 1-10 letters\n// this actually seems like it could be it's own function, however I will keep it in this \n// function as two actions \n\tvar randomString = \"\";\n\tvar possible = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n\t// index is the wrong variable here, but i am using it, it does loop 10 times\n\tfor (var index = 1; index <= 10; index++)\n\t\t\n\t// for (var x = 1; x <= 10; x++) // this just returns the last string at with 1\n\t// random letter\n\t// for (var length = 1; length <= 10; length++);\n\n\t\t// got this line from stack overflow, not sure how it works really\n\t\t// it does return a random string of 10 letters, but not of varying lengths \n\t\trandomString += possible.charAt(Math.floor(Math.random() * possible.length));\n \t\n\t\tconsole.log(randomString) // ==> KpIJVhyhdD\n\n// return array with the number of string items equal to the integer taken as an argument\n\n\t// let's see if i can just generate an array with the length of 4\n\tnewArray = []\n\n\tfor ( var index = 0; index <= 4; index ++){\n\t\tnewArray[index] += randomString;\n\t\treturn newArray;\n\t}\n\n\t// nothing is happening when i am printing this\n\tconsole.log(newArray) // ==> [ 'undefinedKpIJVhyhdD' ]\n\t\t\n}", "function unusualFive() {\n let array =[\"a\",\"b\",\"c\",\"d\",\"e\"]\nreturn array.length\n}", "function getConsecutiveStrings(arrayOfStrings, k) {\n let n = arrayOfStrings.length;\n\n if (n === 0 || k > n || k <= 0) {\n return [\"\"];\n }\n\n let consecutiveConcatenatedStrings = [];\n\n for (let idx = 0; idx <= arrayOfStrings.length - k; idx += 1) {\n let consecutiveStrings = arrayOfStrings.slice(idx, idx + k);\n consecutiveConcatenatedStrings.push(consecutiveStrings.join(''));\n }\n console.log(consecutiveConcatenatedStrings);\n return consecutiveConcatenatedStrings;\n}", "function longestStringReducing(array) {\n const reduced = array.reduce(function (longestWord, word) {\n return word.length > longestWord ? word : longestWord;\n }, \"\");\n console.log(reduced.length);\n console.log(reduced);\n return reduced.length;\n return reduced;\n}", "function fill_correct(len) \t\t\n\t{\n\t\tfor(i=0;i<len;i++)\n\t\t{\n\t\t correct[i]=i+1;\t\n\t\t}\n\t}", "function repeatedString(s, n) {\n var count = 0;\n var sum = 0;\n var aTail = 0;\n var array = s.split('');\n var sumEnter = (n - n % array.length) / array.length;\n var tail = n - (sumEnter * array.length);\n console.log('sumEnter ' + sumEnter);\n console.log('tail ' + tail);\n\n for (var i = 0; i < array.length; i++) {\n if ('a' == array[i]) {\n count++;\n }\n }\n\n if (n % array.length == 0) {\n sum = count * (n / array.length);\n } else {\n tail = s.substring(0, tail).split('');\n console.log('qwerty' + tail);\n tail.forEach(element => {\n if (element === 'a') {\n aTail++;\n }\n });\n sum = count * sumEnter + aTail;\n }\n console.log('sum ' + sum);\n return sum;\n}", "function spinWords(...rest) {\n //TODO Have fun :)\n let arr = [rest][0][0].split(\" \");\n let newArr = [];\n arr.forEach(function (item, i, arr) {\n if (item.length >= 5) {\n //console.log(i);\n\n newArr.push(item.split(\"\").reverse().join(\"\"));\n } else {\n newArr.push(item);\n }\n });\n\n return newArr.join(\" \");\n}", "_subtractOverflows(length, ...overflows) {\n return overflows.reduce((currentValue, currentOverflow) => {\n return currentValue - Math.max(currentOverflow, 0);\n }, length);\n }", "function howManyDifferent(a){\n\n // if the string length % 2 == 0\n if (a.length % 2 !== 0){\n\n // -1 representing that solution is not possible.\n return -1;\n }\n\n // create a new string of the first half of the given string\n let astring = a.substring(0, a.length / 2);\n\n // and a new string for the second half of the given string\n let bstring = a.substring((a.length / 2), a.length);\n\n // return the result of calling 2 helper functions\n // with our 2 new strings as helper arguements\n return stringChecker(astring, bstring, difFreqChecker);\n}", "function thisLength(num1, num2) {\n if(num1 === num2){\n console.log( \"Jinx\");\n }\n var arr = [];\n for(var i = num1; i >= 0; i--){\n arr.push(num2);\n }\n return arr;\n }", "function sc(screws) {\n if (!screws || !screws.length) return 0;\n\n const move = 1;\n const remove = 1;\n const swapTool = 5;\n\n let time = 1;\n\n for (let i = 1; i < screws.length; i++) {\n time += move + remove + (screws[i] === screws[i - 1] ? 0 : swapTool);\n }\n\n return time;\n}", "function increment_second(){\n /*sec ++ ;\n return sec;*/\nvar second_minute;\n second_minute = 60;\n//TODO [] Parcourir un tableau.\n console.log(second_minute.length);\n\n for(var i = 0; i < second_minute.length; i++){\n var second_plus = second_minute[i];\n\n console.log(\"Qu'est ce que celà donne: \"+ second_plus);\n // break;\n }\n return second_plus;\n}", "function sumConsecutives(s) {\n \n}", "function fixTheMeerkat(arr) {\n let out = [];\n arr.forEach((x,y) => out[arr.length - 1 - y] = x);\n return out;\n}", "function runLengthEncoding(str) {\n let encodedChars = [];\n\tlet currentRun = 1;\n\tfor (let i = 1; i < str.length; i++) {\n\t\tlet currentChar = str[i];\n\t\tlet prevChar = str[i - 1];\n\t\t\n\t\tif ((currentChar !== prevChar) || currentRun === 9) {\n\t\t\tencodedChars.push(currentRun.toString());\n\t\t\tencodedChars.push(prevChar);\n\t\t\tcurrentRun = 0;\n\t\t}\n\t\tcurrentRun += 1;\n\t}\n\t\n\tencodedChars.push(currentRun.toString());\n\tencodedChars.push(str[str.length - 1]);\n\treturn encodedChars.join(\"\")\n}", "function squashLettersTogether(acc, currentString, array){\n if (array.length === 0) {\n acc.push(currentString)\n return acc\n }\n else {\n var element = array.shift();\n if (element === currentString[0]) {\n var newString = currentString.concat(element);\n return squashLettersTogether(acc, newString, array)\n }\n else {\n acc.push(currentString)\n return squashLettersTogether(acc, element, array)\n }\n } \n}", "function timesTen(arr) {\n for (i = 0; i < arr.length; i++) {\n var newArr = arr[i] * 10;\n return newArr;\n }\n}", "function wordLength(word)\r\n{ var len=[]\r\n for (let i = 0; i < word.length; i++)\r\n {\r\n len[i]=word[i].length\r\n }\r\n return len\r\n}", "function longest_phrase(array) {\n console.log(\"Your array has \"+array.length + \" elements in it.\");\n var element_length = [];\n\n// 2.)\n for (i=0;i<array.length;i++) {\n\n// 3.)\n element_length.push(array[i].length);\n\n// 4.)\n var longest_string = Math.max(...element_length);\n }\n// 5.)\n var longest_phrase_index = element_length.indexOf(longest_string);\n\n// 6.) and 7.)\n console.log(\"The word in the array is: \" +array[longest_phrase_index]);\n}", "function countingValleys(s) {\n let counter = 0\n let valleys = 0\n for(var i=0; i<s.length;i++){\n if(s[i] == \"F\"){\n console.log(\"forward\")\n } else if (s[i] == \"D\"){\n counter -= 1\n } else if (s[i] == \"U\"){\n counter += 1\n if(counter == 0){\n valleys += 1\n }\n }\n }\n return valleys\n }", "function reverseArray(array){\n let temp = 0;\n for(let i = 0; i <= (array.length/2); i++){\n temp = array[i]; // 0 = 1;\n array[i] = array[array.length - 1 - i]; // 1 = arrays length - i, which is 1 = 4\n array[array.length - 1 - i] = temp; // \n console.log(array);\n }\n return array;\n}", "function cycleIterator(array) {\n let count = 0\n function innerFunc(){\n for(let i=0; i<array.length; i++){\n if(count < array.length){\n let result = array[count]\n count++\n return result\n }else{\n count = 0\n }\n };\n }\n return innerFunc\n}", "function frameIt(array) {\n let max = 0;\n for (let word of array) {\n if (word.length > max) {\n max = word.length\n\n }\n }\n console.log(\"*\".repeat(max + 4))\n array.forEach((item, i) => {\n const numberOfSpaces = max - item.length\n // console.log(numberOfSpaces)\n console.log('* ' + item + \" \".repeat(numberOfSpaces) + \" *\")\n\n // console.log(item)\n })\n console.log(\"*\".repeat(max + 4))\n}", "function adjustTimecodesBoundaries(words) {\n return words.map((word, index, arr) => {\n // excluding first element\n if (index != 0) {\n const previousWord = arr[index - 1];\n const currentWord = word;\n if (previousWord.end > currentWord.start) {\n word.start = previousWord.end;\n }\n\n return word;\n }\n\n return word;\n });\n}", "function findShort(s){\n\n var array = [];\n var auxArray = [];\n var auxElemento = 0;\n array = s;\n var separador = \" \" \n array = array.split(separador);\n\n var swap = true;\n\n for (let i = 0; i < array.length; i++) {\n auxArray.push(array[i].length);\n \n }\n array = auxArray;\n\n while (swap) {\n swap = false;\n\n for (let i = 0; i < array.length; i++) {\n if (array[i] > array [ i+1]) {\n\n auxElemento = array[i];\n array[i] = array [i+1];\n array[i+1] = auxElemento;\n swap = true;\n }\n \n }\n \n }\n return console.log(array[0]);\n\n}", "function calculateTimeout(counter, array) {\r\n var computerMessageLength = array[(counter)].length;\r\n var timeoutFactor = (computerMessageLength / 30);\r\n console.log(`Number of seconds for typing loader / setTimeout: ${timeoutFactor.toFixed(1)} seconds`)\r\n return (timeoutFactor * 1000); // multiple timeout factor by 1000 miliseconds for setTimeout length\r\n }", "function makeTimesMultipleBroken(arrayOfNs) {\n\tconst result = [];\n\tfor (var i = 0; i < arrayOfNs.length; i++) {\n\t\tconst index = i;\n\t\tresult.push(function(value) {\n\t\t\treturn times(value, arrayOfNs[index]);\n\t\t});\n\t}\n\treturn result;\n}", "function numOfPermutations(lettersArr) { let num = 1; for (let i = 1; i <= lettersArr.length; i++) { num *= i } return num }", "function stringShifter(s) {\n let counter = 0;\n for(let i=0; i < s.length; i++) {\n let tempVar = s.substring(i, s.length)+s.slice(0,i);\n if(tempVar[0] === tempVar[tempVar.length-1]) {\n counter++;\n }\n }\n return counter;\n}", "function incrementByOne (counter) {\n\n counter[0] += 1;\n\n for (i = 0; i < counter.length; i++){\n\n if (counter[i] > i){\n counter[i] = 0;\n counter[(i+1)] += 1;\n }\n }\n\n return counter;\n }", "function addLength(str) {\n//start-here\nreturn str.split(\" \").map(x => `${x} ${x.length}`)\n }", "function StringReduction(str) { \nvar res = str.length + 1;\n while(res>str.length){\n res = str.length;\n str = str.replace(/ab|ba/, 'c');\n str = str.replace(/ca|ac/, 'b');\n str = str.replace(/bc|cb/, 'a');\n } ;\n \n // code goes here \n return str.length; \n \n}", "function solution3(A) {\n count = 0;\n for (i = 0; i < A.length; i++) {\n if (i + 1 > A.length || i + 2 > A.length) {\n } else if (A[i] - A[i + 1] == A[i + 1] - A[i + 2]) {\n count += 1;\n\n let newA = A.slice(i + 2)\n let dist = A[i] - A[i + 1]\n\n for (j = 0; j < newA.length; j++) {\n if (j + 1 >= A.length) {\n console.log(\"No more new array!\")\n } else if (newA[j] - newA[j + 1] == dist) {\n count += 1;\n }\n }\n }\n }\n // console.log(count)\n}", "function adjustTimecodesBoundaries(words) {\n return words.map((word, index, arr) => {\n // excluding first element\n if (index !== 0) {\n const previousWord = arr[index - 1];\n const currentWord = word;\n if (previousWord.end > currentWord.start) {\n word.start = previousWord.end;\n }\n\n return word;\n }\n\n return word;\n });\n}", "function generateNewSequence(arrLength){\n console.log(\"this is the array length being passed into generate new sequence \"+arrLength);\n const colorChoice=[\"red\",\"orange\",\"lime\",\"yellow\"];\n\n for(let i=0; i<arrLength; i++){\n // console.log(\"iterator of loop that pushes colors to automated sequence: \"+i);\n const randomColorIndex=Math.floor(Math.random()*colorChoice.length);\n // console.log(\"random color \"+colorChoice[randomColorIndex]);\n automatedArray.push(colorChoice[randomColorIndex]);\n }\n // console.log(\"result of newly created sequence \"+automatedArray);\n playerChoice.length=0;\n clickCounter=0;\n}", "function length (history) {\n const { past, future } = history\n return past.length + 1 + future.length\n}", "function arrayPalindrome(array){\n let len = array.length;\n for(let i = 0; i < array.length/2; i++){\n if(array[i] !== array[len - i - 1]){ //if array[i] is not equal to length of the array - i - 1 ... \n return false;\n }\n }\n return true;\n}" ]
[ "0.70563996", "0.6950846", "0.69185436", "0.68652797", "0.68445075", "0.6233782", "0.6169983", "0.6168231", "0.6058266", "0.60278684", "0.5944811", "0.58830535", "0.5882414", "0.5815312", "0.5780303", "0.5755633", "0.5639378", "0.56136996", "0.56085646", "0.56011456", "0.5558851", "0.55125755", "0.5484037", "0.5409409", "0.5403722", "0.5374271", "0.53540415", "0.5331456", "0.5309684", "0.5308125", "0.53010374", "0.5290345", "0.5270045", "0.52478856", "0.51968443", "0.5167576", "0.51547414", "0.5149052", "0.51471734", "0.5142399", "0.51405305", "0.513914", "0.51360387", "0.5115131", "0.5115035", "0.5110195", "0.5098014", "0.5094797", "0.5083513", "0.5083267", "0.5077378", "0.50716317", "0.50487864", "0.50480807", "0.5044045", "0.50434303", "0.503434", "0.5020924", "0.50095075", "0.49996707", "0.49994364", "0.49986276", "0.4971663", "0.49600708", "0.49600473", "0.4956661", "0.49546582", "0.49542892", "0.49532822", "0.49505997", "0.49491104", "0.49353713", "0.4935031", "0.49345866", "0.49311182", "0.49284506", "0.49234226", "0.49220487", "0.49212843", "0.49211812", "0.4919844", "0.49180079", "0.4913061", "0.4906436", "0.49035287", "0.49029082", "0.4902321", "0.49021202", "0.48933798", "0.48921022", "0.4889482", "0.48870105", "0.4882261", "0.4879588", "0.48782945", "0.48766053", "0.4876602", "0.4872708", "0.48683152", "0.4864139" ]
0.6862273
4
console.log(previousLengths(["hello", "dojo", "awesome","what"])); Challenge 9 Add Seven to Most Build a function that accepts an array. Return a new array with all the values of the original, but add 7 to each. Do not alter the original array. Example, addSeven([1,2,3]) should return [8,9,10] in a new array.
function addSeven(arr) { var newArr = []; for(var i = 0; i < arr.length; i++) { newArr[i] = arr[i] + 7; } return newArr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function previousLengths(arr){\n for(var i=0;i<arr.length-1;i++){\n arr[i+1]=arr[i].length;\n }\n return arr;\n\n}", "function previousLengths(arr){\n for(i=arr.length-1; i>0; i--){\n arr[i] = arr[i-1].length;\n }\n return arr;\n}", "function previousLengths(arr) {\n for(var i = arr.length - 1; i > 0; i--) {\n arr[i] = arr[i - 1].length;\n }\n return arr;\n}", "function previousLengths(arr){\n for(let i = arr.length - 1; i > 0; i--){\n arr[i] = arr[i - 1].length // Loop 1 - arr[2] = arr[1]\n }\n return arr\n }", "function previouslengths(arr){\n \n for(var i=arr.length-1;i>0;i--){\n arr[i]=arr[i-1].length;\n }\n return arr;\n}", "function addSevenToMost(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n if(i == 0){\n continue;\n } else {\n newArr.push(arr[i] + 7);\n }\n }\n return newArr;\n}", "function addSevenToMost(arr) {\n for(var i=0; i<arr.length; i++) {\n arr[i] = arr[i] + 7;\n }\n return arr;\n}", "function addSeven2Most(arr) {\n var newArr = [];\n for (i=1; i<arr.length; i++) {\n newArr.push(arr[i]+7);\n }\n return newArr;\n}", "function addSevenToMost(arr) {\n var result_arr = [];\n for (var i = 1; i < arr.length; i++) {\n result_arr.push(arr[i]+7);\n }\n return result_arr;\n}", "function luckySeven(arr){\n let newArr = [];\n for(let i = 0; i < arr.length; i++){\n newArr.push(arr[i] + 7);\n }\n arr = newArr;\n return arr;\n}", "function addSevenToMost(arr) {\n var newArr = [];\n var sum = 0;\n for(var i = 0; i < arr.length; i++) {\n sum = arr[i] + 7;\n newArr.push(sum);\n }\n return newArr;\n}", "function previousLengths(array) {\n for (var i = array.length - 1; i >= 0; i--) {\n console.log(\"array[\" + i + \"]: \" + array[i]);\n \n // if the i === 0, just stop\n if (i !== 0) {\n var element = array[i - 1];\n console.log(\"length of previous value: \" + element.length)\n array[i] = element.length;\n }\n }\n return array;\n}", "function addSeven(arr){\n var new_arr =[];\n for(var i=0;i<arr.length;i++){\n new_arr.push(arr[i]+7);\n }\n return new_arr;\n}", "function addSeven(arr){\n var newArr = []\n for(i = 1; i < arr.length; i++){\n newArr.push(arr[i] + 7)\n } \n return newArr\n}", "function addSeven(arr){\n var newarr = [];\n for(var i = 0; i < arr.length; i++){\n newarr.push( arr[i] = arr[i] + 7);\n }\n return newarr;\n}", "function getLengthsPart2(puzzleInput){\n // \"Once you have determined the sequence of lengths to use, add the following lengths to the end of the sequence:\"\n var sequenceToAdd = \"17, 31, 73, 47, 23\";\n\n // For example, if you are given 1,2,3, your final sequence of lengths should be 49,44,50,44,51,17,31,73,47,23\n var a = [];\n \n puzzleInput.split(\"\").forEach(character => {\n a.push(character.charCodeAt(0));\n });\n\n sequenceToAdd.split(\",\").forEach(character => {\n a.push(+character);\n });\n\n return a;\n}", "function addSeven(arr){\n\tnewArr = [];\n\n\tfor (var num = 1; num < arr.length; num++) {\n\t\tnewArr.push(arr[num] + 7);\n\t}\n\n\tconsole.log(newArr);\n\treturn(newArr);\n\n}", "function seven(arr) {\n var addSeven = 7;\n for (var i = 0; i < arr.length; i++) {\n arr[i] += addSeven;\n\n }\n return arr;\n}", "function addseven(arr){\n for (var i=0;i<arr.length;i++){\n arr[i]=arr[i]+7;\n }\n return arr;\n}", "function addSevenNewArray(array) {\n var plusSevenArray = [];\n\n for (var i in array) {\n plusSevenArray[i] = array[i] + 7;\n }\n\n return plusSevenArray;\n}", "function improved(array) {\n var prev = new Array(array.length);\n var next = new Array(array.length);\n\n var prev_index = 0;\n addPrevious(prev, array);\n addNext(next, array);\n\n array = multiply(prev, next);\n console.log(array);\n}", "function seventoMost(arr){\n let newArr=[]\n for (let i =1; i < arr.length; i++){\n newArr.push(arr[i] +7)\n }\n return newArr\n}", "function AddSeven(arr){\n var newarr = [];\n for(var i = 1; i < arr.length; i++){\n newarr.push(arr[i]+7);\n }\n console.log(newarr);\n }", "function makeArray(arrayLength)\n{\n //Solution goes here.\n}", "function f9(arr) {\n return arr\n .sort((a, b) => a - b)\n .slice(-5)\n .reduce((acc, el) => acc + el, 0);\n}", "function createArray(length) {\n let temp_array = [0];\n let help_flag = false;\n\n for(let i=1; i<=length;i++) {\n \n temp_array.push(temp_array[i-1]+1);\n \n }\n for(let i=length;i>0;i--) {\n temp_array.push(temp_array[i]-1);\n }\n return temp_array;\n}", "function fixTheMeerkat(arr) {\n let out = [];\n arr.forEach((x,y) => out[arr.length - 1 - y] = x);\n return out;\n}", "function sortByLength (array) {\n var temp = \"\";\n for (var i = 0; i < array.length ; i++){\n var j = i;\n while(j > 0 && array[j-1].length > array[j].length){\n temp = array[j]\n array[j] = array[j-1];\n array[j-1] = temp;\n j--\n }\n }\n return array;\n}", "function seven(){\n var newArray = [];\n for(var i = 1; i < 50; i+=2){\n newArray.push(i);\n }\n return newArray;\n}", "function largerThenThree(array) {\n let newArray = []\n\n for(const number of array) {\n if (number > 7) {\n newArray.push(number)\n }\n }\n\n return newArray\n}", "_subtractOverflows(length, ...overflows) {\n return overflows.reduce((currentValue, currentOverflow) => {\n return currentValue - Math.max(currentOverflow, 0);\n }, length);\n }", "function addSeven(arr){\n var newArr = []\n for(e in arr){\n newArr[e] = arr[e] + 7;\n }\n return newArr\n}", "function main(inputArr){\n sumFirstLastByUnshiftPop(inputArr);\n}", "function unusualFive() {\n let array =[\"a\",\"b\",\"c\",\"d\",\"e\"]\nreturn array.length\n}", "function solveDay10Part1(input){\n input.lengths.forEach(length =>{\n // Reverse the order of that length of elements in the list, starting with the element at the current position.\n reverseSubArray(input.array, input.currentPosition, length);\n\n // Move the current position forward by that length plus the skip size.\n input.currentPosition += length + input.skipSize; \n\n // Increase the skip size by one.\n input.skipSize++;\n });\n\n var solution = +input.array[0] * +input.array[1];\n\n return solution;\n}", "function num_lost_words(pre_set_word_array_array, min_length){\n let lost_options = 0;\n for(let pre_set_word_array of pre_set_word_array_array){\n let lost_len = min_length - pre_set_word_array.length;\n lost_options += Math.pow(letters.length,lost_len);\n }\n return lost_options;\n }", "function sumOfSelves(arr){\n//for each array element, sum itself plus the preceeding elements\n//add that new sum to a new array\n let result=arr;\n for (let i=arr.length-1;i<arr.length;i--){\n result[i]=(arr[i)\n }\n\n console.log(\"#12: \"+result);\n}", "function addRightwards(arrayToAdd){\r\n for (let i = 0; i < 4; i++){\r\n // Creates a 1x4 array which only contains non-zero elements\r\n // Returned array can be < 4 long\r\n let tempArray = arrayToAdd[i].filter(num => num > 0);\r\n // Prepends zeros to the 1x4 array to maintain the 1x4 size\r\n while (tempArray.length < 4){\r\n tempArray.unshift(0);\r\n }\r\n // Adds from the RHS side\r\n for (let j = 3; j >= 1; j--){\r\n if (tempArray[j] === tempArray[j-1]){\r\n // Sets the RHS element to 2x the original value\r\n tempArray[j] = tempArray[j] + tempArray[j-1]\r\n // Removes the LHS value and prepends a zero to maintain 1x4 size\r\n tempArray.splice(j-1,1);\r\n tempArray.unshift(0)\r\n }\r\n }\r\n arrayToAdd[i] = tempArray;\r\n }\r\n}", "function slasher(arr, howMany) {\n var counter = 0;\n while (counter < howMany) {\n arr.shift(0); //shift method mutates original array. \n counter++;\n }\n return arr;\n}", "function upArray(arr){ \n\n \n if(arr.length == 0) {\n return null; \n }\n \n if(arr.length > 16) {\n val = arr[arr.length - 1];\n arr[arr.length - 1] = val + 1; \n return arr; \n }\n \n for(var i = 0; i < arr.length; i++) {\n if(arr[i] < 0 || arr[i].toString().length > 1) {\n return null; \n }\n }\n \n var strings = \"\";\n arr.map(function(item) {\n strings += item;\n });\n \n\n var newValue = (parseInt(strings) + 1).toString(); \n console.log(newValue); \n var output = [];\n \n for(var i = 0; i < newValue.length; i++) {\n output.push(parseInt(newValue.charAt(i))); \n }\n \n return output; \n \n}", "function sevenToMost(arr)\n{\n var map= arr.map(x => x+7)\n map[0]-=7\n return map\n \n}", "function doReturnArray(array) {\n array[array.length] = 10;\n return array.reverse();\n}", "function sum_array_length ( array_one, array_two, array_three, array_four){\n\n sum_array = [];\n sum_array.push.apply(sum_array, array_one);\n sum_array.push.apply(sum_array, array_two);\n sum_array.push.apply(sum_array, array_three);\n \n console.log( sum_array.length + \" \" + sum_array + \" sum_array longitud\" );\n \n}", "function getMissedNumsLength(arr) {\n arr.sort((a,b) => a - b);\n return arr[arr.length - 1] - arr[0] + 1 - arr.length; \n}", "function arrayChange(inputArray) {\n let steps = 0;\n \n for (let i = 0; i < inputArray.length - 1; i++) {\n while (inputArray[i] >= inputArray[i + 1]) {\n inputArray[i+1] += 1;\n steps += 1;\n }\n }\n return steps;\n}", "function decreaseArray(list){\r\n list.unshift(10);\r\n var answer =list.reduce(function(element1, element2){\r\n return element1 + element2; \r\n });\r\n return answer ;\r\n}", "function maxLength(arr) {\n return Math.max(...arr.map((word)=>{return word.length}))\n //(10,4,9,13): returns 13\n}", "function functionalLengths(states) {\n return states.reduce((lengths, state) => {\n lengths[state] = state.length;\n return lengths;\n },{});\n \n}", "function generateArrayLength(a, b) {\r\n var arr = []\r\n arr.push(a);\r\n var count = a;\r\n for (var i = 0; i < b - 1; i++) {\r\n count++;\r\n arr.push(count);\r\n }\r\n return arr\r\n}", "function looper (len) {\n\tvar results = [];\n\tfor (var i = 0; i < len -1; i+=2){\n\t\tresults.push(i);\n\t};\n\treturn results.map(function(element){\n\t\treturn element * 3;\n\t})\n}", "function twelve(arr){\n for(var i = 0; i < arr.length; i++){\n var temp = arr[0];\n arr[0] = arr[arr.length-1]; \n arr[arr.length-1] = temp; \n }\n return arr; \n}", "function thisLength(num1, num2) {\n if(num1 === num2){\n console.log( \"Jinx\");\n }\n var arr = [];\n for(var i = num1; i >= 0; i--){\n arr.push(num2);\n }\n return arr;\n }", "function imperativeLengths(states) {\n let lengths = [];\n states.forEach(function(state) {\n lengths[state] = state.length; \n });\n return lengths;\n}", "function PrevArray(seed, seed_size) {\n let arr = [];\n let startNumber;\n for (let i = seed_size; i > 0; i--) {\n\t\tif (i==seed_size)\n\t\t\tstartNumber = seed - i;\n\t\t//console.log(\"i\", i);\n\t\tarr.push(seed - i);\n\t\tconsole.log(seed-i)\n\t\t\n }\n return [arr, startNumber];\n}", "function calcArraySum(arrayEntered) {\n let total = 0;\n let totalString = \"\";\n for (let num of arrayEntered) {\n total += num;\n totalString += num + \" + \";\n }\n\n console.log(totalString.slice(0, -3) + \" = \" + total);\n}", "function previous(arr){\n for( var i = arr.length - 1; i >= 0; i--){\n arr[i] = string //what is string length?\n }\n}", "function longerThan (arr, num)\n{\n\nvar output = arr.filter( x => x.length > num )\n\nreturn output\n}", "function stringsLength(array) {\n\n for (i = 0; i < array.length; i++) {\n \n numArray.push(strLength(array[i]));\n }\n return numArray;\n}", "function func12(inputArray){\n var temp=inputArray[0];\n inputArray[0]=inputArray[inputArray.length-1];\n inputArray[inputArray.length-1]=temp;\n return inputArray;\n}", "function lengths(arr){\n return arr.map(f => f.length);\n}", "function equalizeArray(numbers) {\n const counts = getEntryCounts(numbers);\n\n const maxCount = counts.reduce((total, count) => Math.max(total, count));\n\n return numbers.length - maxCount;\n}", "function howMany(array) {\n return array.length;\n}", "function listLengthOfAllWords(array) {\n for (let j = 0; j < array.length; j++) {\n array[j] = array[j].length ;\n };\n return array\n}", "function largestOfFour(arr) {\n // You can do this!\n var newArray = [];\n for (var i = 0; i < arr.length; i++){\n console.log(arr[i]);\n var biggest = Math.max.apply(null, arr[i]);\n newArray.push(biggest);\n\n }\n console.log(newArray);\n return newArray;\n}", "function getLength(array) {\n console.log(array);\n // base case\n if (array[0] === undefined) return 0;\n // recursive call\n // return 1+ getLength(array without the first value)\n return 1 + getLength(array.slice(1));\n}", "function reverseWords2(string) {\n let stringArray = string.split(' ');\n\n stringArray = stringArray.map((function length(currentValue) {\n if (currentValue.length >= 5) {\n return currentValue.split('').reverse().join('');\n } else {\n return currentValue;\n }\n }));\n return console.log(stringArray.join(' '));\n}", "function incrementInteger(array){\n array[array.length - 1] += 1;\n return array;\n}", "function fixTheMeerkat(arr) {\n return arr.reverse()\n}", "function longPlanets2(someArray){\n var longPlanets2 = [];\n someArray.forEach(function(item){\n if (item.length >= 7){\n longPlanets2.push(item);\n }\n })\n return longPlanets2\n}", "function fixTheMeerkat(arr) {\n let givenArr = arr;\n return givenArr.reverse()\n}", "function backNewNumber(number) {\n const newNumber = [];\n let j = number.length - 1;\n while (j >= 0) {\n number[j] += 1;\n if (number[j] > 9) {\n j -= 1;\n } else {\n break;\n }\n }\n\n number.map((item) => {\n if (item <= 9) {\n newNumber.push(item);\n }\n });\n if (newNumber.length === 0) {\n return null;\n }\n\n return newNumber;\n}", "function timesTen(arr) {\n for (i = 0; i < arr.length; i++) {\n var newArr = arr[i] * 10;\n return newArr;\n }\n}", "function sortByLength(arr) {\n return arr.sort((a, b) => a.length - b.length);\n}", "function arrayManipulation(n, queries) {\n let max = 0;\n\n for (let q of queries) {\n max += q[2];\n }\n\n let range = [0, n - 1];\n let len = queries.length;\n\n // 6 12 // 6\n}", "function push(array) {\n var lastIndex = array.length -1;\n \n for (var i = 1; i < arguments.length; i++) {\n array[lastIndex + i] = arguments[i];\n }\n\n return array.length\n}", "function upArray(arr) {\n if(arr.length === 0 || arr[arr.length - 1] < 0) return null\n arr[arr.length - 1]++\n for(let i = arr.length - 1; i >= 0; i--) {\n if(arr[i] === 10) {\n arr[i - 1]++\n arr[i] = 0\n if(i === 0 ) arr.unshift(1) \n }\n if(arr[i] > 10 || arr[i] < 0) return null\n } return arr\n}", "function returnReverso(array) { //array= [1,2,3,4]; array.length = 4; \n\n let nuevoArreglo = []; //[4,3,2,1]\n for (let i = array.length - 1; i >= 0; i--) { //i =3>2>1>0>-1\n nuevoArreglo.push(array[i]);\n }\n return nuevoArreglo;\n}", "function sumItUp(arr){\n var total=0;\n for(var i=0; i < arr.length; i++ )\n {\n console.log[i]; \n var subtotal=numArray[0]+[1];\n var numArray=numArray.shift;\n return subtotal; \n }\n}", "function sumItUp(arr){\n var total=0;\n for(var i=0; i < arr.length; i++ )\n {\n console.log[i]; \n var subtotal=numArray[0]+[1];\n var numArray=numArray.shift;\n return subtotal; \n }\n}", "function countup(n) {\n if (n < 1) {\n return [];\n } else {\n alert(n)\n const countArray = countup(n - 1);\n //alert(n);\n //alert(countArray);\n countArray.push(n);\n //alert(countArray);\n return countArray;\n }\n}", "function addto(arr,num){\n if(arr.length < num){\n return null;\n }\n let tempSum = 0;\n let maxSum = 0;\n for(let i = 0; i<num ; i++){\n maxSum += arr[i];\n }\n \ntempSum = maxSum;\n for(let i = num;i<arr.length;i++){\n \n tempSum = tempSum - arr[i-num] + arr[i]; //8+arr[2]-arr[2-2] === 8+0-7\n maxSum = Math.max(tempSum,maxSum);\n console.log(maxSum)\n }\n return maxSum;\n}", "function sortByLength(array) {\n if (array instanceof Array) {\n let localArray = [...array];\n localArray.sort((name1, name2) => name1.length - name2.length);\n return localArray;\n } else {\n return \"Invalid\";\n }\n}", "function mainpop(){\n Array.SIZE_RATIO = 3;\n let arr = new Array();\n arr.push(3);\n arr.push(5);\n arr.push(15);\n arr.push(19);\n arr.push(45);\n arr.push(10);\n arr.pop();\n arr.pop();\n arr.pop();\n console.log(arr); \n console.log(arr.length); \n}", "function FPL(arr){\n var sum = 0;\n for(var i = 0; i < arr.length; i++){\n sum = (arr[0] + arr.length);\n }\n console.log(sum);\n}", "function slasher(arr, howMany) {\n\n for (var i = 0; i < howMany; i++) {\n arr.shift();\n }\n\n return arr;\n}", "function longestStringReducing(array) {\n const reduced = array.reduce(function (longestWord, word) {\n return word.length > longestWord ? word : longestWord;\n }, \"\");\n console.log(reduced.length);\n console.log(reduced);\n return reduced.length;\n return reduced;\n}", "function addFive() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tnewArray.push(oldArray[i] + 5);\n}\n}", "function largest(){\n var n=4\n var array=[ 43, 56, 23, 89, 88, 90, 99, 652]\n var newArray=array.sort(function(a,b){\n return b-a\n // return a-b\n })\n // return newArray.slice(-n).shift()\n return newArray[n-1]\n}", "function pipeFix(numbers) {\n\t// create an array\n\tlet nums = [];\n\n\t// iterate starting at index 0 and ending at including the last element\n\tfor (let i = numbers[0]; i <= numbers[numbers.length - 1]; i++) {\n\t\tnums.push(i);\n\t}\n\t// return new array\n\treturn nums;\n}", "function returnReverso(array) { //array= [1,2,3,4]; array.length = 4; \n let nuevoArreglo = []; //[4,3,2,1]\n for (let i = array.length - 1; i >= 0; i--) { //i =3>2>1>0>-1\n nuevoArreglo.push(array[i]);\n }\n return nuevoArreglo;\n}", "function score(dice) {\n\n let result = 0;\n let newArr = [];\n for (let i=1; i<=6; i++){\n newArr.push(dice.filter((num) => num === i))\n }\n\n console.log(newArr);\n\n switch (newArr[0].length){\n case 0:\n break;\n\n case 1:\n result += 100;\n break;\n\n case 2:\n result += 200;\n break;\n\n case 3:\n result += 1000;\n break;\n\n case 4:\n result += 1100;\n break;\n\n case 5:\n result += 1200;\n break;\n }\n\n switch (newArr[4].length){\n case 0:\n break;\n\n case 1:\n result += 50;\n break;\n\n case 2:\n result += 100;\n break;\n\n case 4:\n result += 50;\n break;\n\n case 5:\n result += 100;\n break;\n }\n\n\n let score = 600;\n for (let i=5; i>0; i--){\n if (newArr[i].length >= 3){\n result += score;\n }\n score -= 100;\n }\n\n\nreturn result;\n\n \n \n}", "function backWards(arr) {\n var newArray = [];\n\n for (var i = arr.length - 1; i >= 0; i--) {\n // code\n newArray.push(arr[i]);\n }\n\n return newArray;\n}", "function maxLength2(a, k) {\n let answer = 0\n for (i = 0; i < a.length; i++) {\n let total = 0\n let l = 0\n let curInd = i\n while (total <= k && curInd < a.length) {\n l++\n total = total + a[curInd]\n console.log(total + \"total\" + l)\n curInd++\n }\n if (curInd)\n if ( l - 1 > answer) answer = l - 1\n }\n return answer\n}", "function slasher(arr, howMany) {\n // it doesn't always pay to be first\n return arr;\n}", "function thirteenEx(array13) {\n let arrayMax = Math.max(...array13);\n console.log(arrayMax);\n return arrayMax;\n}", "function steamrollArray(arr) {\n var newArr = [];\n // var arrCopy = [...arr];\n var arrLength = arr.length;\n var n = 0;\n while (arr.length > 0) {\n var val = arr.shift();\n if (Array.isArray(val)) { \n arr = val.concat(arr);\n } else {\n newArr.push(val);\n }\n }\n console.log(newArr);\n return newArr;\n }", "function thisLength(num1, num2) {\n var arr = []\n for (i = 0; i < num1; i++) {\n arr.push(num2)\n }\n return arr\n}", "function mutateTheArray(n, a) {\n if (n === 1) {\n return a;\n }\n var result = new Array(n);\n \n for (let i = 0; i < n; i++) {\n let left = a[i-1] ? a[i-1] : 0;\n let curr = a[i]\n let right = a[i+1] ? a[i+1] : 0;\n \n result[i] = (left+curr+right)\n } \n return result; \n \n}", "function shorterInArray(arr){\n\tvar short= arr[0].length;\n for (i=0 ; i<arr.length ; i++){\n if (short > arr[i].length){\n \tshort=arr[i];\n }\n }return short;\n}", "function takeRight(array, count) {\n var newArray = [];\n if (array.length > count) {\n for (var i = array.length - 1; i >= array.length - count; i--) {\n newArray.unshift(array[i]);\n }\n } else {\n newArray = array;\n }\n return newArray;\n}" ]
[ "0.72804934", "0.7237461", "0.71827894", "0.70686823", "0.6862755", "0.6730513", "0.6687041", "0.6636175", "0.66083074", "0.6567686", "0.6561311", "0.6548345", "0.63130236", "0.62699515", "0.61957395", "0.615735", "0.61298513", "0.60966927", "0.60307616", "0.6024432", "0.5985571", "0.59690434", "0.5953507", "0.5933495", "0.5813289", "0.57809645", "0.57539624", "0.5744335", "0.5735715", "0.5715513", "0.57105756", "0.5695503", "0.56578726", "0.56400424", "0.56291264", "0.5610671", "0.55786395", "0.5575406", "0.55735403", "0.5543578", "0.5520263", "0.5508955", "0.5480264", "0.547594", "0.5473405", "0.545042", "0.54436725", "0.5419957", "0.54061043", "0.5398475", "0.53893715", "0.5383638", "0.5380478", "0.5374248", "0.537135", "0.5369156", "0.5365", "0.5358656", "0.5332277", "0.5330376", "0.53226423", "0.531149", "0.53024995", "0.530163", "0.52867925", "0.528595", "0.5283345", "0.52812195", "0.52742517", "0.52676344", "0.52529377", "0.52484626", "0.5248026", "0.52412194", "0.52411425", "0.523667", "0.5235326", "0.5233623", "0.5233623", "0.52300394", "0.5227831", "0.5221774", "0.5219076", "0.5212385", "0.5208683", "0.520458", "0.52006197", "0.51994485", "0.5197219", "0.51971817", "0.5195565", "0.5176151", "0.51733786", "0.5171937", "0.51699257", "0.51685995", "0.51657075", "0.51652527", "0.516503", "0.51644546" ]
0.62820715
13
console.log(addSeven([1,2,3])); Challenge 10 Reverse Array Given an array, write a function that reverses its values, inplace. Example: reverse([3,1,6,4,2]) returns the same array, but now contains values reversed like so... [2,4,6,1,3]. Do this without creating an empty temporary array. (Hint: you'll need to swap values).
function reverse(arr) { for(var i = 0; i < arr.length/2; i++) { var temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reverse(arr){\n //code\n}", "function reverseInPlace(array) {\n let len = array.length;\n for (let i = len - 1; i >= 0; i -= 1) {\n array.push(array[i]);\n }\n while (len > 0) {\n array.shift();\n len -= 1;\n }\n return array;\n}", "function reverseArrayInPlace (arr) {\n\tvar initLen = Math.floor(arr.length / 2),\n\t\tremoveIndex,\n valStore;\n print(\"Number of Iterations: \" + initLen);\n\tfor (var i = 0; i < initLen; i += 1) {\n valStore = arr[i]; // 1\n\t\tarr[i] = arr[arr.length - 1 - i]; // 5 to front\n arr[arr.length - 1 - i] = valStore;\n print(\"current array length: \" + arr.length);\n print(\"Iteration \" + i);\n print(\"Array: \" + arr);\n\t}\n\treturn arr;\n}", "function reverseArr(arr) {\n // code here\n}", "function reverseFunc(array) {\n let reversedNumbers = [];\n\n for (let index = array.length - 1; index >= 0; index--) {\n let currentNumber = array[index];\n reversedNumbers.push(currentNumber);\n }\n\n return reversedNumbers;\n // use for loop to repeat process until theres no more numbers inside array\n // create a variable that represents the new reverse-array\n // .pop off the last number from the original array (or just use array[index] instead of array.pop())\n // then .push() that popped off number into that new reverse-array\n // return the new array\n}", "function reverse(arr) {\n return arr.reverse();\n}", "function swapArr(arr){\nreturn arr.reverse();\n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length / 2); i++) {\n // swaps the number at the index with it's mirror, until you get to the middle number\n let old = array[i];\n array[i] = array[array.length - 1 - i]; // Where the index is gets assigned it's mirror\n // console.log(array);\n array[array.length - 1 - i] = old; // it's mirror gets assigned the value you saved from the original index\n // console.log(array);\n }\n return array;\n}", "function reverseArrayInPlace2(arr){\n for(var i = 0; i < arr.length / 2; i++){\n var tempVar = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = tempVar;\n }\n return arr;\n}", "function reverseArray (array) {\n array.reverse();\n}", "function reverseInPlace(arr) {\n var temp\n for (var i = 0; i < arr.length / 2; i++) { //add math.floor(arr.length/2) IF you have an odd numbered array. \n temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n console.log(\"Loop no: \" + i + \":\" + arr) //This is only to show us what is happening and how it is happening.\n }\n return arr\n}", "function reverseArrayInPlace(arr) {\n const newArr = [];\n\n for (let i = 0; i < arr.length; i++) {\n newArr.unshift(arr[i]);\n }\n return console.log(newArr);\n}", "function rev(arr){\n arr.reverse();\n console.log(arr);\n}", "function reverseArray(arr) {\n arr.reverse();\n}", "function subtractReverse(array) {\n //Write your code here\n}", "function reverseArrayInPlace(array) {\n for (i = 0; i <= Math.floor(array.length / 2); i++) {\n a = array[i];\n b = array[array.length - 1 - i];\n array[i] = b;\n array[array.length - 1 - i] = a;\n }\n return array;\n}", "function three(arr){\n return arr.reverse(); \n}", "function reverse(arr){ //arr = [\"a\",\"b\",\"c\",\"d\",\"e\"];\n var temp = []; //temp stands for temparary\n for(var i=arr.length-1; i > 0;i--){ //the loop that loops through half of the array.\n temp[i] = arr[i];\n }\n console.log(arr); //logs out the newly edited array.\n}", "function reverse(arr) {\n return arr.reverse()\n }", "function reverseArrayInPlace(array){\n\n let end = array.length - 1;\n let start = 0;\n while(end > start){\n \n let tmp = array[start]\n\n array[start] = array[end]\n array[end] = tmp\n\n end--;\n start++;\n }\n return array;\n}", "function reverseArray(arr) {\n\tarr.reverse();\n\tconsole.log(arr);\n}", "function fun1(){\nvar arry=[\"abc\",\"def\",\"ghi\"];\ndocument.write(arry);\n\nvar new_arry=arry.reverse()\ndocument.write(\"<br>\");\ndocument.write(new_arry);\n}", "function reverseArrayTwo(inArray){\n counter = 0;\n\n for(let i = inArray.length-1; i >=0; i -- ){\n let temp = inArray[i];\n inArray[i]= inArray[counter];\n inArray[counter] = temp;\n counter ++;\n }\n}", "function reverse(arr) {\n var newarr = [];\n for (i = arr.length-1; i > -1; i--) {\n newarr.push(arr[i]);\n }\n arr = newarr;\n return arr;\n}", "function reverseThis(arrayEntered) {\n return arrayEntered.reverse();\n}", "function reverseArrayInPlace(arr) {\n for (var i = 0; i < Math.floor(arr.length / 2); i++) {\n var temp = arr[i];\n arr[i] = arr[((arr.length - 1) - i)];\n arr[((arr.length - 1) - i)] = temp;\n }\n}", "function reverse(theArray){\nconst newArray = [];\nfor (let i= theArray.length -1; i>= 0; i--){\nnewArray.push(theArray [i]);\n}\nreturn newArray;\n}", "function reverseArr(arg) {\n return arg.reverse();\n}", "function reverse(arr){\n y = arr.length-1;\n for (x = 0; x < arr.length/2; x++){\n var swap = arr[x];\n arr[x] = arr[y];\n arr[y] = swap;\n y = y - 1;\n }\n return arr;\n}", "function reverseArrayInPlace(arr) {\n for (let i = 0; i <= arr.length / 2; i++) {\n let element = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = element;\n }\n return arr;\n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length/2); i++) {\n let oldIndexValue = array[i];\n array[i] = array[(array.length - 1) - i];\n array[(array.length - 1) - i] = oldIndexValue;\n } \n return array;\n}", "function f3(arr) {\n // return [...arr].concat(arr.reverse());\n return arr.concat(arr.slice().reverse());\n}", "reverseArrayInPlace(arr) {\n for(let i=0; i < Math.floor(arr.length/2); i++) {\n let currEl = arr[i],\n newPos = (arr.length-1) - i;\n \n // Set the value of the index position we're currently on with whatever the value is at the index we want to swap with.\n arr[i] = arr[newPos];\n\n // Set the value of the corresponding index position we swap with to the value we stored in current element, currEl.\n arr[newPos] = currEl;\n }\n\n return arr;\n }", "reverse(arr) {\n return arr.reverse();\n }", "function reversearr(arr){\n // for(var i=0;i<arr.length/2;i++){\n // var temp=arr[i];\n // arr[i]=arr[arr.length-1-i];\n // arr[arr.length-1-i]=temp;\n for(var i=0;i<arr.length;i++){\n arr[i]=arr[i+1];\n \n }\n return arr;\n}", "function reverseArray(array) {\n return array.reverse();\n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length / 2); i++) {\n let old = array[i];\n array[i] = array[array.length - 1 - i];\n array[array.length - 1 - i] = old;\n }\n return array;\n}", "function reverse(arr)\n{\n var temp;\n var end=arr.length-1\n for(var i=0; i<arr.length/2; i++)\n {\n \n temp=arr[i];\n arr[i]=arr[end-i];\n arr[end-i]=temp;\n }\n return arr\n}", "function reverseArrayInPlace(newArray) {\n\n\tfor(var i = 0; i < newArray.length; i++){\n\t\tnewArray[i] = newArray.length-i;\n\t}\n\n\t return newArray;\n}", "function revArray(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.unshift(arr[i]);\n }\n document.getElementById(\"3\").innerHTML = newArr;\n return newArr;\n}", "function reverser(arr){\n var x = 0;\n for(var e=0; e<arr.length/2; e++){\n x = arr[e];\n arr[e] = arr[arr.length-1-e];\n arr[arr.length-1-e] = x;\n }\n return arr;\n}", "function fixTheMeerkat(arr) {\n let givenArr = arr;\n return givenArr.reverse()\n}", "function reverseArrayInPlace(x){\n\tvar size = x;\n\tx = [];\n\tfor( i = 0; i < size.length; i++){\n\t\tx.unshift(size[i]);\n\t} \n\treturn x;\n}", "function reverseArrayInPlace(anArray) {\n var temp = 0;\n var listLength = anArray.length;\n \n for (var i = 0; i < Math.floor(listLength / 2); i++) {\n\ttemp = anArray[i];\n\tanArray[i] = anArray[listLength - 1 - i];\n\tanArray[listLength - 1 - i] = temp;\n }\n}", "function reverse(numbers) {\n let startIndex = 0;\n let lastIndex = numbers.length-1;\n\n while (startIndex < lastIndex){\n // swapping items here\n [numbers[startIndex], numbers[lastIndex]] = [numbers[lastIndex], numbers[startIndex]];\n startIndex+=1;\n lastIndex-=1;\n }\n\n return numbers;\n}", "function reverseArray(arr) {\n return;\n}", "function reverse(arr){\n // we want to swap values for half as many times as there are values in the array\n for (var i = 0; i < arr.length/2; i++){\n // swap values\n var temp = myArr[i]; \n myArr[i] = myArr[arr.length-1-i]; \n myArr[arr.length-1-i] = temp; \n }\n}", "function reverseArray(array){\n let temp = 0;\n for(let i = 0; i <= (array.length/2); i++){\n temp = array[i]; // 0 = 1;\n array[i] = array[array.length - 1 - i]; // 1 = arrays length - i, which is 1 = 4\n array[array.length - 1 - i] = temp; // \n console.log(array);\n }\n return array;\n}", "function reverseArray(array) {\n // Your code here\n var revArr = [];\n for(var i = array.length - 1; i > -1; --i) {\n revArr.push(array[i]);\n }\n return revArr;\n}", "function rev_array()\n {\n \tvar rev_arr = create_array();\n\tvar swap_num = 0;\n\tvar j = rev_arr.length-1;\n\n\t \tfor (var i=0; i<rev_arr.length/2; i++)\n\t \t{\n\t \t\tswap_num = rev_arr[i];\n\t \t\trev_arr[i] = rev_arr[j];\n\t \t\trev_arr[j] = swap_num;\n\t \t\tj--;\n\t \t}\n\t \tconsole.log(\"This is the array after being reversed [\" + rev_arr + \"]\");\n }", "function reverseMinus(array){\n\n}", "function reverseArray(array){\n //Empty Array to store the new array\n var reversed = [];\n for (var i = array.length - 1; i >= 0; i--){\n reversed.push(array[i]);\n }\n return reversed;\n}", "function reverse(arr) {\n var newArr = [];\n\n for (i = 0; i < arr.length; i++) {\n newArr.unshift(arr[i]);\n }\n}", "function reverse(arr) {\n for(var i =0; i<arr.length/2;i++){\n temp = arr[i];\n arr[i]= arr[arr.length-1-i];\n arr[arr.length-1-i] = temp;\n }\n return arr;\n}", "function reverse(arr) {\n for (var i = 0; i < arr.length / 2; i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverse(arr){\n let temp\n for (let i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[i];\n arr[i] = arr[arr.length-i-1];\n arr[arr.length-i-1] = temp;\n }\n return arr\n}", "function Reverse (arr){\n let newarr = []\n for (let i = arr.length -1; i >= 0; i--){\n newarr.push(arr[i])\n } \n return newarr\n}", "function doReturnArray(array) {\n array[array.length] = 10;\n return array.reverse();\n}", "function myReverse(arr){\n let result = [];\n for(let i = arr.length -1; i >= 0;i--){\n result.push(arr[i]);\n }\n return result;\n}", "function reverse(arr) {\n let reversedArr;\n\n for (let i = arr.length - 1; i >= 0; i--) {\n reversedArr.push(arr[i])\n }\n\n return reversedArr;\n}", "function reverseArray(arr){\n var arrRev = []\n for(var i=0; i<arr.length;i++){\n arrRev.unshift(arr[i]);\n };\n console.log(arrRev);\n}", "function reverseArray(data){\n let revArr = [];\n for(i = 0; i < data.length; i++)\n revArr.unshift(data[i]);\n console.log(revArr);\n}", "function reverseInPlace(arr) {\n\tlet p1 = 0;\n\tlet p2 = arr.length - 1;\n\n\twhile (p1 < p2) {\n\t\t[arr[p1], arr[p2]] = [arr[p2], arr[p1]];\n\t\tp1++;\n\t\tp2--;\n\t}\n\treturn arr;\n}", "function returnReversed(arr) {\n for(var i = 0; i < arr.length / 2; i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverseArray(input_arr) {\n // Your code here\n var new_arr = [];\n for (var i = input_arr.length; i > 0; --i) {\n new_arr.push(input_arr[i - 1]);\n }\n return new_arr;\n}", "function reverseArrayInPlace(myArr) {\n\n var holdVal = myArr;\n \n console.log(\"The array is : \" + holdVal);\n \n for (i = holdVal.length; i >= 0; i--) {\n holdVal.push(myArr[i]);\n } \n \n console.log(\"The new array is : \" + holdVal);\n console.log(\"The lenght is : \" + holdVal.length);\n \n var halfArray = holdVal.length/2;\n \n holdVal.splice(0, halfArray);\n holdVal.shift();\n \n console.log(\"The spliced vr of the array is : \" + holdVal);\n}", "function reverseArray(arr){\n var temp = 0\n for(i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[arr.length-i-1];\n arr[arr.length-i-1] = arr[i];\n arr[i] = temp;\n }\n return arr;\n}", "function reverse (arr) {\n newArr = []\n for (var i = arr.length - 1; i >= 0; --i){\n newArr.push(arr[i])\n }\n return newArr\n}", "function reverseArray(arr){\n //your code here\n \n\n\nvar arr2 = [];\nfor(i=0; i<arr.length; i++) {\n\tvar element = arr[i];\n\tarr2.unshift(element);\n }\n return arr2;\n}", "function reverseArray(array) {\n // Your code here\n var counter = 0;\n var newarray = [];\n for(var i = array.length-1; i>=0; i--){\n newarray[counter] = array[i];\n counter++;\n }\n return newarray;\n}", "function reverse(list) {\n var t=0;\n j=list.length-1;\n for (let i = 0; i < list.length-1; i++) {\n t = list[j];\n list[j]=list[i];\n list[i]=t;\n j=j-1;\n }\n return list;\n}", "function reverseArray(a) {\n /** built in method */\n a.reverse();\n\n /** custom approach */\n const temp = [];\n for (let i = a.length-1; i >= 0; i--) {\n temp.push(a[i]);\n }\n console.log(temp);\n return temp;\n}", "function reverseArray(array) {\n // Your code here\n var arr1 = [];\n var x = array.length-1;\n\n for(var i = 0; i<array.length; i++){\n arr1[i] = array[x--];\n }\n return arr1;\n }", "function fixTheMeerkat(arr) {\n return arr.reverse()\n}", "function reverse(nums){\n let newArr = []\n nums.map(item => newArr.unshift(item))\n return newArr\n }", "function reverseOrder (array) {\n console.log ('Array before reverse order manipulation: ');\n console.log (array); \n for(let idx = 0; idx < array.length / 2; idx++){\n console.log (\"idx value: \" + idx);\n\n // for each pair, idx positions are generic at\n // array.length-1-idx and idx\n // idx=0 -> array.length-1 and 0\n // idx=1 -> array.length-1-1 and 1\n // idx=2 -> array.length-1-2 and 2\n // swap by holding on value as temp and then shifting\n\n let temp = array[(array.length-1)-idx];\n array[(array.length-1) - idx] = array[idx];\n array[idx] = temp;\n console.log (\"temp:\" + temp);\n }\n console.log ('Array after reverse order manipulation: ');\n // console.log(array);\n return array;\n}", "function reverseArray(arr){\n for(let i = 0; i < Math.floor(arr.length/2); i++){\n let temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n }\n return arr\n}", "function inPlaceReverse(arr) {\n let i = 0;\n while (i < arr.length - 1) {\n arr.splice(i, 0, arr.pop());\n i++;\n }\n return arr;\n}", "function reverseArray(array) {\n // Your code here\n let newArr = [];\n for (let i = 0; i < array.length; i++) {\n newArr.push(array[array.length - i - 1]);\n }\n return newArr;\n}", "function reverse(a){\n let newA = [];\n\n for(let i = a.length-1; i >= 0 ; i--){\n newA.push(a[i]);\n }\n\n return newA;\n}", "function reverse(array) {\n\t var copy = array.slice();\n\t copy.reverse();\n\t return copy;\n\t }", "function reverseArray(arr){\n var newArr = [];\n for(var i=arr.length-1; i>=0; i--){\n newArr += arr;\n }\n return newArr;\n }", "reverseArray(arr) {\n let reversed = [];\n\n for(let i=arr.length-1; i >= 0; i--) {\n reversed.push(arr[i]);\n }\n\n return reversed;\n }", "function reverseArr(arr) {\n let reversed = [];\n\n function punchInLast(arr) {\n if (arr.length < 1) return;\n\n reversed.push(arr.pop());\n punchInLast(arr);\n }\n\n punchInLast(arr);\n\n return reversed;\n}", "function recursiveReverse(arr) {\n\tvar reversed = []\n\n\t// for(var i = 1; i <= arr.length; i++) {\n\t// \treversed.push(arr[arr.length - i])\n\t// }\n\n\tfunction recursive(arr) {\n\t\tif(arr.length === 0) {\n\t\t\treturn reversed\n\t\t} else {\n\t\t\treversed.push(arr.pop())\n\t\t\treturn recursive(arr)\n\t\t}\n\t}\n\n\treturn recursive(arr)\n}", "function reverseMutate() {\n let newOnes = ones.slice().reverse();\n console.log(ones);\n console.log(newOnes);\n }", "function recursiveReverse(arr) {\n if (arr.length === 0 ) return arr;\n\n var first = arr.shift();\n\n recursiveReverse(arr);\n\n arr.push(first);\n console.log(arr)\n\n return arr;\n}", "function reverseArray(arr) {\n var r = arr.length-1;\n for (var x = 0; x < arr.length; x++){\n if (x < r) {\n temp = arr[x];\n arr[x] = arr[r];\n arr[r] = temp;\n //console.log(arr, x, r);\n r--;\n }\n }\n //console.log(arr)\n return arr;\n}", "function reverseArray(array){\n\tvar newArray = [];\n\t// console.log(array);\n\tfor(var maxIndex = array.length-1; maxIndex > -1; maxIndex--){\n\t\tnewArray.push(array[maxIndex]);\n\t}\n\tconsole.log(newArray);\n\tconsole.log(\"--------------------------------------\");\n}", "function reverseList(arr) {\n var length = Math.ceil(arr.length / 2);\n var temp;\n for (var i = 0; i < length; i++) {\n temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverseArr(array) {\n\tvar newArr = [];\n for(var i = 0; i < array.length; i++) {\n \tnewArr.unshift(array[i]);\n console.log(newArr);\n }\n return newArr;\n}", "function func12(inputArray){\n var temp=inputArray[0];\n inputArray[0]=inputArray[inputArray.length-1];\n inputArray[inputArray.length-1]=temp;\n return inputArray;\n}", "function reverserArr(arr){\n var newArr = []\n for(var i = arr.length-1; i >=0 ;i--){\n newArr.push(arr[i])\n }\n return newArr\n}", "function reverseArrayWithNoReverse(arr) {\n let newArr = [];\n for (const i in arr) {\n newArr.unshift(arr[i]);\n }\n return console.log(newArr);\n}", "function customReverse(originalArray) {\n let leftIndex = 0;\n let rightIndex = originalArray.length - 1;\n\n while (leftIndex < rightIndex) {\n // Swap the elements with temp variable\n let temp = originalArray[leftIndex];\n originalArray[leftIndex] = originalArray[rightIndex];\n originalArray[rightIndex] = temp;\n\n // Move indices to the middle\n leftIndex++;\n rightIndex--;\n }\n}", "function reverseArray(arr) {\n for (var i = 0; i <= (arr.length / 2); i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverse(array){\n\tresult =[];\n\tiLen = array.length-1;\n\tarray.forEach(function(item,i){\n\t\tresult[i]=array[iLen-i];\n\t});\n\treturn result;\n}", "function reverseArray(arr) {\n for (let i = 0; i < Math.floor(arr.length / 2); i++) {\n // arr[i] | arr[arr.length-1-i]\n arr[arr.length - 1 - i] = arr[i] + arr[arr.length - 1 - i];\n arr[i] = arr[arr.length - 1 - i] - arr[i];\n arr[arr.length - 1 - i] = arr[arr.length - 1 - i] - arr[i];\n }\n return arr;\n }", "function reverseArray(input){\n\tvar output = [];\n\tfor (var i=0; i<input.length; i++){\n\t\toutput.unshift(input[i]);\n\t}\n\treturn output;\n}", "function reverseArrayPlain(arr) {\n\n var swap;\n\n window.performance.mark('pStart');\n\n for (var i = 0; i < arr.length / 2; i++) {\n swap = arr[i];\n arr[i] = arr[arr.length - i];\n arr[arr.length - i] = swap;\n }\n\n window.performance.mark('pEnd');\n console.log(\"reverseArrayPlain done!\");\n\n }" ]
[ "0.71709675", "0.6948195", "0.6929113", "0.692301", "0.6883915", "0.6878862", "0.6856885", "0.684621", "0.6778876", "0.677617", "0.675403", "0.67477715", "0.67211366", "0.6718343", "0.671831", "0.6702483", "0.66729164", "0.66414195", "0.6617382", "0.66086364", "0.65959436", "0.6592468", "0.65754354", "0.65681195", "0.6556564", "0.6536127", "0.6532464", "0.6521816", "0.65184766", "0.6517174", "0.6516704", "0.65144587", "0.6507154", "0.65015924", "0.6482792", "0.64815986", "0.6477134", "0.6462776", "0.64545566", "0.645213", "0.6450096", "0.6445129", "0.6442311", "0.644215", "0.6427551", "0.64271307", "0.64240843", "0.6421815", "0.6421615", "0.6421433", "0.64165825", "0.64054286", "0.6403641", "0.6398934", "0.6388808", "0.6387788", "0.6385626", "0.6381456", "0.63814366", "0.6356495", "0.6353969", "0.6350846", "0.6349675", "0.6322435", "0.6313053", "0.6305248", "0.6301083", "0.62967104", "0.62958133", "0.629458", "0.6287558", "0.62720525", "0.6270946", "0.6264932", "0.6263923", "0.62633026", "0.6257947", "0.6257125", "0.6257", "0.62486416", "0.62453485", "0.62364537", "0.6234726", "0.6230988", "0.6230656", "0.6211901", "0.6181527", "0.6178698", "0.61779404", "0.61656153", "0.6164101", "0.6159254", "0.61538935", "0.614812", "0.61354405", "0.613474", "0.61256206", "0.6105609", "0.60940284", "0.6082289" ]
0.6361204
59
console.log(reverse([3,1,6,4,2])); Challenge 11 Outlook: Negative Given an array, create and return a new one containing all the values of the original array, but make them all negative (not simply multiplied by 1). Given [1,3,5], return [1,3,5].
function negative(arr) { var newArr = []; for(var i = 0; i < arr.length; i++) { if(arr[i] > 0) { newArr[i] = arr[i] - arr[i] * 2; }else{ newArr[i] = arr[i]; } } return newArr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function reverseMinus(array){\n\n}", "function invert(array) {\n var newArr = [];\n for(var i = 0; i < array.length; i++){\n newArr.push(-array[i]);\n }\n return newArr;\n }", "function invert(array) {\n\t//return array.map((element) => (element === 0 ? element : -element));\n\treturn array.map((element) => -element);\n}", "function invert(array) {\n return array.map(num => num * -1)\n}", "function outlookNegative(array){\n let newArray = [];\n for(let i = 0; i < array.length; i++){\n // if(array[i] > 0){\n // newArray.push(array[i] * -1);\n // } else {\n // newArray.push(array[i]);\n // }\n newArray.push(array[i] > 0 ? -array[i] : array[i]);\n }\n return newArray;\n}", "function subtractReverse(array) {\n //Write your code here\n}", "function mapToNegativize(sourceArray) {\n\n // return sourceArray.map(el =>\n // el * -1\n // )\n let newArray=[]\n sourceArray.forEach (el =>\n\n newArray.push(el * -1)\n )\nreturn newArray\n}", "function negative(arr){\n let newArr=[]\n for (let i = 0; i < arr.length; i++){\n if (arr[i] > 0){\n newArr.push(arr[i]*-1)\n }\n else {\n newArr.push(arr[i])\n }\n }\n return newArr\n}", "function negativeArray(arr){\n var newarr = [];\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n arr[i] = arr[i] - arr[i] * 2;\n newarr.push(arr[i]);\n }\n else{\n arrnew.push(arr[i]);\n }\n }\n return newarr;\n}", "function outlookNegative(arr){\n var newArr = []\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n newArr.push(arr[i] * -1)\n }else{\n newArr.push(arr[i])\n }\n }\n return newArr\n}", "function reverse(theArray){\nconst newArray = [];\nfor (let i= theArray.length -1; i>= 0; i--){\nnewArray.push(theArray [i]);\n}\nreturn newArray;\n}", "function invert_copy(array) {\r\n let arr = []\r\n for (let i = array.length - 1; i >= 0; i--) {\r\n arr.push(array[i]);\r\n }\r\n return arr;\r\n}", "function outlookNetative(array) {\n var allNegative = [];\n\n for (var i in array) {\n if (array[i] > 0) {\n allNegative[i] = array[i] * -1;\n } else {\n allNegative[i] = array[i];\n }\n }\n return allNegative;\n}", "function makeNegative(numbers) {\n // numbers.map(function(num, index, array){ });\n // don't need index or array. \n // numbers.map(function(num){ });\n //map will return a new array. That's the end goal. So we don't need the variable \n return numbers.map(function(num){\n // if(num > 0){\n // num *= -1;\n // // same as num = num * -1;\n // }\n // return num; \n // or we can\n return Math.abs(num) * -1; \n });\n\n}", "function outlookNegative(arr) {\n\tvar newArr = [];\n\tnum = 0;\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (arr[num] > 0) {\n\t\t\tnewArr.push(arr[num] * -1);\n\t\t} \n\t\telse {\n\t\t\tnewArr.push(arr[num]);\n\t\t}\n\t}\n\n\tconsole.log(newArr);\n\treturn newArr;\n}", "function myReverse(arr){\n let result = [];\n for(let i = arr.length -1; i >= 0;i--){\n result.push(arr[i]);\n }\n return result;\n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length / 2); i++) {\n // swaps the number at the index with it's mirror, until you get to the middle number\n let old = array[i];\n array[i] = array[array.length - 1 - i]; // Where the index is gets assigned it's mirror\n // console.log(array);\n array[array.length - 1 - i] = old; // it's mirror gets assigned the value you saved from the original index\n // console.log(array);\n }\n return array;\n}", "function mapToNegativize(arr){\n return arr.map(x => x * -1)\n\n}", "function reverseFunc(array) {\n let reversedNumbers = [];\n\n for (let index = array.length - 1; index >= 0; index--) {\n let currentNumber = array[index];\n reversedNumbers.push(currentNumber);\n }\n\n return reversedNumbers;\n // use for loop to repeat process until theres no more numbers inside array\n // create a variable that represents the new reverse-array\n // .pop off the last number from the original array (or just use array[index] instead of array.pop())\n // then .push() that popped off number into that new reverse-array\n // return the new array\n}", "function arrNegative(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] > 0) {\n var a = 2 * arr[i];\n arr[i] -= a;\n }\n }\n return arr;\n}", "function invert(arr) {\n // container\n let invertedArr = [];\n for (let i = 0; i < arr.length; i++) {\n invertedArr.push(-arr[i]);\n }\n return invertedArr;\n }", "function removeNegatives (array) {\n if(!(array instanceof Array)) {return 'Please pass an array.'};\n let copyTo;\n let negativeCount = 0;\n for (var i = 0; i < array.length; i++) {\n if (array[i] < 0) {\n negativeCount++;\n copyTo = i;\n break;\n };\n };\n if (negativeCount > 0) {\n for (let j = i + 1; j < array.length; j++) {\n if (array[j] < 0) {\n negativeCount++;\n } else {\n array[copyTo] = array[j];\n copyTo++;\n };\n };\n array.length -= negativeCount;\n };\n return array;\n}", "function reverseInPlace(array) {\n let len = array.length;\n for (let i = len - 1; i >= 0; i -= 1) {\n array.push(array[i]);\n }\n while (len > 0) {\n array.shift();\n len -= 1;\n }\n return array;\n}", "function reverse(arr) {\n var newarr = [];\n for (i = arr.length-1; i > -1; i--) {\n newarr.push(arr[i]);\n }\n arr = newarr;\n return arr;\n}", "function fixTheMeerkat(arr) {\n let givenArr = arr;\n return givenArr.reverse()\n}", "function OutNeg(arr){\n var newarr = [];\n var temp = 0;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n temp = -Math.abs(arr[i]);\n newarr.push(temp);\n } else newarr.push(arr[i])\n }\n console.log(newarr);\n}", "function reverse(arr) {\n return arr.reverse();\n}", "function reverseArrayInPlace(array) {\n for (i = 0; i <= Math.floor(array.length / 2); i++) {\n a = array[i];\n b = array[array.length - 1 - i];\n array[i] = b;\n array[array.length - 1 - i] = a;\n }\n return array;\n}", "function inverseArray(array) {\n oldArray = array;\n newArray = [];\n for (i = array.length - 1; i >= 0; i--) {\n newArray.push(oldArray[i]);\n }\n return newArray;\n}", "function negative(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] *= -1;\n }\n }\n return arr\n}", "function reverse(array) {\n var output = [];\n\n for (let i = array.length - 1; i >= 0; i--) {\n output.push(array[i]);\n }\n\n return output;\n}", "function reverse(array){\n\tresult =[];\n\tiLen = array.length-1;\n\tarray.forEach(function(item,i){\n\t\tresult[i]=array[iLen-i];\n\t});\n\treturn result;\n}", "function reverseArray(array) {\n // Your code here\n var revArr = [];\n for(var i = array.length - 1; i > -1; --i) {\n revArr.push(array[i]);\n }\n return revArr;\n}", "function Reverse (arr){\n let newarr = []\n for (let i = arr.length -1; i >= 0; i--){\n newarr.push(arr[i])\n } \n return newarr\n}", "function reverse(arr){\n //code\n}", "function reverseArray (array) {\n array.reverse();\n}", "function reverseArray(array){\n\tvar newArray = [];\n\t// console.log(array);\n\tfor(var maxIndex = array.length-1; maxIndex > -1; maxIndex--){\n\t\tnewArray.push(array[maxIndex]);\n\t}\n\tconsole.log(newArray);\n\tconsole.log(\"--------------------------------------\");\n}", "function fixTheMeerkat(arr) {\n return arr.reverse()\n}", "function reverseArrayWithNoReverse(arr) {\n let newArr = [];\n for (const i in arr) {\n newArr.unshift(arr[i]);\n }\n return console.log(newArr);\n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length/2); i++) {\n let oldIndexValue = array[i];\n array[i] = array[(array.length - 1) - i];\n array[(array.length - 1) - i] = oldIndexValue;\n } \n return array;\n}", "function makeNegative(numbers) {\n var negs = []; \n for (var i = 0; i < numbers.length; i++) {\n var neg = Math.abs(numbers[i]) * -1; \n negs.push(neg);\n }\n return negs; \n}", "function reverseArray(array){\n let temp = 0;\n for(let i = 0; i <= (array.length/2); i++){\n temp = array[i]; // 0 = 1;\n array[i] = array[array.length - 1 - i]; // 1 = arrays length - i, which is 1 = 4\n array[array.length - 1 - i] = temp; // \n console.log(array);\n }\n return array;\n}", "function three(arr){\n return arr.reverse(); \n}", "function reverseArrayInPlace(array) {\n for (let i = 0; i < Math.floor(array.length / 2); i++) {\n let old = array[i];\n array[i] = array[array.length - 1 - i];\n array[array.length - 1 - i] = old;\n }\n return array;\n}", "function reverseArray(array){\n //Empty Array to store the new array\n var reversed = [];\n for (var i = array.length - 1; i >= 0; i--){\n reversed.push(array[i]);\n }\n return reversed;\n}", "function reverser(arr){\n var x = 0;\n for(var e=0; e<arr.length/2; e++){\n x = arr[e];\n arr[e] = arr[arr.length-1-e];\n arr[arr.length-1-e] = x;\n }\n return arr;\n}", "function reverseArrayInPlace(arr) {\n const newArr = [];\n\n for (let i = 0; i < arr.length; i++) {\n newArr.unshift(arr[i]);\n }\n return console.log(newArr);\n}", "function reverse(arr) {\n return arr.reverse()\n }", "function arraynegativo(x){\n for(var i=0; i<x.length ; i++){\n if(x[i] >0 ){\n x[i] = x[i] * -1;\n }\n }\n return x\n}", "function returnReversed(arr) {\n for(var i = 0; i < arr.length / 2; i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverseArray(arr) {\n return;\n}", "function reverse(a){\n let newA = [];\n\n for(let i = a.length-1; i >= 0 ; i--){\n newA.push(a[i]);\n }\n\n return newA;\n}", "reverse(arr) {\n return arr.reverse();\n }", "function reverse (arr) {\n newArr = []\n for (var i = arr.length - 1; i >= 0; --i){\n newArr.push(arr[i])\n }\n return newArr\n}", "function reverseArray(array) {\n return array.reverse();\n}", "function reverse(arr){\n let temp\n for (let i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[i];\n arr[i] = arr[arr.length-i-1];\n arr[arr.length-i-1] = temp;\n }\n return arr\n}", "function negate(arrayEntered) {\n let result = [];\n for (let i = 0; i < arrayEntered.length; i++) {\n result.push(arrayEntered[i] * -1);\n }\n return result;\n}", "function reverse(arr){ //arr = [\"a\",\"b\",\"c\",\"d\",\"e\"];\n var temp = []; //temp stands for temparary\n for(var i=arr.length-1; i > 0;i--){ //the loop that loops through half of the array.\n temp[i] = arr[i];\n }\n console.log(arr); //logs out the newly edited array.\n}", "function reverse(array) {\n\t var copy = array.slice();\n\t copy.reverse();\n\t return copy;\n\t }", "function reverseArrayInPlace (arr) {\n\tvar initLen = Math.floor(arr.length / 2),\n\t\tremoveIndex,\n valStore;\n print(\"Number of Iterations: \" + initLen);\n\tfor (var i = 0; i < initLen; i += 1) {\n valStore = arr[i]; // 1\n\t\tarr[i] = arr[arr.length - 1 - i]; // 5 to front\n arr[arr.length - 1 - i] = valStore;\n print(\"current array length: \" + arr.length);\n print(\"Iteration \" + i);\n print(\"Array: \" + arr);\n\t}\n\treturn arr;\n}", "function reverse(arr) {\n for (var i = 0; i < arr.length / 2; i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverseArray(array) {\n // Your code here\n let newArr = [];\n for (let i = 0; i < array.length; i++) {\n newArr.push(array[array.length - i - 1]);\n }\n return newArr;\n}", "function reverseArrayInPlace2(arr){\n for(var i = 0; i < arr.length / 2; i++){\n var tempVar = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = tempVar;\n }\n return arr;\n}", "function reverse(nums){\n let newArr = []\n nums.map(item => newArr.unshift(item))\n return newArr\n }", "function reverse(arr) {\n for(var i = 0; i < arr.length/2; i++) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n return arr;\n}", "function reverse(arr) {\n for(var i =0; i<arr.length/2;i++){\n temp = arr[i];\n arr[i]= arr[arr.length-1-i];\n arr[arr.length-1-i] = temp;\n }\n return arr;\n}", "function reverseArray(array){\n let array1 = []\n for (let i=array.length - 1;i>=0;i--){\n array1.push(array[i])\n }\n return array1\n}", "function reverseArray(arr) {\n for (let i = 0; i < Math.floor(arr.length / 2); i++) {\n // arr[i] | arr[arr.length-1-i]\n arr[arr.length - 1 - i] = arr[i] + arr[arr.length - 1 - i];\n arr[i] = arr[arr.length - 1 - i] - arr[i];\n arr[arr.length - 1 - i] = arr[arr.length - 1 - i] - arr[i];\n }\n return arr;\n }", "reverseArray(arr) {\n let reversed = [];\n\n for(let i=arr.length-1; i >= 0; i--) {\n reversed.push(arr[i]);\n }\n\n return reversed;\n }", "function reverseArrayInPlace(newArray) {\n\n\tfor(var i = 0; i < newArray.length; i++){\n\t\tnewArray[i] = newArray.length-i;\n\t}\n\n\t return newArray;\n}", "function doReturnArray(array) {\n array[array.length] = 10;\n return array.reverse();\n}", "function reverse(arr)\n{\n var temp;\n var end=arr.length-1\n for(var i=0; i<arr.length/2; i++)\n {\n \n temp=arr[i];\n arr[i]=arr[end-i];\n arr[end-i]=temp;\n }\n return arr\n}", "function inverseMirror (array) {\n var inverseMirrorArray = [];\n for (var i = array.length - 1; i >=0; i--) {\n inverseMirrorArray.push(array[i]);\n }\n return inverseMirrorArray;\n }", "function negatives(array) {\n for (let i = 0; i < array.length; i++) {\n if(array[i] < 0) { \n array[i] = 0;\n }\n }\n return array;\n}", "function negativos(array) {\n var newArray = [];\n for (var i = 0; i < array.length; i++) { \n if(array[i] > 0){\n newArray.push(array[i]*-1);\n }\n else{\n newArray.push(array[i]);\n }\n }\n\n return newArray;\n}", "function reverseInPlace(arr) {\n var temp\n for (var i = 0; i < arr.length / 2; i++) { //add math.floor(arr.length/2) IF you have an odd numbered array. \n temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n console.log(\"Loop no: \" + i + \":\" + arr) //This is only to show us what is happening and how it is happening.\n }\n return arr\n}", "function reverse(arr) {\n var newArr = [];\n\n for (i = 0; i < arr.length; i++) {\n newArr.unshift(arr[i]);\n }\n}", "function reverseArray(array) {\n // Your code here\n var arr1 = [];\n var x = array.length-1;\n\n for(var i = 0; i<array.length; i++){\n arr1[i] = array[x--];\n }\n return arr1;\n }", "function reverseArray2(array) {\n let output = [];\n\n for (let i = array.length - 1; i >= 0; i--) {\n output.push(array[i]);\n }\n return output;\n}", "function reverseArray(input_arr) {\n // Your code here\n var new_arr = [];\n for (var i = input_arr.length; i > 0; --i) {\n new_arr.push(input_arr[i - 1]);\n }\n return new_arr;\n}", "function reverseArray(array) {\n // Your code here\n var counter = 0;\n var newarray = [];\n for(var i = array.length-1; i>=0; i--){\n newarray[counter] = array[i];\n counter++;\n }\n return newarray;\n}", "function reverse(arr){\n y = arr.length-1;\n for (x = 0; x < arr.length/2; x++){\n var swap = arr[x];\n arr[x] = arr[y];\n arr[y] = swap;\n y = y - 1;\n }\n return arr;\n}", "function inverti_array(a){\n var array = new Array();\n //copio l'array in modo da non modificare i valori iniziali\n for(var i=0;i<a.length;i++){\n array[i] = copia_array(a[i])\n }\n for(var i=0;i<array.length/2;i++){\n var a_supp = array[i];\n array[i] = array[array.length-1-i];\n array[array.length-1-i] = a_supp;\n }\n return array;\n }", "function reverseArr(arr) {\n // code here\n}", "function reverseArray(arr){\n var temp = 0\n for(i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[arr.length-i-1];\n arr[arr.length-i-1] = arr[i];\n arr[i] = temp;\n }\n return arr;\n}", "function reverse(arr) {\n let reversedArr;\n\n for (let i = arr.length - 1; i >= 0; i--) {\n reversedArr.push(arr[i])\n }\n\n return reversedArr;\n}", "function reverseArray(arr){\n for(let i = 0; i < Math.floor(arr.length/2); i++){\n let temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n }\n return arr\n}", "function reverse(arr) {\n let tempArr = [];\n\n for (i = 0; i < arr.length; i++) { // arr 길이(요수의 수)만큼 반복\n tempArr[i] = arr[arr.length - i - 1];\n // tempArr[0] = arr[3 - 0 - 1] = arr[2]\n // tempArr[1] = arr[3 - 1 - 1] = arr[1]\n // tempArr[2] = arr[3 - 2 - 1] = arr[0]\n }\n\n return tempArr // arr 배열의 순서와 반대가 되는 새로운 배열\n}", "function reverseArr(array) {\n\tvar newArr = [];\n for(var i = 0; i < array.length; i++) {\n \tnewArr.unshift(array[i]);\n console.log(newArr);\n }\n return newArr;\n}", "function reverseArrayInPlace(array){\n\n let end = array.length - 1;\n let start = 0;\n while(end > start){\n \n let tmp = array[start]\n\n array[start] = array[end]\n array[end] = tmp\n\n end--;\n start++;\n }\n return array;\n}", "function neg(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n return arr;\n}", "function reverseArray(array){\n let newArray=[];\n for(let i=array.lenght -1;i>=0;i--){\n newArray.push(array[i])\n }\n return newArray\n}", "function reverse(list) {\n var t=0;\n j=list.length-1;\n for (let i = 0; i < list.length-1; i++) {\n t = list[j];\n list[j]=list[i];\n list[i]=t;\n j=j-1;\n }\n return list;\n}", "function reverse(arr){\n // we want to swap values for half as many times as there are values in the array\n for (var i = 0; i < arr.length/2; i++){\n // swap values\n var temp = myArr[i]; \n myArr[i] = myArr[arr.length-1-i]; \n myArr[arr.length-1-i] = temp; \n }\n}", "function swapArr(arr){\nreturn arr.reverse();\n}", "function flipSignForAll1D(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] *= -1;\n }\n }", "function reverseOrder (array) {\n console.log ('Array before reverse order manipulation: ');\n console.log (array); \n for(let idx = 0; idx < array.length / 2; idx++){\n console.log (\"idx value: \" + idx);\n\n // for each pair, idx positions are generic at\n // array.length-1-idx and idx\n // idx=0 -> array.length-1 and 0\n // idx=1 -> array.length-1-1 and 1\n // idx=2 -> array.length-1-2 and 2\n // swap by holding on value as temp and then shifting\n\n let temp = array[(array.length-1)-idx];\n array[(array.length-1) - idx] = array[idx];\n array[idx] = temp;\n console.log (\"temp:\" + temp);\n }\n console.log ('Array after reverse order manipulation: ');\n // console.log(array);\n return array;\n}", "function reverseArray(arr) {\n arr.reverse();\n}", "function reverseArrayInPlace(arr) {\n for (var i = 0; i < Math.floor(arr.length / 2); i++) {\n var temp = arr[i];\n arr[i] = arr[((arr.length - 1) - i)];\n arr[((arr.length - 1) - i)] = temp;\n }\n}", "function absolute(numbers) {\n let numbersClone = numbers.map(function(number) {\n return number < 0 ? (number *= -1) : number;\n });\n return numbersClone;\n}" ]
[ "0.78636616", "0.7821786", "0.7661021", "0.76451856", "0.7635298", "0.75784993", "0.7437917", "0.7426829", "0.74070793", "0.7403391", "0.7395724", "0.7367335", "0.73426056", "0.7337558", "0.7262756", "0.7257129", "0.7243493", "0.72382474", "0.7237839", "0.72297835", "0.72121656", "0.7167177", "0.71459544", "0.7119728", "0.7096358", "0.708971", "0.7087957", "0.7087361", "0.708368", "0.7058009", "0.705414", "0.7050375", "0.7044422", "0.7043251", "0.70346034", "0.7032155", "0.7029484", "0.7019582", "0.69933987", "0.69909894", "0.69846165", "0.6964865", "0.69611627", "0.6958688", "0.6958219", "0.6954453", "0.6953891", "0.69498676", "0.6947361", "0.69454306", "0.69417197", "0.6937699", "0.69358987", "0.6935361", "0.6935149", "0.6912135", "0.69069856", "0.6904053", "0.6898037", "0.6884473", "0.68826365", "0.68760675", "0.68750066", "0.68746287", "0.68653125", "0.68634224", "0.6863342", "0.68612516", "0.68506014", "0.6840623", "0.683979", "0.683574", "0.68343073", "0.68316764", "0.683068", "0.68275195", "0.68178636", "0.68031704", "0.6801777", "0.67989457", "0.67965066", "0.6793757", "0.679345", "0.67817265", "0.67703855", "0.6767709", "0.6765091", "0.6761936", "0.67516696", "0.6749605", "0.6740075", "0.67397654", "0.6718907", "0.671601", "0.6704792", "0.6699671", "0.6694445", "0.66821307", "0.6672262", "0.66711867" ]
0.7371627
11
console.log(negative([1,3,5])); Challenge 12 Always Hungry Create a function that accepts an array, and prints "yummy" each time one of the values is equal to "food". If no array values are "food", then print "I'm hungry" once.
function alwaysHungry(arr) { var food = false; for(var i = 0; i < arr.length; i++) { if(arr[i] === "food") { console.log("yummy"); food = true; } } if(food === false){ console.log("I'm hungry") } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function alwaysHungry(arr){\r\n for(var i=0; i<arr.length; i++){\r\n if(arr[i] == \"food\"){\r\n console.log(\"yummy\");\r\n } else if(arr[i] !== \"food\"){\r\n console.log(\"hungry\")\r\n }\r\n }\r\n }", "function hungry(arr){\n var food = false;\n for(e in arr){\n if(arr[e] == \"food\"){\n console.log(\"yummy\");\n food = true;\n }\n }\n if(food == false){\n console.log(\"I'm hungry\");\n }\n // return undefined;\n}", "function hungry(arr){\n yummy = []\n for (var i = 0; i< arr.length; i++){\n if (arr[i]==\"food\"){\n yummy.push(\"yummy\")\n }\n }\n if (yummy.length == 0){\n console.log(\"I'm Hungry\")\n }\n else {\n console.log(yummy)\n }\n}", "function alwaysHungry(array){\n let hungry = true;\n let newArray;\n // iterate through the array values\n for(let i = 0; i < array.length; i++){\n // for each element equal to \"food\", change to yummy\n if (array[i] === 'food'){\n // foodMsg = 'food';\n console.log('yummy');\n array[i] = 'yummy';\n hungry = false;\n }\n }\n if(hungry){ // if hungry condition is true\n console.log(\"I\\'m hungry\");\n }\n // if no array elements are \"food\", print \"I'm hungry\" only once\n // return hungry ? \"I'm hungry\" : foodMsg;\n return array;\n}", "function alwaysHungry(arr){\n var hungry = true\n for(var i = 0; i < arr.length; i++){\n if(arr[i] === \"food\"){\n console.log(\"Yummy\")\n hungry = false\n }\n }\n if(hungry === true){\n console.log(\"I'm Hungry\")\n }\n return 0\n}", "function alwaysHungry(array) {\n var response = \"I'm hungry\";\n\n for (var i in array) {\n if (array[i] === \"food\") {\n console.log(\"yummy\")\n response = \"\";\n }\n }\n\n return response;\n}", "function alwaysHungry(arr) {\n\tvar counter = 0;\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (arr[num] == \"food\") {\n\t\t\tcounter++;\n\t\t\tconsole.log(\"yummy\");\n\t\t}\n\t}\n\n\tif (arr[num] == arr[arr.length] && counter == 0) {\n\t\t\tconsole.log(\"I'm hungry\");\n\t}\n}", "function alwayshungry(arr){\n var count = 0;\n for(var i=0;i<arr.length;i++){\n if(arr[i] == \"food\"){\n console.log(\"yummy\");\n count += 1;\n }\n }\n if(count == 0){\n console.log(\"I'm hungry\");\n }\n}", "function alwaysHungry(arr){\n\n var count=0;\n for (var i=0;i<arr.length;i++){\n if(arr[i]===\"food\"){\n console.log(\"yummy\");\n \n count+=1;\n \n \n }\n }\n if(count!=1)\n console.log(\"I'm hungry\");\n \n }", "function alwaysHungry(arr){\n count = 0;\n for(i in arr){\n if(arr[i] === \"food\"){\n console.log(\"yummy\");\n count ++;\n }\n }\n if(count === 0){\n console.log(\"I'm hungry\");\n }\n}", "function imhungry(arr) {\n var count = 0; //can do without this... you just need to see if it exists within the arr\n for(var i = 0; i < arr.length; i++) {\n if (arr[i] === \"food\") {\n console.log(\"yummy\");\n count = count + 1 //var full = true... and then \"if !true\" log I'm hungry.\n }\n }\n if (count === 0) {\n console.log(\"I'm hungry\")\n }\n}", "function alwaysHungry(arr) {\n if (arr.includes(\"food\") == false) {\n console.log(\"I'm hungry!\");\n return\n } else {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] == \"food\") {\n console.log(\"yummy\")\n }\n }\n }\n}", "function alwaysHungry(arr) {\n\tvar i = 0;\n\tvar numFood = 0;\n\twhile(i < arr.length) {\n\t\tif(arr[i] === \"food\") {\n\t\t\tconsole.log(\"yummy\");\n\t\t\tnumFood++;\n\t\t\ti++;\n\t\t} else {\n\t\t\ti++;\n\t\t}\n\t}\n\tif(numFood === 0) {\n\t\tconsole.log(\"I'm hungry\");\n\t}\n}", "function zero_negativity(arr){\n if(Array.isArray(arr)){\n for(let i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n console.log(\"Your input is an array, but there is a negative with index \" + i + \", and it has a value of \" + arr[i] + \".\");\n return false;\n }\n }\n console.log(\"Your input is an array and no negatives were found.\");\n return true;\n }\n else{\n console.log(\"Your arguement is not an array. Please only use an array.\");\n };\n return false;\n}", "function alwaysHungry2(arr) {\n\tvar i = 0;\n\tvar numFood = 0;\n\twhile(i < arr.length) {\n\t\t// console.log(\"food: \" + numFood + \" i: \" + i); //console.log t-chart for keeping track\n\t\tif(arr[i] === \"food\") {\n\t\t\tnumFood++;\n\t\t\tif(numFood % 3 === 0) {\n\t\t\t\tconsole.log(\"in my tummy\");\n\t\t\t} else {\n\t\t\t\tconsole.log(\"yummy\");\n\t\t\t}\n\t\t}\n\t\ti++;\n\t}\n\tif(numFood === 0) {\n\t\tconsole.log(\"I'm hungry\");\n\t}\n}", "function Hungry1(arr){\n var checks = false;\n for(var i = 0; i < arr.length; i++){\n if(arr[i] == \"food\"){\n console.log(\"yummy!\");\n status = true;\n }\n \n }\n \n if(checks != true){\n console.log(\"I'm Hungry\");\n}\n}", "function getPositives2(arr){\n arr.filter(isPositive).forEach(function(entry) {console.log(entry);});\n}", "function yahtzee() {\n for (var i = 0; i < diceArray.length; i++) {\n if (diceArray[i] !== diceArray[0]) {\n return 0;\n }\n }\n return 50;\n}", "function findTheCheese (foods) {\n\n for (var i = 0; i < foods.length; i++) {\n\n switch (foods[i]) {\n case \"cheddar\":\n return \"cheddar\"\n break;\n case \"gouda\":\n return \"gouda\"\n break;\n case \"camembert\":\n return \"camembert\"\n break;\n }\n }\n return \"no cheese!\"\n}", "function hungry(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] = \"food\") {\n arr[i] = \"yummy\";\n }\n else (arr[i] = \"I'm hungry\");\n }\n}", "function declineEverything(arr) {\n const politelyDecline = (veg) => {\n console.log('No ' + veg + ' please. I will have pizza with extra cheese.');\n}\n\narr.forEach(element => {\n return politelyDecline(element);\n})\n}", "function greetAliens(arr) {\n for(let i=0; i<arr.length; i++) {\n console.log(`Oh powerful ${arr[i]} we humans offer our unconditional surrender!`)\n }\n}", "function ideas(array_ideas) {\n \n let good = 0\n for (let i = 0; i < array_ideas.length; i++) {\n if (array_ideas[i] == 'good' && ++good > 2) {\n return 'I smell a series'\n } \n }\n return good ? 'Publis!' : 'Fail!'\n}", "function findTheCheese (foods) {\n for (var i=0; i<foods.length; i++){\n foods.shift();\n if (foods[i] === \"gouda\"){\n return `gouda`;\n }\n else if (foods[i] === `cheddar`){\n return 'cheddar';\n }\n else {\n return `no cheese!`;\n }\n }\n}", "function ifArray(input_array) {\n for (let i=0; i<input_array.length; i++) {\n allFood(input_array[i])\n }\n}", "function checkForFarkle() {\n var diceNum = [0, 0, 0, 0, 0, 0];\n for (i = 0; i < 6; i++) {\n if (!diceArr[i].set) {\n diceNum[diceArr[i].value - 1]++;\n }\n }\n for (i = 0; i < 6; i++) {\n if (i === 0 || i == 4) {\n if (diceNum[i] > 0) {\n return 'safe';\n }\n } else {\n if (diceNum[i] == 3) {\n return 'safe';\n }\n }\n }\n return 'Farkle! Too bad!';\n}", "function checkPositive(arr) {\n\n let b = arr.every((args) => args > 0)\n if (b == true) {\n return 'yes';\n }\n return 'no';\n}", "function extraYahtzee(yahtzeePoints) {\n\n for (var i = 0; i < diceArray.length; i++) {\n if (diceArray[i] !== diceArray[0]) {\n return 0;\n }\n }\n if (yahtzeePoints === \"50\") {\n return 100;\n } else if (yahtzeePoints === \"\") {\n alert(\"You must fill in yahtzee first\")\n submitCount++;\n } else {\n return 0;\n }\n}", "function super_fizzbuzz(array) {\n\tfor (var num in array) {\n\t\tvar output = \"\";\n\t\tif ((array[num] % 5 === 0) && (array[num] % 3 === 0 )) {\n\t\t\toutput = \"FizzBuzz\";\n\t\t} else if (array[num] % 5 === 0) {\n\t\t\toutput = \"Buzz\";\n\t\t} else if (array[num] % 3 === 0) {\n\t\t\toutput = \"Fizz\";\n\t\t}\n\t\tconsole.log(output || array[num]);\n\t}\n\n}", "function fruitNames() {\n for (var i = 0; i < foods.length; i++) {\n console.log('Do you like to eat ' + foods[i] + '?');\n }\n}", "function whosTheWinner(goals) {\n var nilaiGryffindor = 0;\n var nilaiSlytherin = 0;\n\n for (var i = 0; i <= goals.length - 1; i++) {\n if (goals[i] === 'Gryffindor') {\n nilaiGryffindor += 1;\n }\n else {\n nilaiSlytherin += 1;\n }\n }\n\n var hasil = '';\n if (nilaiGryffindor > nilaiSlytherin) {\n hasil = 'Gryffindor Juara Futsal Hogwarts 2018';\n }\n else if (nilaiGryffindor === nilaiSlytherin) {\n hasil = 'Draw, pertandingan akan dilanjutkan dengan penalty kick!';\n }\n else {\n hasil = 'Slytherin Juara Futsal Hogwarts 2018';\n }\n\n return hasil;\n // your code here\n}", "function findTheCheese (foods) {\n const cheese = [\"cheddar\", \"gouda\", \"camembert\"];\n \n for (let i=0; i < foods.length; i++) { \n \n let flag = cheese.indexOf(foods[i]);\n \n if(flag !== -1) {\n return foods[i];\n }\n } \n return \"no cheese!\";\n}", "function toDoSandwich(arr) {\n // console.log(arr);\n let bread = arr.includes('bread')\n // console.log(bread);\n if (bread) return 'sandwich for you'\n return 'no bread '\n}", "function checkYuGiOh(n){\n \n let myArray = []; \n \n \n for(let i=1; i<= n; i++){\n \n if( i % 2 === 0 && i % 3 === 0 && i % 5 === 0){myArray.push(\"Yu-Gi-Oh\") }\n else if( i % 2 === 0 && i % 5 === 0){myArray.push(\"Yu-Oh\") }\n else if( i % 2 === 0 && i % 3 === 0){myArray.push(\"Yu-Gi\") }\n else if( i % 5 === 0){myArray.push(\"Oh\") }\n else if( i % 3 === 0){myArray.push(\"Gi\") }\n else if( i % 2 === 0){myArray.push(\"Yu\") }\n else {myArray.push(i) }\n \n } \n \n \n if(typeof n === \"number\"){ \n return myArray;} \n else{\n return `invalid parameter: \"fizzbuzz is meh\"`}\n \n \n \n}", "function printPositiveIndex(arr){\n for ( var i=0; i< arr.length; i++){\n if(arr[i] > 0){\n console.log(arr.indexOf(arr[i]))\n }\n }\n}", "function outlookNegative(arr) {\n\tvar newArr = [];\n\tnum = 0;\n\n\tfor (var num = 0; num < arr.length; num++) {\n\t\tif (arr[num] > 0) {\n\t\t\tnewArr.push(arr[num] * -1);\n\t\t} \n\t\telse {\n\t\t\tnewArr.push(arr[num]);\n\t\t}\n\t}\n\n\tconsole.log(newArr);\n\treturn newArr;\n}", "function outlookNegative(array){\n let newArray = [];\n for(let i = 0; i < array.length; i++){\n // if(array[i] > 0){\n // newArray.push(array[i] * -1);\n // } else {\n // newArray.push(array[i]);\n // }\n newArray.push(array[i] > 0 ? -array[i] : array[i]);\n }\n return newArray;\n}", "function checkFood(food){\n\tvar food = [\"chicken\", \"beef\", \"fish\", \"lamb\", \"veal\"];\n\n\t//The first term starts with 0\n\n\tif(food == food[0] || food == food[1] || food == food[2] || food == food[3] || food == food [4]){\n\t\talert(\"You are considered as meat\");\n\t}else{\n\t\talert(\"You may or may not be considered as meat\");\n\t//if chicken, beef, fish, lamb or veal is entered, then a popup will appaer with \"You are considered as meat\"\n\t//if something else is entered, then a popup will appear saying \"you may or may not be considered as meat\"\t\n\t}\n}", "function truthyFalsey(arr){\nreturn \"anything\"\n}", "function findTheCheese (foods) {\n\nlet cheese = [\"cheddar\", \"gouda\", \"camembert\"]\n\nfor (let i = 0; i < foods.length; i++)\n{\n for (let b = 0; b < cheese.length; b++) {\n if (foods[i] === cheese[b]){\n return(foods[i]);\n }\n }\n}\nreturn (\"no cheese!\");\n}", "function onlyNegativeEvens(numbs){\n //returns an array containing all the positive evens from the sequence\n var NegativeEvenOnly = [];// empty array to store requested values in\n for (let i = 0; i < numbs.length; i++) {\n if (isNegative(numbs[i]) && isEven(numbs[i])){//CALLING OLDER FUNCTIONS\n NegativeEvenOnly.push(numbs[i]);// if check is good, pass into empty array\n }\n }\n return NegativeEvenOnly;// show us empty array\n}", "function test(input) {\n\n var results = [];\n for (var i = 1; i <= input; i++) {\n\n if (i % 3 == 0 ) {\n results.push(\"I'm sorry, Dave. I'm afraid I can't do that.\");\n } else if (i.toString().match(/0/)) {\n results.push(\"Beep!\")\n\n } else if (i.toString().match(/1/)) {\n results.push(\"Boop!\")\n\n } else {\n results.push(i);\n }\n }\n return results;\n }", "function howMuchILoveYou(nbPetals) {\n // your code\n var n = nbPetals % 6;\n \n var arr = [\"not at all\", \"I love you\", \"a little\", \"a lot\", \"passionately\", \"madly\"];\n \n return arr[n]; \n}", "function noNeg(arr){\n var positiveArr = []\n\nfor ( var i=0; i< arr.length; i++){\n if(arr[i] < 0){\n var newInd = arr[i] * 0;\n \n positiveArr.push(newInd);\n } else {\n positiveArr.push(arr[i]) \n }\n }\n \nreturn positiveArr\n}", "function checkYuGiOh(n){\n \nlet dArray = []; \n \nfor(let i=1; i<= n; i++){\n \n\nswitch (true) {\n\n case i % 2 === 0 && i % 3 === 0 && i % 5 === 0:\n dArray.push(\"Yu-Gi-Oh\");\n break;\n \n case i % 2 === 0 && i % 5 === 0:\n dArray.push(\"Yu-Oh\");\n break;\n \n case i % 2 === 0 && i % 3 === 0:\n dArray.push(\"Yu-Gi\");\n break;\n \n case i % 5 === 0:\n dArray.push(\"Oh\");\n break;\n \n case i % 3 === 0:\n dArray.push(\"Gi\");\n break;\n \n case i % 2 === 0:\n dArray.push(\"Yu\");\n break;\n \n default:\n dArray.push(i);\n}\n\n} \n \nif(Number(n)){ \n return dArray;\n } else{\n return `invalid parameter: \"fizzbuzz is meh\"`;\n }\n \n}", "function foodFunc() {\n\n var favFood = prompt('Guess one of the top four styles of foods that I enjoy eating.').toLowerCase();\n var foodStyles = ['mexican', 'italian', 'southern', 'japanese'];\n\n for (var i = 0; i < 5; i++) {\n if (favFood === foodStyles[0] || favFood === foodStyles[1] || favFood === foodStyles[2] || favFood === foodStyles[3]) {\n favFood = alert('Correct, ' + favFood + ' food is delicious!');\n score++;\n break;\n } else if (i !== 6) {\n favFood = prompt('That doesn\\'t make the top four. Please try again.');\n }\n }\n if (i === 5) {\n favFood = alert('My top four favorite styles of food are mexican, italian, southern, and japanese food!');\n }\n}", "function negNone(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n document.getElementById(\"1\").innerHTML = arr;\n return arr;\n}", "function johnLennonFacts(array) {\n\t// body...\n\tvar i = 0;\n\n\twhile(i < array.length){\n array[i] = array[i] + \"!!!\";\n i++;\n\t};\n\n\treturn array;\n}", "function paul(x){\n let score = 0\n \n for(i= 0; i < x.length; i++) {\n \n if(x[i] === 'life') {\n score = score + 0\n } else if (x[i] === 'Petes kata') {\n \n score = score + 10\n } else if(x[i] === 'eating') {\n \n score = score + 1\n } else if (x[i] === 'kata'){\n score = score + 5\n }\n }\n \n if(score < 40 ) {\n return 'Super happy!'\n } else if(score >= 40 && score < 70) {\n return 'Happy!'\n } else if(score >= 70 && score < 100) {\n return 'Sad!'\n } else if(score > 100) {\n return 'Miserable!'\n } \n}", "function whatDidYouEat(food) {\n var outcome;\n switch (food) {\n case \"beans\":\n outcome = \"gas attack\";\n break;\n case \"salad\":\n outcome = \"safe and sound\";\n break;\n case \"mexican\":\n outcome = \"diarrhea in 30 minutes\"\n break;\n default:\n outcome = \"please enter valid food\";\n }\n return outcome;\n}", "function onlyNegativeOdds(numbs){\n //returns an array containing all the positive evens from the sequence\n var NegativeOddOnly = [];// empty array to store requested values in\n for (let i = 0; i < numbs.length; i++) {\n if (isNegative(numbs[i]) && isOdd(numbs[i])){//CALLING OLDER FUNCTIONS\n NegativeOddOnly.push(numbs[i]);// if check is good, pass into empty array\n }\n }\n return NegativeOddOnly;// show us empty array\n}", "function taskFive() {\n //For loop that let us target each individual string in the Array\n for (let i = 0; i < fruits.length; i++) {\n //if the string matches one of these strings, push the string to \"trash\"\n if (fruits[i] === \"apelsin\" || fruits[i] === \"päron\") {\n trash.push(fruits[i]);\n }\n\n //Otherwise push the string to \"eatable\"\n else {\n eatable.push(fruits[i]);\n }\n }\n\n //when the loop is done, display \"eatable\" and trash, also separate the Arrays with a \"<br>\" and display the titles with bold\n document.getElementById(\"answer-five\").innerHTML =\n \"Ätbara frukter: \".bold() + eatable + \"<br>\" + \"Skräp: \".bold() + trash;\n}", "function fearFactorFunc(factor, weakAgainsts) {\n var length = weakAgainsts.length;\n if (length > 9) {\n console.log(\"Maksimal weaknesses hanya 9\");\n } \n else {\n var flag = true;\n for (var i = 0; i < weakAgainsts.length; i++) {\n var bilangan = \"\";\n switch (i) {\n case 0 : bilangan = \"pertama\"; break;\n case 1 : bilangan = \"kedua\"; break;\n case 2 : bilangan = \"ketiga\"; break;\n case 3 : bilangan = \"keempat\"; break;\n case 4 : bilangan = \"kelima\"; break;\n case 5 : bilangan = \"keenam\"; break;\n case 6 : bilangan = \"ketujuh\"; break;\n case 7 : bilangan = \"kedelapan\"; break;\n case 8 : bilangan = \"kesembilan\"; break;\n }\n if (weakAgainsts[i] === factor) {\n var string = \"Dia kalah karena kelemahan yang \" + bilangan;\n flag = false;\n }\n }\n if (flag) {\n console.log(\"Selamat dia juara\");\n } else {\n console.log(string);\n }\n }\n}", "function fruitGame() {\n var fruitList = ['raspberries','pomegranates','lemons','pineapples','grapes','strawberries','apples'];\n\n for( var i = 0 ; i < 6 ; i++ ){\n var fruitGuess = prompt('Guess one of my favorite fruits (plural).').toLowerCase();\n\n for( var j = 0 ; j < fruitList.length ; j++ ) {\n if( fruitGuess === fruitList[j]) {\n alert(`Awesome!! ${fruitGuess} is one of the correct answers! I like ${fruitList[0]}, ${fruitList[1]}, ${fruitList[2]}, ${fruitList[3]}, ${fruitList[4]}, ${fruitList[5]} and Granny Smith ${fruitList[6]}`);\n totalScore++;\n i = 6;\n break;\n }\n }\n\n if ( i > 4 && i < 6 ){\n alert(`Sorry. I actually like ${fruitList[0]}, ${fruitList[1]}, ${fruitList[2]}, ${fruitList[3]}, ${fruitList[4]}, ${fruitList[5]} and Granny Smith ${fruitList[6]}.`);\n break;\n } else if ( i === 4 ) {\n alert('Nope. Sorry. You have one more chance.');\n } else if ( i < 4 ) {\n alert(`${fruitGuess} is not one them.`);\n }\n }\n}", "function greetAll(nameArray) {\n let greetAll = \"Hoi \";\n\n for (let i = 0; i < nameArray.length; i++) {\n if (i === nameArray.length -1) { // scenario 1 - conditional\n return greetAll = greetAll + \" en \" + nameArray[i] + \"!\";\n }\n if (nameArray.length === 2 || i === nameArray.length -2) { // scenario 2 - conditional\n greetAll = greetAll + nameArray[i];\n }\n else {\n greetAll = greetAll + nameArray[i] + \", \"; // scenario 3 - conditional\n }\n }\n\n return greetAll\n}", "function solution(arr){\n\n}", "function checkAge() {\n if (age < 21) {\n alert(\"Sorry {{{toMarkdown}}}name{{{toMarkdown}}}, you aren't old enough to view this page!\");\n }\n else {\n alert(\"You can drink anything\");\n }\n console.log(checkAge(\"Charles\", 21))\n console.log(checkAge(\"Abby\", 27))\n console.log(checkAge(\"James\", 17))\n console.log(checkAge(\"John\", 18))\n\n // my favortie veggies in an array\n\n var favoriteVegstables = ['carrota', 'corn', 'green beens', 'onion', 'beats'];\n\n for (v = 0; v < favoriteVegstables.length; v++) {\n console.log(favoriteVegstables[v]);\n }\n\n //names and ages for people \n\n var people = [\n {name: \"Josh\",\n age: 16},\n\n { name: \"Don\",\n age: 93 },\n\n {\n name: \"Bobbito\",\n age: 23\n },\n\n { name: \"Samantha\",\n age: 11 },\n\n { name: \"Fran\",\n age: 55},\n ];\n\n for (i = 0; i < people.length; i++) {\n checkAge(people[i].name, people[i].age);\n }\n\n // makes any word argument\n\n\n function getlength(word) {return word.length }\n var number = (\"Hello World!\");\n let anyWord = getLength('Hello World');\n let test = anyWord % 2\n if (test == 0) {\n console.log('The world is nice and even!');\n }\n else {\n console.log('The world is an odd place!');\n }\n}", "function outlookNegative(arr){\n var newArr = []\n for(var i = 0; i < arr.length; i++){\n if(arr[i] > 0){\n newArr.push(arr[i] * -1)\n }else{\n newArr.push(arr[i])\n }\n }\n return newArr\n}", "function checkPositive(arr) {\n // Add your code below this line\n return arr.some(num => num > 0); //checks array if any element > 0;\n // Add your code above this line\n}", "function outlookNetative(array) {\n var allNegative = [];\n\n for (var i in array) {\n if (array[i] > 0) {\n allNegative[i] = array[i] * -1;\n } else {\n allNegative[i] = array[i];\n }\n }\n return allNegative;\n}", "function forLoop(array) {\nfor (var i = 0; i < 25; i++)\n{\n if (i===1 || i===0){\n array.push(`I am ${i} strange loop.`)\n}\nelse {\n array.push(`I am ${i} strange loops.`)\n}}\n return array\n}", "function bePositive(arr){\nvar positiveArr = []\n\nfor ( var i=0; i< arr.length; i++){\n if(arr[i] < 0){\n var newInd = arr[i] * -1;\n \n positiveArr.push(newInd);\n } else {\n positiveArr.push(arr[i]) \n }\n }\n \nreturn positiveArr\n}", "function dispenseChocolates(chocolates,number)\n{\n var result = [];\n if (number <= 0) {\n return \"Number cannot be zero/negative\";\n }\n else if (number > chocolates.length)\n return \"Insufficient chocolates in the dispenser\";\n else\n for (let i = 0; i < number; i++) {\n result.push(chocolates.pop());\n }\n return result;\n}", "function able(num){\n var arr = [];\n for(var i=1; i<= num; i++) {\n if(i % 2 === 0 && i % 3 === 0 && i % 5 === 0){\n arr.push(\"yu-gi-oh\");\n }\n else if(i % 2 === 0 && i % 3 === 0){\n arr.push(\"yu-gi\");\n }\n else if(i % 2 === 0 && i % 5 === 0){\n arr.push(\"yu-oh\");\n }\n else if(i % 3 === 0 && i % 5 === 0){\n arr.push(\"gi-oh\");\n }\n else if(i % 2 === 0){\n arr.push(\"yu\");\n }\n else if(i % 3 === 0){\n arr.push(\"gi\");\n }\n else if(i % 5 === 0){\n arr.push(\"oh\");\n }\n else {arr.push(i)}\n }\nreturn arr;\n}", "function countSheeps(arrayOfSheep) {\n // TODO May the force be with you\n\n// counter\n let count = 0\n\n console.log(arrayOfSheep)\n\n// loop through the array\n for(let i = 0; i < arrayOfSheep.length; i++)\n {\n\n console.log(\"i\", i)\n\n// false = count not increasing\n if(findTheSheep(arrayOfSheep[i]))\n {\n\n count = count\n\n// anything else, count increases\n }else{\n\n count++\n\n }\n\n }\n return count;\n}", "function chap19(){\n var wantChicken = false;\n var foodArray = [\"Salmon\", \"Tilapia\", \"Tuna\", \"Lobster\"];\n var customerOrder = prompt(\"What would you like?\", \"Look the menu\");\n for (var i = 0; i <= 3; i++) {\n if (customerOrder === foodArray[i]) {\n wantChicken = true;\n alert(\"We have it on the menu!\");\n break;\n }\n }\n if(wantChicken===false) {\n\t\talert(\"We don't serve chicken here, sorry.\");\n\t}\n}", "function chap18(){\n var foodArray = [\"Salmon\", \"Tilapia\", \"Tuna\", \"Lobster\"];\n var customerOrder = prompt(\"What would you like?\", \"Look the menu\");\n for (var i = 0; i <= 3; i++) {\n if (customerOrder === foodArray[i]) {\n alert(\"Thanks, I'll be right back with your food!\");\n }\n }\n}", "function cake() {\n let cakeFlavour = [vanilla = cake, chocolate = !cake];\n \n \n if ((cake !== chocolate) && (cake === vanilla)) {\n console.log('this cake is vanilla');\n } else {\n console.log('no cake');\n }\n }", "function checkFruits(fruit) {\n switch (fruit) {\n case \"banana\":\n return \"banana is creamy\";\n case \"orange\":\n return \"orange is juicy\";\n case \"strawberry\":\n return \"strawberry is yummy\";\n case \"apple\":\n return \"apple is crunchy\";\n default:\n \"Please enter a fruit\";\n }\n}", "function lvl5exercise4() {\n var array = [1, \"adam\"];\n console.log(\"4) \" + array.indexOf(\"adam\"));\n\n}", "function perspectiva(arrayNegativo) {\n for (let i = 0; i < arrayNegativo.length; i++) {\n if ( arrayNegativo[i] < 0 ) {\n console.log(\"Encontrado Negativo: \", arrayNegativo[i])\n } else {\n console.log(\"Encontrado Positivo: \", arrayNegativo[i])\n arrayNegativo[i] = arrayNegativo[i] * -1\n }\n }\n for (let x = 0; x < arrayNegativo.length; x++) {\n console.log(\"Posicion en el Array #[\"+(x)+\"]: \", arrayNegativo[x]) \n }\n return arrayNegativo\n}", "function whatReallyHappensToday() {\n\tvar disasterList = [];\n\tvar probV = Math.random();\n\tvar probT = Math.random();\n\tvar probE = Math.random();\n\tvar probB = Math.random();\n\tvar probM = Math.random();\n\tif(probV < .1) {\n\t\tdisasterList.push(\"volcano\");\n\t}\n\tif(probT < .15) {\n\t\tdisasterList.push(\"tsunami\");\n\t}\n\tif(probE < .20) {\n\t\tdisasterList.push(\"earthquake\");\n\t}\n\tif(probB < .25) {\n\t\tdisasterList.push(\"blizzard\");\n\t}\n\tif(probM < .30) {\n\t\tdisasterList.push(\"meteor strike\");\n\t}\n\tconsole.log(disasterList);\n\tif(disasterList.length > 0) {\n\t\tconsole.log(\"Today Kenny has died in the following accidents: \" + disasterList + \" ... bummer.\");\n\t} else {\n\t\tconsole.log(\"Kenny isn't dead!?\");\n\t}\n}", "function replaceNegative(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = \"Negative\"\n }\n }\n console.log(arr);\n}", "function FizzBuzzifier(array) {\n let answer = [];\n for (let i = 0; i < array.length; i++) {\n console.log(`Loop number ${i}`)\n if ((array[i] % 3 === 0) && (array[i] % 5 === 0)) {\n answer.push('FizzBuzz')\n } else if (array[i] % 3 === 0) {\n answer.push('Fizz') \n } else if (array[i] % 5 === 0) {\n answer.push('Buzz') \n } else {\n answer.push(array[i])\n }\n }\n console.log(`answer:`, answer);\n return answer;\n}", "function checkYuGiOh(n) {\r\n let numbers = [];\r\n\r\n for(let i=1; i<=n ; i++) {\r\n numbers.push(i)\r\n }\r\n\r\n if(typeof n === \"string\" && n.indexOf(\" \") >= 0) {\r\n console.log(`invalid parameter: \"${n}\"`);\r\n } else {\r\n for(let i=0; i<numbers.length; i++) {\r\n if(numbers[i] % 2 === 0 && numbers[i] % 3 === 0 && numbers[i] % 5 ===0 ) {\r\n numbers[i] = \"yu-gi-oh\";\r\n } else if(numbers[i] % 2 === 0 && numbers[i] % 3 === 0) {\r\n numbers[i] = \"yu-gi\";\r\n } else if(numbers[i] % 2 === 0 && numbers[i] % 5 === 0) {\r\n numbers[i] = \"yu-oh\";\r\n } else if(numbers[i] % 2 === 0) {\r\n numbers[i] = \"yu\";\r\n } else if(numbers[i] % 3 === 0) {\r\n numbers[i] = \"gi\";\r\n } else if(numbers[i] % 5 === 0) {\r\n numbers[i] = \"oh\";\r\n }\r\n }\r\n console.log(numbers);\r\n }\r\n}", "function countFeelings(string, array) {\n \n // Input: String of random lower-case letters, an array of strings.\n // Output: String.\n \n // Algorithm:\n // - [X] Look through the feelings.\n // - [X] Look at each letter in the feeling.\n // - [X] Check if the letter is in the string.\n // - [X] If all letters are found in the string keep a count.\n \n let count = array.length;\n \n for(let i = 0; i < array.length; i++) {\n const word = array[i].split('');\n \n for(let j = 0; j < word.length; j++) {\n const letter = word[j];\n \n if(!string.includes(letter)){\n count -= 1;\n break;\n };\n }\n }\n \n const answer = count === 1 ? `${count} feeling.` : `${count} feelings.`;\n \n return answer;\n }", "function findWinner(arr) {\n\tlet found = arr.find(el => el.isEligible).name;\n\tif (found) {\n\t\treturn `Congratulations ${found}, you win one thousand pounds`;\n\t}\n\treturn \"bad luck, we're going to spend the prize money on pizza\";\n}", "function negativevalues(arr)\r\n{\r\n\tfor(var i=0;i<arr.length;i++)\r\n\t{\r\n\t\tif (arr[i]<0)\r\n\t\t{\r\n\t\t\tarr[i]=0;\r\n\t\t}\r\n\t}\r\n\r\n\t\tconsole.log (\"Removing negatives\",arr);\r\n}", "function arrayNo(arr) {\n let positive = [];\n for (let i = 0; i < arr.length; i++) {\n let no = arr[i];\n if (no < 0) {\n break;\n }\n else {\n positive.push(no);\n }\n\n }\n return positive;\n\n}", "function exercise(input){\n if(input === 'running'){\n var statement = \"Today's excercise: \" + input ; \n }else if (input === 'swimming'){\n var statement = \"Today's excercise: \" + input ; \n }\n return statement; \n}", "function positive(num) {\r\n if (num > 0) {\r\n return console.log(num);\r\n } else {\r\n return console.log(-1 * num);\r\n }\r\n}", "function carsFun(){\n let cars = [\"mercedes\", \"bmw\", \"ford\", \"jeep\", \"honda\", \"land cruiser\"];\n let carsUser=prompt(\"Can you guess what my favorite car is ?\")\n console.log(carsUser)\n for(let count2=1 ; count2<cars.length ; count2++){\n if (carsUser.toLowerCase()!==cars[count2]){\n alert(\"No, Please try again !\");\n let carsUser=prompt(\"Can you guess what my favorite cars are again ?\")\n console.log(carsUser)\n }else if(carsUser.toLowerCase()==cars[count2]){\n alert(\"Yes, this is true. Actually My favorite cars are: mercedes, bmw, ford, jeep, honda and land cruiser.\");\n sum=sum+1;\n count2=6;\n }\n }\n}", "function noNegatives(arr) {\n for (var idx = 0; idx < arr.length; idx++) {\n if (arr[idx] < 0) {\n arr[idx] = 0;\n }\n }\n console.log(arr);\n}", "function negatives(array) {\n for (let i = 0; i < array.length; i++) {\n if(array[i] < 0) { \n array[i] = 0;\n }\n }\n return array;\n}", "function maybe(array) {\n if( chance.bool() ) {\n return choice(array);\n} \n else {\n return '';\n }\n}", "function myDrinks1(){\n\n\n let answer = 'None';\n let drinks = ['tea','coffee','water'];\n let count = 6;\n console.log('What are my favorite drinks?');\n for (let j=0 ; j<6 ; j++){\n let gues = prompt('Can you guess one of my favorite drinks?\\n You have '+count+' attempts left.');\n count--;\n\n for (let i=0; i<4 ; i++){\n if (gues === drinks[i]){\n alert('Wow!! You got it right!');\n answer = 'right';\n score++;\n break;\n }\n }\n\n if (answer==='right'){\n break;\n }\n\n }\n alert('My favorite drinks are: '+drinks);\n}", "function printOneReturnAnother(arr){\n console.log(arr[arr.length - 2]);\n for(var i = 0; i < arr.length; i++){\n if(arr[i] % 2 == 1 || arr[i] % 2 == -1){\n return arr[i];\n } else {\n return \"No odds.\";\n }\n }\n}", "function checkResult(){\n if(collectedFruit.length < eatenFruit.length){\n return 'lost';\n } else if(collectedFruit.length === eatenFruit.length) {\n return 'even';\n } else {\n if(collectedFruit.length >= 8){\n return 'won';\n } else {\n return 'ok';\n }\n }\n}", "function customEvery(array){\n var answer = true\n array.forEach(function(i){\n if(i % 2 != 0){\n answer = false\n console.log(answer)\n return answer\n }\n })\n return answer\n}", "function warnTheSheep(queue) {\n\nif (queue[queue.length -1] === 'wolf') {\n return 'Pls go away and stop eating my sheep';\n } else {\n let index = queue.findIndex( (x) => x == 'wolf' );\n return `Oi! Sheep number ${queue.length - index - 1}! You are about to be eaten by a wolf!`;\n }\n }", "function fizzBuzzAgain() { \n let myArray = Array.from(arguments);\n\n return myArray.map((value) => {\n let result = value;\n if(result % 5 === 0 && result % 3 === 0) {\n result = \"FizzBuzz\";\n }\n else if(result % 5 === 0) {\n result = \"Buzz\";\n }\n else if(result % 3 === 0) {\n result = \"Fizz\";\n }\n return result;\n })\n}", "function checkPositive(arr) {\n // Add your code below this line\n return arr.every(function(currentValue){\n return currentValue > 0;\n });\n // Add your code above this line\n}", "function negativeAmount() {\n if (userGuess / secretNumber === 1){\n setFeedback(\"You win\");\n finish = true;\n } else if ((userGuess - secretNumber) > 60.5){\n setFeedback(\"Wow! You are freezing!\");\n } else if ((userGuess - secretNumber) > 55.5){\n setFeedback(\"Wow! You better put on a jacket cause its super cold!\");\n } else if ((userGuess - secretNumber) > 50.5){\n setFeedback(\"Its is super cold man!\");\n } else if ((userGuess - secretNumber) > 40.5) {\n setFeedback(\"Now you are cold!\");\n } else if ((userGuess - secretNumber) > 30.5) {\n setFeedback(\"It's getting warm around here\");\n } else if((userGuess - secretNumber) > 20.5) {\n setFeedback(\"It's getting very warm in here!\");\n } else if((userGuess - secretNumber) > 15.5) {\n setFeedback(\"It's getting very very warm in here!\");\n } else if ((userGuess - secretNumber) > 7.5){\n setFeedback(\"It is hot!\");\n } else if ((userGuess - secretNumber) > 5.5){\n setFeedback(\"I am very hot here!!\");\n } else if((userGuess - userGuess) > 1.5){\n setFeedback(\"I am burning here!!\");\n }else if ((userGuess - secretNumber) > 0.5){\n setFeedback(\"Its is hotter than the sun!!!!!\");\n } else {\n }\n }", "function scoreInUniversty(num) {\r\n if (0 <= num && num <= 49) {\r\n return console.log(\"F\");\r\n } else if (50 <= num && num <= 69) {\r\n return console.log(\"D\");\r\n } else if (70 <= num && num <= 84) {\r\n return console.log(\"C\");\r\n } else if (85 <= num && num <= 94) {\r\n return console.log(\"B\");\r\n } else if (95 <= num && num <= 100) {\r\n return console.log(\"A\");\r\n }\r\n}", "function gussAnimal() {\n alert(\n \"It is gitting more exciting now \" +\n username +\n \", For this question you have six attempts to guss one of my favorite Animal List\"\n );\n for (let i = 1; i < 7; i++) {\n let animalGuess = prompt(\n \"Here is your attempt number \" + i + \", Guess one animal!\"\n ).toLowerCase();\n console.log(\"Animal Guessing \" + i + \": \" + animalGuess);\n for (let j = 0; j < favAnimals.length; j++) {\n if (animalGuess === favAnimals[j]) {\n alert(\n \"Well Done \" +\n username +\n \", that's right \" +\n animalGuess +\n \" is in my list\"\n );\n flag2 = true;\n break;\n }\n if (flag2 == true) {\n break;\n }\n }\n if ((i == 6 && flag2 == false) || flag2 == true) {\n break;\n } else if (flag2 == false) {\n alert(\"No that's incorrect, try again\");\n }\n }\n if (flag2 == false) {\n alert(\"So sorry \" + username + \", you got none right :(\");\n }\n alert(\n \"my list of favorite animals are: \" +\n favAnimals[0] +\n \", \" +\n favAnimals[1] +\n \", \" +\n favAnimals[2] +\n \", \" +\n favAnimals[3] +\n \" and \" +\n favAnimals[4]\n );\n\n for (let i = 0; i < favAnimals.length; i++) {\n console.log(\"Animal number \" + i + 1 + \" is \" + favAnimals[i]);\n }\n }", "function negativeValues(arr){\n for(var i = 0; i < arr.length; i++){\n if(arr[i] < 0){\n arr[i] = 0;\n }\n }\n console.log(arr); //or: return arr;\n}", "function beepBoop(userInput){\n\n var list = [];\n\n if (isNaN(userInput)) {\n return \"Please enter a real number, friend.\";\n }\n\n for (var i = 0; i <= userInput; i++){\n var replace = i;\n\n if (i.toString().includes(1)){\n var replace = \"Beep!\";\n\n }\n if (i.toString().includes(2)) {\n var replace = \"Boop!\";\n\n }\n if (i.toString().includes(3)) {\n var replace = \"I'm sorry, Dave. I'm afraid I can't do that.\";\n }\n list.push(replace);\n }\n\n return list;\n}", "function warnTheSheep(queue) {\n let positionInQue = queue.length - 1;\n\n for (let i = 0; i < queue.length; i++) {\n if ((queue[i] === 'wolf') && (queue.indexOf('wolf') !== queue.length - 1)) {\n return `Oi! Sheep number ${positionInQue}! You are about to be eaten by a wolf!`;\n } else if (queue.indexOf('wolf') === queue.length - 1) {\n return \"Pls go away and stop eating my sheep\";\n } else {\n positionInQue--;\n continue;\n }\n } \n}", "function getFruit(array) {\n for (i = 0; i < array.length; i++ ) {\n console.log(array[i]);\n }\n}", "function punteggio () {\n for (var j = 0; j < casualArray.length; j++) {\n if (casualArray.includes(guessArray[j])) {\n risultato++\n }\n }\n document.write (\"Il tuo punteggio è: \" + risultato);\n}" ]
[ "0.7211276", "0.7023037", "0.695569", "0.6935531", "0.6932139", "0.69065213", "0.687068", "0.68292034", "0.67541516", "0.67254597", "0.66782475", "0.6672089", "0.6620615", "0.64404887", "0.6432771", "0.63878524", "0.6201085", "0.6180165", "0.6153753", "0.61414564", "0.6114075", "0.6081932", "0.6072435", "0.6061176", "0.6059984", "0.60439557", "0.6039339", "0.5962249", "0.5943441", "0.5909764", "0.58843076", "0.5872957", "0.5863672", "0.5847453", "0.5841862", "0.5840917", "0.5830496", "0.5820222", "0.5818701", "0.57857275", "0.5772445", "0.5771636", "0.5767703", "0.57626104", "0.5761735", "0.5753255", "0.57494456", "0.57346743", "0.57310283", "0.5725504", "0.57111526", "0.57106555", "0.57094777", "0.57051986", "0.5695394", "0.568643", "0.56789875", "0.5653991", "0.56525743", "0.5651268", "0.5651183", "0.56504136", "0.56475157", "0.5634122", "0.5614522", "0.56057453", "0.56051147", "0.56031674", "0.56027687", "0.55982876", "0.5596175", "0.55909705", "0.5586061", "0.5583144", "0.5578869", "0.5577165", "0.5571812", "0.5570606", "0.55703825", "0.5557163", "0.5555625", "0.55530965", "0.5551548", "0.5548616", "0.5546159", "0.55414903", "0.5537176", "0.5536658", "0.5531052", "0.5530279", "0.55295736", "0.55207896", "0.55128276", "0.55120814", "0.55079764", "0.5495852", "0.5494542", "0.54930973", "0.5487942", "0.5484028" ]
0.67625886
8
alwaysHungry(['food',"cake",'wine','apple']); Challenge 13 Swap Toward the Center Given an array, swap the first and last values, third and thirdtolast values, etc. Example: swapTowardCenter([true,42,"Ada",2,"pizza"]) turns the array into ["pizza", 42, "Ada", 2, true]. swapTowardCenter([1,2,3,4,5,6]) turns the array into [6,2,4,3,5,1]. No need to return the array this time.
function swapTowardCenter(arr){ for(var i = 0; i < arr.length/2; i+=2) { var temp = arr[i]; arr[i] = arr[arr.length - 1 - i]; arr[arr.length - 1 - i] = temp; } console.log(arr); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function swapTowardCenter(arr){\n for (let i = 0; i < arr.length/2; i++) {\n var temporaryVarForSwitchingIndex = arr[i]\n arr[i] = arr[arr.length - 1-i] \n arr[arr.length - 1-i] = temporaryVarForSwitchingIndex \n \n }\n return arr \n}", "function swapTowardCenter(arr){\n var temp;\n var count = arr.length -1;\n\n for(var i = 0; i < arr.length; i++){\n if(i == 0){\n temp = arr[0];\n arr[0] = arr[count];\n arr[count] = temp;\n count += 2;\n } else if ((i < arr.length/2) && (i % 2 == 0)){\n temp = arr[i];\n arr[i] = arr[count];\n arr[count] = temp;\n count += 2;\n }\n }\n\n return arr;\n}", "function swapTowardCenter(arr){\n var temp;\n for(var i = 0 ; i < arr.length/2; i+=2){\n temp = arr[i];\n arr[i] = arr[arr.length-1-i];\n arr[arr.length-1-i] = temp;\n }\n return arr;\n}", "function swapTowardsTheCenter(arr) {\n var len = arr.length;\n var idx = 0;\n var lastIdx = arr.length - 1;\n while (idx <= len / 2 && lastIdx >= len / 2) {\n var temp = arr[idx];\n arr[idx] = arr[lastIdx];\n arr[lastIdx] = temp;\n idx = idx + 2;\n lastIdx = lastIdx - 2;\n }\n return arr;\n}", "function swapTowardsCenter(arr){\n for(var i = 0; i < arr.length/2; i+=2){\n var temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n }\n return arr\n}", "function CenterSwap(arr) {\n\tfor (var i = 0; i <=arr.length/2; i++) {\n\t\tvar temp=arr[i];\n\t\tarr[i]= arr[arr.length-1-i]\n\t\tarr[arr.length-1-i]=temp;\n\t}\n\treturn arr;\n}", "function swapTowardCenter(arr) {\n for (var i = 0; i < arr.length / 2; i = i + 2) {\n var temp = arr[i];\n arr[i] = arr[arr.length - (i + 1)];\n arr[arr.length - (i + 1)] = temp;\n }\n console.log(arr);\n}", "function swapTowardCenter(array) {\n var midpoint = array.length / 2;\n\n console.log(\"midpoint: \" + midpoint);\n for (var i = 0; i < midpoint; i++) {\n if (i % 2 === 0) { // Even index found, swap this, matching end index \n console.log(i);\n var temp = array[i]; \n array[i] = array[array.length -1 - i];\n array[array.length -1 - i] = temp;\n console.log(array);\n }\n }\n \n return array;\n}", "function swaptoCenter(arr){\n let temp\n for (let i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[i];\n arr[i] = arr[arr.length-i-1];\n arr[arr.length-i-1] = temp;\n }\n return arr\n}", "function swap(arr) {\n\n var temp1 = arr[0];\n var temp2 = arr[2];\n\n arr[0] = arr[arr.length - 1];\n arr[2] = arr[arr.length - 3];\n arr[arr.length - 1] = temp1;\n arr[arr.length - 3] = temp2;\n return arr;\n}", "function swap(before, after, array)\n{\n \n //swap the element:\n let temp = array[before]; \n array[before] = array[after];\n array[after] = temp;\n}//end of swap()", "function swap(arr,xp, yp)\n{\n var temp = arr[xp];\n arr[xp] = arr[yp];\n arr[yp] = temp;\n}", "function moveConsonants (array) {\r\n if (!(array[0] == \"a\" || array[0] == \"e\" || array[0] == \"i\" ||array[0] == \"o\" || array[0] == \"u\")) {\r\n var first = array.shift();\r\n array.push(first);\r\n moveConsonants(array);\r\n } else {\r\n array.push(\"ay\");\r\n }\r\n }", "function swapValues(array){\n debugger; // debugger command for stepping through code in Chrome\n // set the temp variable to the first value of the given array\n var temp = array[0];\n // now updated the array[0] value to array[array.length - 1]\n array[0] = array[array.length - 1];\n // now switch (reset) array[array.length - 1] to the value of the temp var\n array[array.length - 1] = temp;\n // return the new array\n return array;\n}", "function swap(array, posA, posB) {\n var temp = array[posA]; \n array[posA] = array[posB]; \n array[posB] = temp; \n }", "function swap (arr){\n //for (var i=0;i<arr.length;i++){\n [arr[0], arr[arr.length-1]] = [arr[arr.length-1], arr[0]];\n \n \n\n //}\n\n return arr;\n}", "function lilysHomework(arr) {\r\n\r\n const swaps = (arr, sarr) => {\r\n let [s, idx] = [0, []];\r\n arr.forEach((v,i) => idx[v] = i);\r\n for (let i = 0, j; i <100000 ; i++) {\r\n while (arr[i] === sarr[i] && i < 100000) i++;\r\n j = idx[sarr[i]];\r\n idx[arr[i]] = j;\r\n arr[i] = [ arr[j], arr[j] = arr[i] ][0];\r\n s++;\r\n }\r\n return s-1;\r\n }\r\n \r\n let asc = [...arr].sort((a,b) => a-b);\r\n let desc = [...asc].reverse();\r\n let s1 = swaps([...arr], asc);\r\n let s2 = swaps(arr, desc);\r\n\r\n return Math.min(s1, s2)\r\n\r\n}", "function swapPair(array) {\n for (let i = 0; i < array.length; i = i + 2) {\n let temp = array[i];\n array[i] = array[i + 1];\n array[i + 1] = temp;\n }\n return array\n}", "function replItems (array) {\n\tfunction lettScore (inLett) {\n\t\tvar outScore;\n\t\tswitch (inLett) {\n\t\t\tcase \"A\":\n\t\t\t\toutScore = 1;\n\t\t\t\tbreak;\n\t\t\tcase \"E\":\n\t\t\t\toutScore = 1;\n\t\t\t\tbreak;\n\t\t\tcase \"R\":\n\t\t\t\toutScore = 2;\n\t\t\t\tbreak;\n\t\t\tcase \"D\":\n\t\t\t\toutScore = 2;\n\t\t\t\tbreak;\n\t\t\tcase \"B\":\n\t\t\t\toutScore = 3;\n\t\t\t\tbreak;\n\t\t\tcase \"M\":\n\t\t\t\toutScore = 3;\n\t\t\t\tbreak;\n\t\t\tcase \"V\":\n\t\t\t\toutScore = 4;\n\t\t\t\tbreak;\n\t\t\tcase \"Y\":\n\t\t\t\toutScore = 4;\n\t\t\t\tbreak;\n\t\t\tcase \"J\":\n\t\t\t\toutScore = 8;\n\t\t\t\tbreak;\n\t\t\tcase \"X\":\n\t\t\t\toutScore = 8;\n\t\t\t\tbreak;\n\t\t}\n\t\treturn outScore;\n\t}\n\n\tfor (var i = 0; i < array.length; i++) {\n\t\tarray[i] = lettScore(array[i]);\n\t}\n}", "function swap(array, posA, posB) {\n var temp = array[posA]; \n array[posA] = array[posB]; \n array[posB] = temp; \n }", "function splitAndSquash(array){\n var init = array.shift();\n return squashLettersTogether([], init, array)\n}", "function swap(array){\n\n for(var i = 0 ; i < array.length/2 ; i++){\n var tmp = array[array.length - 1 - i];\n array[array.length -1 - i] = array[i];\n array[i] = tmp;\n }\n return array.join(\"\");\n\n }", "function swap(array){\n\n for(var i = 0 ; i < array.length/2 ; i++){\n var tmp = array[array.length - 1 - i];\n array[array.length -1 - i] = array[i];\n array[i] = tmp;\n }\n return array.join(\"\");\n\n }", "function InPlace(arr) {\n // let swap = (arr, i, j) => ([arr[i], arr[j]] = [arr[j], arr[i]], arr);\n let swap = (arr, i, j) => {\n let tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n function findCenter(arr, left, right) {\n let flag = arr[left];\n let idx = left + 1;\n for (let i = idx; i <= right; i++) {\n if (arr[i] < flag) {\n swap(arr, idx, i);\n idx++;\n }\n }\n swap(arr, left, idx - 1)\n return idx;\n }\n function sort(arr, left, right) {\n if (left < right) {\n let centerIndex = findCenter(arr, left, right);\n sort(arr, left, centerIndex - 1);\n sort(arr, centerIndex, right)\n }\n }\n sort(arr, 0, arr.length - 1);\n return arr;\n}", "function ShiftArrayValsLeft(arr){\n}", "function arraySwap(array) {\n\t\t\tif (!array || !array.length)\n\t\t\t\treturn array;\n\n\t\t\tvar left = 1;\n\t\t\tvar right = array.length - 1;\n\t\t\tfor (; left < right; left++, right--) {\n\t\t\t\tvar temporary = array[left];\n\t\t\t\tarray[left] = array[right];\n\t\t\t\tarray[right] = temporary;\n\t\t\t}\n\t\t\treturn array;\n\t\t}", "function swaptocenter(arr){\n for(var i=0;i<arr.length/2;i+=2){\n var temp=arr[i];\n arr[i]=arr[arr.length-1-i];\n arr[arr.length-1-i]=temp;\n }\n return arr;\n}", "function bubbleSortEnhanced(array) {\n\n var swapped = true;\n var temp;\n\n do {\n swapped = false;\n for(var i = 0; i < array.length; i++) {\n if( array[i] !== undefined && array[i + 1] !== undefined && array[i] > array[i + 1] ) {\n //swap(array, i, i + 1);\n temp = array[i];\n array[i] = array[i + 1];\n array[i + 1] = temp;\n swapped = true;\n }\n }\n } while(swapped)\n return array;\n}", "function swap(arr=[], a, b){\n\tlet temp = arr[a];\n\tarr[a] = arr[b];\n\tarr[b] = temp;\n\treturn;\n}", "function swap(arr) {\n var temp = arr[arr.length - 1];\n arr[arr.length - 1] = arr[0];\n arr[0] = temp;\n}", "function swap(arr, x, y) {\n var tmp = arr[x];\n arr[x] = arr[y];\n arr[y] = tmp;\n }", "function swap(arr)\r\n{\t\r\n\r\n\tvar temp;\r\n\tvar c =arr.length;\r\n\tfor (var i = 0; i < arr.length; i++) \r\n\t{\r\n\t\t\ttemp = arr[c-1-i];\r\n\t arr[c-1-i]=arr[i];\r\n\t arr[i]=temp;\r\n\t \t\r\n\t\t\r\n\t}\r\n\t\r\n\tconsole.log(arr);\r\n}", "function swap(arr)\n{\n var temp;\n var end=arr.length-1;\n for(var i=0; i<arr.length/2; i+=2)\n {\n \n temp=arr[i];\n arr[i]=arr[end-i];\n arr[end-i]=temp;\n }\n return arr\n}", "function swap(currentPosition,nextPosition,array){\n\t\tvar temp = array[currentPosition];\n\t\tarray[currentPosition] = array[nextPosition];\n\t\tarray[nextPosition] = temp;\n\t}", "function shuffleArray(array) {\n // track pairity\n var pairity = 1;\n \n // Randomize array in-place using Durstenfeld shuffle algorithm \n // Cribbed from https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array\n for (var i = array.length - 1; i > 0; i--) {\n var j = Math.floor(Math.random() * (i + 1));\n var temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n if(i!=j) pairity*=-1; // No swap is even pairity; all else are odd\n }\n\n // We want an even number of swaps, to give us an even pairty, which means a solvable. puzzle.\n // If we don't have it, just swap the first two elements. (Or move the empty space!)\n if(pairity==-1) {\n // This was an odd number of swaps\n tmp = array[0];\n array[0] = array[1];\n array[1] = tmp;\n }\n}", "function fixTheMeerkat(arr) {\n let givenArr = arr;\n return givenArr.reverse()\n}", "function swapPairs(arr){\n \n for( var i = 0; i<=arr.length-2; i+=2){\n temp = arr[i+1];\n arr[i+1] = arr[i];\n arr[i] = temp;\n }\n return arr;\n \n}", "function swapArr(arr){\nreturn arr.reverse();\n}", "function swap(array, i , j){\n let temp = array[i]\n array[i] = array[j]\n array[j] = temp\n}", "function swap(arr){\n var temp = arr[0];\n arr[0] = arr[arr.length-1];\n arr[arr.length-1] = temp;\n return arr;\n}", "function swap(arr){\n for (i = 0; i < arr.length / 2; i++){\n if (i % 2 == 0){\n var temp = arr[i];\n arr[i] = arr[arr.length - (i + 1)];\n arr[arr.length - (i + 1)] - temp;\n }\n }\n return arr\n}", "function swap(arr) {\n var temp = arr[0];\n arr[0] = arr[arr.length-1];\n arr[arr.length-1] = temp;\n return arr; \n}", "function swap(arr) {\r\n var storage = arr[0];\r\n arr[0] = arr[arr.length - 1];\r\n arr[arr.length -1] = storage;\r\n return arr; \r\n}", "function cocktailShakerSort(array, delay){\n var data = array.slice();\n var swaps = 0;\n //Main loop\n for(var i = 0; i < data.length/2; i++){\n var swapped = false;\n \n //Sorts next, unsorted largest-value\n for(var j = i; j < data.length - i - 1; j++){\n if(data[j] > data[j+1]){\n var tmp = data[j];\n data[j] = data[j+1];\n data[j+1] = tmp;\n swapped = true;\n \n timeouts.push(setTimeout(swap, delay*swaps, j, j+1));\n swaps++;\n }\n }\n \n //Sorts next, unsorted smallest-value\n for(var j = data.length - 2 - i; j > i; j--){\n if(data[j] < data[j-1]){\n var tmp = data[j];\n data[j] = data[j-1];\n data[j-1] = tmp;\n swapped = true;\n \n timeouts.push(setTimeout(swap, delay*swaps, j, j-1));\n swaps++;\n }\n }\n \n if(!swapped) break; //If finished sorting\n }\n \n return data;\n}", "function swap(array, left, right){\n [array[left], array[right]]=[array[right], array[left]];\n return array;\n}", "function swap(j, array) {\n var temp = array[j]\n array[j] = array[j + 1]\n array[j + 1] = temp\n\n return array\n\n}", "swapPositions( x, y, oppositeDay ) {\n if (oppositeDay) {\n [x,y]=[y,x];\n }\n var str = this.target;\n var xChar = str[x];\n var yChar = str[y];\n var newStr = [];\n\n\n for (var i = 0; i < str.length; i++) {\n if (i === x) {\n newStr.push( yChar );\n } else if (i === y) {\n newStr.push( xChar );\n } else {\n newStr.push( str[i] );\n }\n }\n this.target = newStr.join(\"\");\n }", "function correctArrayReplacement(arrKey, arrCorrect, guess){\n for(i=0; i<=arrKey.length; i++){\n if(arrKey[i]==guess){\n arrCorrect.splice(i, 1, guess)\n };\n }\n document.getElementById(\"current\").innerHTML = arrCorrect;\n }", "function swapPairs(arr){\n var temp;\n for (var i =0; i < arr.length; i+=2){\n if((arr.length-1) - i > 1){\n temp = arr[i];\n arr[i] = arr[i+1];\n arr[i+1]= temp;\n }\n }\n return arr;\n\n}", "swapLetters( x, y, oppositeDay ) {\n var str = this.target;\n var newStr = [];\n if (oppositeDay) {\n [x,y]=[y,x];\n }\n\n for (var i = 0; i < str.length; i++) {\n if (str[i] === x) {\n newStr.push( y );\n } else if (str[i] === y) {\n newStr.push( x );\n } else {\n newStr.push( str[i] );\n }\n }\n this.target = newStr.join(\"\");\n }", "function swapPairs(arr){\n for (index = 0; index < arr.length-1; index+=2){\n var currentValue = arr[index];\n arr[index] = arr[index+1];\n arr[index+1] = currentValue;\n }\n return arr;\n}", "function swap(array, i, j) {\r\n let swapVar;\r\n swapVar = array[i];\r\n array[i] = array[j];\r\n array[j] = swapVar;\r\n return array;\r\n }", "function reverseArrayReplace(array) {\n var midpoint = (array.length / 2) - 1; \n\n for (var i = 0; i <= midpoint; i++) {\n var temp;\n temp = array[i];\n array[i] = array[array.length - 1 - i];\n array[array.length - 1 - i] = temp; \n }\n\n return array;\n}", "function swap(array, a, b) {\n let temp = array[b];\n array[b] = array[a]\n array[a] = temp\n}", "function swap( arr, exceptions ) {\r\n\tvar i;\r\n\tvar except = exceptions ? exceptions : [];\r\n\tvar shufflelocations = new Array();\r\n\tfor (i=0; i<arr.length; i++) {\r\n\t\tif (except.indexOf(i)==-1) shufflelocations.push(i);\r\n\t}\r\n\r\n\tfor (i=shufflelocations.length-1; i>=0; --i) {\r\n\t\tvar loci = shufflelocations[i];\r\n\t\tvar locj = shufflelocations[randrange(0,i+1)];\r\n\t\tvar tempi = arr[loci];\r\n\t\tvar tempj = arr[locj];\r\n\t\tarr[loci] = tempj;\r\n\t\tarr[locj] = tempi;\r\n\t}\r\n\treturn arr;\r\n}", "function changeWinners(winnersArray) {\n winnersArray[0] = 'xyz'\n winnersArray[1] = 'pqr'\n winnersArray[2] = 'jkl'\n}", "function swap(arr){\n for(var i=0;i<arr.length;i++){\n if(arr[i]<0){\n arr[i]='Dojo'\n }\n }\n return arr;\n}", "function swap(arr, i, j){\n\thold = arr[i];\n\tarr[i]=arr[j];\n\tarr[j]=hold;\n\treturn arr\n}", "function swap(array, i, j) {\n var temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n}", "function swap(array, i, j) {\n var temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n}", "function swap(arr,first,second){\n if(first == second){\n return;\n }\n var temp = arr[first];\n arr[first] = arr[second];\n arr[second] = temp;\n}", "function swap(array, i, j){\n const temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n}", "function shiftToLeft(arr, ind){\n if(arr.length >= 3 && arr[ind+1] && arr[ind+2]){\n var temp1 = arr[ind+1];\n var temp2 = arr[ind+2];\n arr[ind+2] = arr[ind];\n arr[ind+1] = temp2;\n arr[ind] = temp1;\n return arr;\n }else{\n console.log(\"out of bounds\");\n }\n}", "function myArrayFunction(myPets){\n var myNewPets = [...myPets];\n // only change code below this line\n myNewPets.push(\"Bird\", \"Fish\");\n var firstPet = myNewPets;\n firstPet.shift();\n var lastPet = myNewPets;\n lastPet.pop();\n myNewPets.unshift(\"Lion\");\n return myNewPets\n // Only change code above this line\n}", "function shift(array, k){\n let tempOne = 0;\n let tempTwo = 0;\n for(let i = 0; i < 1; i++){\n if(array.length < 2){\n return false;\n }\n tempOne = array[0]; // 0 = 1\n array[0] = array[array.length - 1]; // 1 = 4\n array[array.length - 1] = tempOne; \n }\n return array;\n}", "function swapPairs(arr){\n for (var i = 0; i < arr.length-1; i+=2) { \n var temp = arr[i]\n arr[i] = arr[i+1]\n arr[i+1] = temp\n }\n}", "function swapValue(currentIndex, smallestIndex, array) {\n // get currentIndex value\n let currentIndexValue = array[currentIndex];\n array[currentIndex] = array[smallestIndex];\n array[smallestIndex] = currentIndexValue;\n return array;\n}", "function swap(array, i, low) {\n var temp = array[i];\n array[i] = array[low];\n array[low] = temp;\n}", "function reverseArr(arr) {\nvar mid = Math.floor(arr.length/2); //cut in half to find the point where we stop swapping chars\nlet front = \"\"; //this is the char from the front of the list\nlet back = \"\"; //and the char from the back of the list\nfor (let i = 0; i < mid; i++){ //for each letter from the front and its pair from the back\n front = arr[i] //assign the \"front\" char\n back = arr[arr.length-(i+1)] //assign the \"back\" char (i+1 bc otherwise it is one number off, index wise)\n console.log(arr.length-(i+1))\n console.log(arr[i])\n console.log(arr[arr.length-(i+1)])\n arr[i] = back; //swap them\n arr[arr.length-(i+1)] = front; //swap\n console.log(arr)\n}\nreturn arr\nconsole.log(arr)\n}", "function swap(arr){\n var num=arr[0];\n var num2=arr[arr.length-1];\n arr[0]=num2;\n arr[arr.length-1]=num; \n return arr; \n}", "function oddSwap(arr) {\n\ttemp = null;\n\n\tfor(var num = 0; num < Math.floor(arr.length/2); num++) {\n\t\tif (num % 2 == 0) {\n\t\t\ttemp = arr[num];\n\t\t\tarr[num] = arr[(arr.length) - 1 - num];\n\t\t\tarr[(arr.length) - 1 - num] = temp;\n\t\t}\n\t}\n\tconsole.log(arr);\n\treturn arr;\n}", "function swapPairs(arr){\n for(var i = 0; i < arr.length-1; i +=2){\n var temp = arr[i];\n arr[i] = arr[i+1];\n arr[i+1] = temp;\n }\n return arr\n}", "function larrysArray(A) {\r\n\r\n // Count the number of swaps needed to sort the array using an insertion sort\r\n function getSwapCount(a) {\r\n var swaps = 0;\r\n // Iterate through the array from 0 to n-1\r\n for (var i = 0; i < a.length-1; i++) {\r\n // Iterate through the array from 1 to n\r\n for (var j = i + 1; j < a.length; j++) {\r\n // If there would be a swap then add 1\r\n swaps += (a[i] > a[j]) ? 1 : 0;\r\n // console.log(\"swaps\", swaps, \"ai\", a[i], \"aj\", a[j]);\r\n }\r\n }\r\n return swaps;\r\n }\r\n\r\n // Get the number of swaps\r\n var numSwaps = getSwapCount(A);\r\n // console.log(numSwaps);\r\n // If the number of swaps is even then the array is sortable using Larry's sort\r\n // otherwise it is not\r\n return ((numSwaps % 2) === 0) ? \"YES\" : \"NO\";\r\n\r\n}", "function swap(arr, a, b) {\r\n let temp = arr[a];\r\n arr[a] = arr[b];\r\n arr[b] = temp;\r\n}", "function hungry(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] = \"food\") {\n arr[i] = \"yummy\";\n }\n else (arr[i] = \"I'm hungry\");\n }\n}", "function setup() {\n for (var i = 0; i < arr.length - 1; i++)\n {\n var index = i;\n for (var j = i + 1; j < arr.length; j++)\n if (arr[j] < arr[index])\n index = j;\n \t\t // Swapping Code\n var smallerNumber = arr[index];\n arr[index] = arr[i];\n arr[i] = smallerNumber;\n }\n}", "function swapArray(array, num1, num2){\n let temp = array[num1];\n array[num1] = array[num2];\n array[num2] = temp;\n}", "function fixTheMeerkat(arr) {\n return arr.reverse()\n}", "function swap(input){\n\t\t//your code is here\n\t\tvar str = ''\n\t\tfor(var i = 0; i < input.length;i++){\n\t\t\tif(input[i] === input[i].toUpperCase()){\n\t\t\tstr = str + input.slice(i, i+1).toLowerCase()\n\t\t}\telse if(input[i] === input[i].toLowerCase()){\n\t\t\tstr = str + input.slice(i, i+1).toUpperCase()\n\t\t}\n\t\t}\n\t\treturn str\n\t}", "function arraySwapPairs(arr) {\n\tfor(var i = 0; i < arr.length -1; i += 2) {\n\t\tvar temp = arr[i];\n\t\tarr[i] = arr[i + 1];\n\t\tarr[i + 1] = temp;\n\t}\n\treturn arr;\n}", "function swap(){\n var str = document.getElementById(\"demo3\").value;\n \nvar UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';\nvar LOWER = 'abcdefghijklmnopqrstuvwxyz';\nvar result = [];\n \n for(var x=0; x<str.length; x++)\n {\n if(UPPER.indexOf(str[x]) !== -1)\n {\n result.push(str[x].toLowerCase());\n }\n else if(LOWER.indexOf(str[x]) !== -1)\n {\n result.push(str[x].toUpperCase());\n }\n else \n {\n result.push(str[x]);\n }\n }\n\ndocument.getElementById(\"ans3\").innerHTML = result.join('');\n}", "function swap(arr, i, j) {\n console.log(i, j)\n let temp = arr[i]\n arr[i] = arr[j]\n arr[j] = temp\n return arr\n}", "function swap(i, unorderedArray) {\n [unorderedArray[i], unorderedArray[i + 1]] = [unorderedArray[i + 1], unorderedArray[i]];\n return unorderedArray;\n}", "function swapPair(arr){\n for(var i=0; i<arr.length/2; i+=2){\n if(i+1>arr.length){\n break\n }else{\n var temp = arr[i]\n arr[i] = arr[i+1]\n arr[i+1] = temp\n }\n }\n return arr\n}", "function swap(arr, i, j) {\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n}", "function swap(array, firstElement, secondElement){\n let temp = array[firstElement];\n array[firstElement] = array[secondElement];\n array[secondElement] = temp;\n}", "function swap (arr, i, j){\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n}", "function swap(array, i, j) {\n quickCounter++;\n const tmp = array[i];\n array[i] = array[j];\n array[j] = tmp;\n}", "function swap( arr, posA, posB ) {\n var temp = arr[posA];\n arr[posA] = arr[posB];\n arr[posB] = temp;\n}", "function swapString(arr) {\n for (var i = 0; i < arr.length; i++) {\n if (arr[i] < 0) {\n arr[i] = 'Negative Value'\n }\n }\n return arr\n}", "function swap(array, i, j) {\n\tlet temp = array[i];\n\tarray[i] = array[j];\n\tarray[j] = temp;\n}", "function swap(array, i, j) {\n\tlet temp = array[i];\n\tarray[i] = array[j];\n\tarray[j] = temp;\n}", "function arrSwap(xarr) {\n for(var i=0; i < Math.ceil(xarr.length/2)-1; i++) {\n var x = xarr[i];\n xarr[i]= xarr[xarr.length-i-1];\n xarr[xarr.length-i-1] = x;\n // console.log(xarr[i]);\n // console.log(xarr[Math.ceil(xarr.length/2)-i-1])\n }\n return xarr;\n}", "function swap_pairs(arr) {\n\tfor(var i = 0; i < arr.length -1; i += 2) {\n\t\tx = arr[i]\n\t\tarr[i] = arr[i + 1]\n\t\tarr[i + 1] = x\n\t}\n\tconsole.log(arr);\n}", "function myArrayFunction(arr) {\n var myNewPets = [...arr];\n myNewPets.push(\"Bird\", \"Fish\");\n myNewPets.pop(\"Fish\");\n myNewPets.shift(\"Dog\");\n myNewPets.unshift(\"Lion\");\n console.log(myNewPets);\n}", "function switchTiles(array) {\n var i = 0;\n\n // find the first two tiles in a row\n while (!array[i] || !array[i+1]) i++;\n\n // store tile value\n var tile = array[i];\n // switche values\n array[i] = array[i+1];\n array[i+1] = tile;\n\n return array;\n }", "function task14_16_13(){\n var arr = [];\n arr.unshift(\"keyboard\");\n arr.unshift(\"mouse\");\n arr.unshift(\"printer\");\n arr.unshift(\"monitor\");\n document.write(\" TOTAL \");\n document.write(\"<br>\");\n document.write(\"Array : \" + arr);\n\n document.write(\"<br>\");\n document.write(\" Removal \");\n document.write(\"<br>\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"keyboard\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"mouse\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"printer\");\n document.write(\"Array : \" + arr);\n document.write(\"<br>\");\n arr.shift(\"monitor\");\n document.write(\"<br>\");\n}", "function swap(arr, i, j) {\n var temp = arr[i];\n arr[i] = arr[j];\n arr[j] = temp;\n}", "function changeArr(arr){\n arr[7] = 'right';\n}", "function annaMap(array, changer) {\n for (let i=0; i<array.length; i++){\n array[i] = changer(array[i]);\n }\n return array;\n}" ]
[ "0.70972925", "0.70154864", "0.6949087", "0.69107425", "0.6877324", "0.67917246", "0.67323375", "0.6472604", "0.6374284", "0.591377", "0.58495134", "0.5780375", "0.5715417", "0.5709263", "0.56621486", "0.56514484", "0.5635146", "0.56259626", "0.5623789", "0.561269", "0.5592371", "0.5583098", "0.5583098", "0.556699", "0.55640435", "0.5562776", "0.555841", "0.5545751", "0.55277586", "0.552468", "0.5504735", "0.54996914", "0.5484214", "0.5471859", "0.54132307", "0.54014564", "0.5387812", "0.5381881", "0.5378567", "0.53610367", "0.53580785", "0.5345912", "0.53437763", "0.53398526", "0.5338797", "0.5336346", "0.53340936", "0.5332155", "0.5321573", "0.5311425", "0.5308657", "0.5303911", "0.52944416", "0.5294388", "0.5291933", "0.5287421", "0.5279611", "0.52717173", "0.5265753", "0.5265753", "0.526435", "0.52626336", "0.525287", "0.5246002", "0.5244804", "0.5233929", "0.52320695", "0.52303845", "0.5222671", "0.5219554", "0.5218048", "0.5216561", "0.5215977", "0.52156985", "0.5214503", "0.5213483", "0.52112544", "0.5210894", "0.5201234", "0.5201027", "0.52002656", "0.5199241", "0.51960856", "0.51936114", "0.51865053", "0.51850563", "0.5178991", "0.51691484", "0.5167048", "0.516343", "0.51624274", "0.51624274", "0.5156551", "0.5154996", "0.514608", "0.5145273", "0.51426035", "0.51406157", "0.5139914", "0.51352215" ]
0.67549497
6
swapTowardCenter([true,42,"Ada",2,"pizza"]); swapTowardCenter([1,2,3,4,5,6]); Challenge 14 Scale the Array Given an array arr and a number num, multiply all values in the array arr by the number num, and return the changed array arr. For example, scaleArray([1,2,3], 3) should return [3,6,9].
function scaleArray(arr, num) { for(var i = 0; i < arr.length; i++) { arr[i] = arr[i] * num; } return arr; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function scaleArrayReplace(array, numToScale) {\n for (var i in array) {\n array[i] = array[i] * numToScale;\n }\n return array;\n}", "function scaleArr(arr) {\n\n for (var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * num;\n }\n return arr;\n}", "function scaleArray(arr,num){\n for( var i=0;i<arr.length;i++){\n arr[i]=arr[i]*num;\n }\n return arr;\n}", "function ScaleA(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num;\n }\n console.log(arr);\n}", "function scaleArray(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] *= num\n }\n return arr\n}", "function scaleArray(arr, num){\n for(let i = 0; i<arr.length; i++){\n arr[i] = arr[i]*num\n }\n return arr\n}", "function scale(arr, num){\n for (var i = 0; i < arr.length; i++){\n arr[i] *= num;\n }\n return arr;\n}", "function scaleArr(arr, num){\n for(var i = 0; i < arr.length; i++)\n arr[i] *= num;\n return arr;\n}", "function scale(arr,num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num\n }\n console.log(arr)\n}", "function scaleTheArray(arr, num) {\n for (var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * num;\n }\n return arr;\n}", "function scaleArr(arr, num){\n return arr.map(x => x * num)\n}", "function scaleArray(arr, num){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * num;\n }\n return arr;\n}", "function scaleArray(arr,num){\n\n\tfor (var i = 0; i < arr.length; i++) {\n\t\tarr[i] = arr[i] * num;\n\t}\n\tconsole.log(arr)\n}", "function scalethearray(arr,y){\n for(var i=0;i<arr.length;i++){\n arr[i]=arr[i]*y\n }\n return arr;\n}", "setScale(key) {\n //swaps accidentals between flats and sharps\n let notes\n if (key === \"F\" || key === \"F m\") {\n let scale = [\"F\", \"G\", \"A\", \"Bb\", \"C\", \"D\", \"E\"]\n return scale\n } else if (key.split(\"\").includes(\"b\")) {\n notes = [\"A\", \"Bb\", \"B\", \"C\", \"Db\", \"D\", \"Eb\", \"E\", \"F\", \"Gb\", \"G\", \"Ab\"]\n } else {\n notes = [\"A\", \"A#\", \"B\", \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\"]\n }\n\n //rotates array until the chosen key is the first element\n \n\n if (key.split(\"\").includes(\"m\")) {\n let baseKey\n if (key.length === 4) {\n baseKey = key.slice(0, 2)\n } else {\n baseKey = key.slice(0, 1)\n }\n \n while (baseKey !== notes[0]) {\n notes.push(notes.shift())\n }\n } else {\n while (key !== notes[0]) {\n notes.push(notes.shift())\n }\n }\n //pulls out notes in selected key to build scale.\n let scale = []\n scale.push(notes[0])\n scale.push(notes[2])\n scale.push(notes[4])\n scale.push(notes[5])\n scale.push(notes[7])\n scale.push(notes[9])\n scale.push(notes[11])\n\n if (key.split(\"\").includes(\"m\")) {\n for (let i = 0; i < 5; i++) {\n scale.push(scale.shift())\n }\n }\n\n return scale\n }", "function scale(array){\n assessmentScale.total=0;\n assessmentScale.satisfactory=0;\n assessmentScale.developing=0;\n assessmentScale.unsatisfactory=0;\n\n for(var i=0; i<=array.length-1;i++){\n switch(array[i]){\n case \"A\":\n assessmentScale.satisfactory++;\n assessmentScale.total++;\n break;\n case \"B\":\n assessmentScale.satisfactory++;\n assessmentScale.total++;\n break;\n case \"C\":\n assessmentScale.developing++;\n assessmentScale.total++;\n break;\n case \"D\":\n assessmentScale.unsatisfactory++;\n assessmentScale.total++;\n break;\n case \"F\":\n assessmentScale.unsatisfactory++;\n assessmentScale.total++;\n break;\n }\n }\n}//end of scale function.", "function squares(arr){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i]*arr[i];\n }\n return arr;\n}", "function func9(inputArray){\n for(var i=0; i<inputArray.length; i++){\n inputArray[i]*=inputArray[i];\n }\n return inputArray;\n}", "scale(s) {\r\n this.forEach((x, i, a) => a[i] *= s);\r\n }", "function swapTowardsCenter(arr){\n for(var i = 0; i < arr.length/2; i+=2){\n var temp = arr[i]\n arr[i] = arr[arr.length - 1 - i]\n arr[arr.length - 1 - i] = temp\n }\n return arr\n}", "function swaptoCenter(arr){\n let temp\n for (let i = 0; i < Math.floor(arr.length/2); i++){\n temp = arr[i];\n arr[i] = arr[arr.length-i-1];\n arr[arr.length-i-1] = temp;\n }\n return arr\n}", "function swapTowardCenter(arr){\n for (let i = 0; i < arr.length/2; i++) {\n var temporaryVarForSwitchingIndex = arr[i]\n arr[i] = arr[arr.length - 1-i] \n arr[arr.length - 1-i] = temporaryVarForSwitchingIndex \n \n }\n return arr \n}", "function CenterSwap(arr) {\n\tfor (var i = 0; i <=arr.length/2; i++) {\n\t\tvar temp=arr[i];\n\t\tarr[i]= arr[arr.length-1-i]\n\t\tarr[arr.length-1-i]=temp;\n\t}\n\treturn arr;\n}", "static scale(dst, src, x, y) {\n dst[0] = x * src[0];\n dst[1] = x * src[1];\n dst[2] = x * src[2];\n\n dst[3] = y * src[3];\n dst[4] = y * src[4];\n dst[5] = y * src[5];\n\n dst[6] = src[6];\n dst[7] = src[7];\n dst[8] = src[8];\n return dst;\n }", "function scale(x,y) {\n matrix[0] *= x;\n matrix[1] *= x;\n matrix[2] *= y;\n matrix[3] *= y;\n }", "function squares(array) {\n for (let i = 0; i < array.length; i++) {\n array[i] = array[i] * array[i];\n \n }\n return array;\n}", "function swapTowardCenter(arr){\n var temp;\n for(var i = 0 ; i < arr.length/2; i+=2){\n temp = arr[i];\n arr[i] = arr[arr.length-1-i];\n arr[arr.length-1-i] = temp;\n }\n return arr;\n}", "function square(arr){\n for(var i=0; i<arr.length;i++){ \n arr[i]=arr[i]*arr[i]; \n } \n return arr;\n}", "function squareIt() {\n\tfor (i = 0; i < oldArray.length; i++) {\n\t\tnewArray.push(oldArray[i] * oldArray[i]);\n\t}\n}", "function swapTowardsTheCenter(arr) {\n var len = arr.length;\n var idx = 0;\n var lastIdx = arr.length - 1;\n while (idx <= len / 2 && lastIdx >= len / 2) {\n var temp = arr[idx];\n arr[idx] = arr[lastIdx];\n arr[lastIdx] = temp;\n idx = idx + 2;\n lastIdx = lastIdx - 2;\n }\n return arr;\n}", "function squareTheValues(arr){\n for (let i=0;i<arr.length;i++){\n arr[i] = arr[i] * arr[i];\n }\n return arr;\n}", "function squaresarr(arr)\r\n{\r\n\tfor(var i=0;i<arr.length;i++)\r\n\t{\r\n\t\tarr[i]=arr[i]*arr[i];\r\n\r\n\t}\r\n\r\n\tconsole.log(\"Squaing values\",arr);\r\n}", "function arraySquare(arr) {\n arr = [1,1,117]\n for(var x = 0; x < arr.length; x++){\n arr[x] = arr[x] * arr[x];\n }\n return arr;\n // console.log(arr);\n}", "function multiplyByTwo(arr) {\n arr = arr.map(function (a) {\n return a*2;\n })\n return arr;\n}", "function squares(arr) {\n for (var idx = 0; idx < arr.length; idx++) {\n arr[idx] = arr[idx] * arr[idx];\n }\n console.log(arr);\n}", "function square(arr){\n for(let i = 0; i < arr.length; i++){\n arr[i] *= arr[i]\n }\n}", "function multiplies10(arr){\n return arr.map(mul10);\n }", "function vecScale(x, c) {\n for (var i = 0; i < x.length; i++) {\n x[i] *= c;\n };\n return x;\n}", "static setScaleV3(xyz, s) {\nxyz[0] *= s;\nxyz[1] *= s;\nxyz[2] *= s;\nreturn xyz;\n}", "function swapTowardCenter(arr){\n var temp;\n var count = arr.length -1;\n\n for(var i = 0; i < arr.length; i++){\n if(i == 0){\n temp = arr[0];\n arr[0] = arr[count];\n arr[count] = temp;\n count += 2;\n } else if ((i < arr.length/2) && (i % 2 == 0)){\n temp = arr[i];\n arr[i] = arr[count];\n arr[count] = temp;\n count += 2;\n }\n }\n\n return arr;\n}", "function scaleShape() {\n \"use strict\";\n var tempx;\n var tempy;\n setUnitMatrixT();\n tempx = window.prompt(\"Enter Scale in X\");\n tempy = window.prompt(\"Enter Scale in Y\");\n newTransform[0][0] = Number(tempx);\n newTransform[1][1] = Number(tempy);\n document.getElementById(\"updates\").innerHTML += \"You entered Scale \" + newTransform[0][0] + \" in X\" + \"<br>\" + \"You entered Scale \" + newTransform[1][1] + \" in Y\" + \"<br>\";\n reDraw();\n}", "function nine(arr){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i] * arr[i]; \n }\n return arr;\n}", "function squareArrayVals(arr){\n for(var i = 0; i < arr.length; i++){\n arr[i] = (arr[i] * arr[i])\n }\n return arr\n}", "function swapTowardCenter(arr) {\n for (var i = 0; i < arr.length / 2; i = i + 2) {\n var temp = arr[i];\n arr[i] = arr[arr.length - (i + 1)];\n arr[arr.length - (i + 1)] = temp;\n }\n console.log(arr);\n}", "function swapTowardCenter(arr){\n for(var i = 0; i < arr.length/2; i+=2) {\n var temp = arr[i];\n arr[i] = arr[arr.length - 1 - i];\n arr[arr.length - 1 - i] = temp;\n }\n console.log(arr);\n }", "function SQuaresSquared(arr){\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i]*arr[i];\n }\n return arr;\n}", "function scaleValue(value){\n //Assuming army size is between \n}", "function sortAndMulti(array, multiplier) {\n\n newArray = [];\n\n for (var i = 0; i < array.length -1; i++) {\n var minIndex = i;\n var tempElementToSwap;\n\n for (var j = i; j < array.length; j++) {\n var elementToCompareTo = array[i];\n\n if (elementToCompareTo < array[minIndex]) {\n minIndex = j;\n }\n }\n\n tempElementToSwap = array[i];\n array[i] = array[minIndex];\n array[minIndex] = tempElementToSwap;\n }\n\n for (var k = 0; k < array.length; k++) {\n newArray[k] = array[k] * multiplier;\n }\n\n return newArray;\n}", "function arrayMultiplyAgain(num, arr) {\n const newArr = arr.map(item => item * num)\n return newArr\n}", "function squareVal(arr) {\n for(var i = 0; i < arr.length; i++) {\n arr[i] = arr[i] * arr[i];\n }\n return arr; \n}", "function multiplier(array) {\n\treturn array.reduce((acc, cur) => acc * cur);\n}", "function modifyArray(nums) {\n nums = nums.map((num) => (num % 2 == 1 ? 3 : 2 ) * num);\n return nums;\n}", "function getmultiplied(arr)\r\n{\r\n for (let i = 0; i < arr.length; i++)\r\n arr[i]=arr[i]*2\r\n return arr;\r\n}", "function p9(){\n var arr = [1,2,4,7,33,55,66,88]\n for(var i = 0; i < arr.length; i++){\n arr[i] = arr[i]*arr[i]\n }\n console.log(arr)\n}", "function doubleVision(array){\n let newArr = [];\n for(let i = 0; i < array.length; i++){\n newArr.push(array[i] * 2);\n }\n array = newArr;\n return array;\n}", "function scale(){\nalert(\"Map scales are linear meaning they give a relationship between distance on a map and the actual distance on the ground. Scale can be given in various ways eg 1cm to represent 50m can be given as 1cm:50m or 1:5000 or 1cm:5000cm or 1/5000.\");\nalert(\"The map scale with components reduced to the same basic unit is called REPRESENTATIVE FRACTION(RF). Always remember that RF=distance on the map/distance on the ground eg Given that the scale of a map is 1cm:2km, then RF=1/200 000 ie 2km has been changed to cm.\");\nalert(\"The scale of the area represented by the map can be derived from the linear scale.The scale of the area is the square of the linear scale eg Given that the scale of a map is 1cm:2.5km the area scale is (1cm×1cm):(2.5km×2.5km)=1cm²:6.25km².\");\nalert(\"Lets do some examples on scale.\");\nalert(\"Find the area scale given that the linear scale is 1:250.ANSWER: Area scale=linear scale²= 1×1:250×250=1:62500.\");\nalert(\"What is the RF of the scale 1cm:3km?ANSWER:RF=1/3×1000=1/3000(3km has been changed to cm)\");\nalert(\"The scale of a map is given as 1:150 000, find the distance in km on the ground represented by 2cm on the map.ANSWER:Lets use simple proportion ie 1cm:150 000cm, so 2cm:x, cross multiplying 1 × x=2×150 000, x= (2× 150 000)/1, x=300 000cm hence 2cm on the map represent 300 000cm on the ground which is 300 000/100 000=3km.(note that 1km=100 000cm).\");\n}", "function scaleCoord() {\r\n\r\n coord[0] = coordOG[0];\r\n coord[1] = coordOG[1];\r\n\r\n var minX = getMin(x);\r\n var minY = getMin(y);\r\n\r\n var scale = mapScale;\r\n\r\n //turn everything positive\r\n if(minX < 0){\r\n coord[0]+=Math.abs(minX);\r\n }\r\n if(minY < 0){\r\n coord[1]+=Math.abs(minY);\r\n }\r\n\r\n coord[0] *= scale;\r\n coord[1] *= scale;\r\n coord[1] = 800 - coord[1];\r\n\r\n\r\n coord[0] += xShift;\r\n coord[1] -= yShift;\r\n\r\n}", "function double(arr){\n for (i=0; i<arr.length; i++){\n arr[i] = arr[i]*2\n }\n return arr\n}", "scale(vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale(vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale(vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale(vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale(vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "function scale( s, v1 ) { return [ s * v1[0], s * v1[1], s * v1[2] ]; }", "move() {\n console.log(this.scale);\n var self = this; // vat that = this; var _this = this;\n this.numbers = this.numbers.map(function(element){\n return element * self.scale;\n })\n }", "scale (vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale (vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale (vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "scale (vec, m) {\n return [vec[0] * m, vec[1] * m];\n }", "function swapTowardCenter(array) {\n var midpoint = array.length / 2;\n\n console.log(\"midpoint: \" + midpoint);\n for (var i = 0; i < midpoint; i++) {\n if (i % 2 === 0) { // Even index found, swap this, matching end index \n console.log(i);\n var temp = array[i]; \n array[i] = array[array.length -1 - i];\n array[array.length -1 - i] = temp;\n console.log(array);\n }\n }\n \n return array;\n}", "scale(sx, sy, sz){\n let e = this.elements;\n e[0] *= sx; e[4] *= sy; e[8] *= sz;\n e[1] *= sx; e[5] *= sy; e[9] *= sz;\n e[2] *= sx; e[6] *= sy; e[10] *= sz;\n e[3] *= sx; e[7] *= sy; e[11] *= sz;\n return this;\n }", "function multiplyBy2(arr) {\n return arr.map((item) => item * 2) // new array is created from map.\n\n}", "function squareNums(numbers) {\n\n numbers = numbers.map(num => num * num);\n return numbers;\n}", "function doubleVision(array){\n for(var i=0;i<array.length;i++){\n array[i] = array[i] * 2;\n console.log(array[i]);\n }\n\n}", "setScale(sx, sy, sz){\n let e = this.elements;\n e[0] = sx; e[4] = 0; e[8] = 0; e[12] = 0;\n e[1] = 0; e[5] = sy; e[9] = 0; e[13] = 0;\n e[2] = 0; e[6] = 0; e[10] = sz; e[14] = 0;\n e[3] = 0; e[7] = 0; e[11] = 0; e[15] = 1;\n return this;\n }", "function sta(arr, num){\n for(e in arr){\n arr[e] = arr[e]*num;\n }\n return arr;\n}", "function scaleVectors(scale, vectorsX, vectorsY) {\n const length = vectorsX.length;\n for (let i = 0; i < length; i++) {\n vectorsX[i] *= scale;\n vectorsY[i] *= scale;\n }\n}", "function update (arr, start, end) {\n\t\tif (typeof arr === 'number' || arr == null) {\n\t\t\tend = start;\n\t\t\tstart = arr;\n\t\t\tarr = null;\n\t\t}\n\t\t//update array, if passed one\n\t\telse {\n\t\t\tif (arr.length == null) throw Error('New data should be array[ish]')\n\n\t\t\t//reset lengths if new data is smaller\n\t\t\tif (arr.length < scales[0].length) {\n\t\t\t\tfor (let group = 2, idx = 1; group <= maxScale; group*=2, idx++) {\n\t\t\t\t\tlet len = Math.ceil(arr.length/group);\n\t\t\t\t\tscales[idx].length = len;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tscales[0] = arr;\n\t\t}\n\n\t\tif (start == null) start = 0;\n\t\tif (end == null) end = scales[0].length;\n\n\t\tstart = nidx(start, scales[0].length);\n\t\tend = nidx(end, scales[0].length);\n\n\t\tfor (let group = 2, idx = 1; group <= maxScale; group*=2, idx++) {\n\t\t\tlet scaleBuffer = scales[idx];\n\t\t\tlet prevScaleBuffer = scales[idx - 1];\n\t\t\tlet len = Math.ceil(end/group);\n\n\t\t\t//ensure size\n\t\t\tif (scaleBuffer.length < len) scaleBuffer.length = len;\n\n\t\t\tlet groupStart = Math.floor(start/group);\n\n\t\t\tfor (let i = groupStart; i < len; i++) {\n\t\t\t\tlet left = prevScaleBuffer[i*2];\n\t\t\t\tif (left === undefined) left = 0;\n\t\t\t\tlet right = prevScaleBuffer[i*2+1];\n\t\t\t\tif (right === undefined) right = left;\n\t\t\t\tscaleBuffer[i] = reduce(left, right, i*2, idx-1);\n\t\t\t}\n\t\t}\n\n\t\treturn scales;\n\t}", "function squareDance (arr) {\n var newArr = []\n for (var i = 0; i < arr.length; i++) {\n newArr[i] = arr[i] * arr[i]\n }\n return newArr\n}", "function modifyArray(nums) {\n \n var arr = nums.map(a => (a%2 == 0 ? a*2 : a*3));\n \n return arr;\n}", "function scaleAll2(newScale){\r\n if(newScale>MIN_SCALE && newScale<MAX_SCALE){\r\n canvas.forEachObject(function(item, index, arry){\r\n if(!item.isTag){\r\n item.scale(newScale);\r\n if(item != fabImg){\r\n //When scaling move element so that distance of elements for center is always in portion wiht scale\r\n var x = ((item.getLeft() - AnnotationTool.originX)/AnnotationTool.SCALE) * newScale + AnnotationTool.originX;\r\n var y = ((item.getTop() - AnnotationTool.originY)/AnnotationTool.SCALE) * newScale + AnnotationTool.originY;\r\n if(item.elementObj){\r\n item.elementObj.setItemPos(x, y, newScale);\r\n }\r\n }\r\n \r\n }\r\n });\r\n canvas.renderAll();\r\n AnnotationTool.SCALE = newScale;\r\n }\r\n }", "function multiplyArray(arr, multiplier) {\n\tvar temp = [];\n\tfor (var i = 0; i < arr.length; ++i) {\n\t\ttemp[i] = arr[i] * multiplier;\n\t}\n\treturn temp;\n}", "function transform(pointArray){\n\t\t//scale points\n\t\tpointArray.forEach(function(point){\n\t\t\treturn scale(point);\n\t\t});\n\t\t//shift points from (0,0) origin to (100,300)\n\t\tpointArray.forEach(function(point){\n\t\t\treturn shift(point);\n\t\t});\n\t\t//converts the list to string\n\t\treturn pointArray.reduce(function(p,c){\n\t\t\treturn convertToString(p,c);\n\t\t},\"\");\t\n\t}", "function scale(scale)\n{\n // Loop through each value pair\n for (var i = 0, size = positions.length; i < size; i+=2)\n {\n // Get x and y coordinates\n var x = positions[i];\n var y = positions[i+1];\n\n // Multiply x and y valu by scale value\n x += x * scale;\n y += y * scale;\n\n // Set position values\n positions[i] = x;\n positions[i+1] = y;\n }\n\n // Redraw the image\n loadImage();\n}", "function squareTheValues(inputArray) {\n\tinputArray.map(element => {\n\t\tconsole.log(element * element);\n\t});\n}", "function planeScale(pointsArray, plane, scaleFactor) {\n\n\n\tif (scaleFactor == undefined) {\n\t\tscaleFactor = 1.5;\n\t};\n\n\n\tfor (i=0 ; i<pointsArray.length ; i++) {\n\n\t\tlet projectedPoint = plane.projectPoint(pointsArray[i], new THREE.Vector3());\n\n\n\t\tlet xFactor = (projectedPoint[\"x\"] - pointsArray[i][\"x\"]) ;\n\t\tlet yFactor = (projectedPoint[\"y\"] - pointsArray[i][\"y\"]) ;\n\t\tlet zFactor = (projectedPoint[\"z\"] - pointsArray[i][\"z\"]) ;\n\n\t\tpointsArray[i][\"x\"] = projectedPoint[\"x\"] - (xFactor * scaleFactor);\n\t\tpointsArray[i][\"y\"] = projectedPoint[\"y\"] - (yFactor * scaleFactor);\n\t\tpointsArray[i][\"z\"] = projectedPoint[\"z\"] - (zFactor * scaleFactor);\n\t\n\t};\n\n}", "function improved(array) {\n var prev = new Array(array.length);\n var next = new Array(array.length);\n\n var prev_index = 0;\n addPrevious(prev, array);\n addNext(next, array);\n\n array = multiply(prev, next);\n console.log(array);\n}", "function multiplyPosition(arr){\n var newArr = [];\n for(var i = 0; i < arr.length; i++){\n newArr.push(arr[i] = arr[i] * i); \n };\n console.log(newArr); \n}", "function rescale(x, a,b, c,d) {\n if (abs(a-b) < 1e-7) return x <= (a+b)/2 ? c : d // avoid division by 0\n return c + (x-a)/(b-a)*(d-c)\n}", "function multiplyArray(factor, a) {\n\t\tvar i;\n\t\tfor (i = 0; i < a.length; i++) {\n\t\t\ta[i] *= factor;\n\t\t}\n\t\treturn a;\n\t}", "function multiplyArray(factor, a) {\n\t\tvar i;\n\t\tfor (i = 0; i < a.length; i++) {\n\t\t\ta[i] *= factor;\n\t\t}\n\t\treturn a;\n\t}", "function multiplyArray(factor, a) {\n\t\tvar i;\n\t\tfor (i = 0; i < a.length; i++) {\n\t\t\ta[i] *= factor;\n\t\t}\n\t\treturn a;\n\t}", "function multiplyArray (arr, multiplier) {\n var i = 0;\n while (i < arr.length) {\n if (arr[i] > 1){\n arr.splice(arr.length, 0, 1);\n }\n arr[i]*=multiplier;\n i++;\n console.log(arr);\n }\n return arr;\n}", "function squareArrVals(arr) {\n for (var idx = 0; idx < arr.length; idx++) {\n arr[idx] = arr[idx] * arr[idx];\n }\n return arr;\n}", "function square(array){\n for (var i = 0; i < 3; i++){ // 3 or constant\n array[i] = array[i] * array[i]; // 1\n }\n return array; // 1\n}", "function manualProductArray(arr) {\n const newArray = [];\n newArray.push(arr[1] * arr[2] * arr[3] * arr[4]);\n newArray.push(arr[0] * arr[2] * arr[3] * arr[4]);\n newArray.push(arr[1] * arr[0] * arr[3] * arr[4]);\n newArray.push(arr[1] * arr[2] * arr[0] * arr[4]);\n newArray.push(arr[1] * arr[2] * arr[3] * arr[0]);\n return console.log(newArray);\n}", "function double(arr) {\n\n for (var i=0;i<arr.length;i++) {\n arr[i] = arr[i]*2;\n }\n return arr;\n }", "function double(arrayx) {\n arrayx = arrayx.map(x => x * 2 );\n return arrayx;\n }", "function productOfArray(arr) {\n \n}", "function squareNums(array){\r\n return array.map(toSquare);\r\n}" ]
[ "0.6993784", "0.6827081", "0.6781742", "0.67712945", "0.6756033", "0.6755876", "0.67301583", "0.67162985", "0.66931087", "0.6651253", "0.66062224", "0.659797", "0.6558341", "0.6268903", "0.6126991", "0.6099188", "0.6065783", "0.60554016", "0.6028381", "0.60040396", "0.6002544", "0.5959507", "0.59591067", "0.59294593", "0.59166396", "0.5878106", "0.5837701", "0.58217424", "0.57843184", "0.5780888", "0.57401264", "0.5732633", "0.57164663", "0.5702615", "0.56966084", "0.5683053", "0.5672378", "0.56709206", "0.56666386", "0.5665074", "0.5651503", "0.56146044", "0.558736", "0.55769783", "0.55699813", "0.55566114", "0.55563575", "0.55371934", "0.5530899", "0.55230373", "0.55154884", "0.5506161", "0.5503312", "0.54952836", "0.5491829", "0.5479579", "0.54794276", "0.54776275", "0.54674345", "0.54674345", "0.54674345", "0.54674345", "0.54674345", "0.5457243", "0.5452936", "0.54443926", "0.54443926", "0.54443926", "0.54443926", "0.54344946", "0.54320335", "0.5413817", "0.5409865", "0.54005027", "0.5396759", "0.5388957", "0.5386175", "0.53835744", "0.5376936", "0.53577954", "0.5330776", "0.5330575", "0.53283566", "0.53274536", "0.53241706", "0.53211945", "0.5315144", "0.53145015", "0.530922", "0.5307627", "0.5307627", "0.5307627", "0.52982163", "0.5296887", "0.5290591", "0.52873915", "0.52763057", "0.52699286", "0.52693", "0.5268213" ]
0.65594935
12
[POST] api/lending fields: state: string money: number accidentDate: date contactImmediately: boolean attorney: string lender: object firstName: string lastName: string role: string email: string phone: string
createNewCompleteLending(req, res) { if (req.body.lender) { let lender = req.body.lender; userModel .register(lender) .then((lenderUser) => { mailer.sendValidationMail(lenderUser); lendingModel .saveLending(req.body, lenderUser._id) .then((lending) => { res.json(lending); }) .catch((error) => { res.status(400).send(error); }) }) .catch((error) => { res.status(400).send(error); }); } else res.status(400).send('missing fields'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function Lead(req) {\n\tif (req.body.name && req.body.company && req.body.email && req.body.message) {\n\t\tthis.name = req.body.name;\n\t\tthis.company = req.body.company;\n\t\tthis.email = req.body.email;\n\t\tthis.message = req.body.message;\n\t\tthis.phone = req.body.phone;\n\t} else {\n\t\treturn false;\n\t}\n}", "function fields() {\n personal_data = {\n 'my_name': ['Tim Booher'],\n 'grade': ['O-5'],\n 'ssn': ['111-22-2222'],\n 'address_and_street': ['200 E Dudley Ave'],\n 'b CITY': ['Westfield'],\n 'c STATE': ['NJ'],\n 'daytime_tel_num': ['732-575-0226'],\n 'travel_order_auth_number': ['7357642'],\n 'org_and_station': ['US CYBER JQ FFD11, MOFFETT FLD, CA'],\n 'e EMAIL ADDRESS': ['tbooher.guest@diux.mil'],\n 'eft': ['X'],\n 'tdy': ['X'],\n 'house_hold_goodies': ['X'],\n 'the_year': ['2018']\n }\n trip_data = { 'a DATERow3_2': ['07/19'], 'reason1': ['AT'], 'a DATERow5_2': ['07/19'], 'reason2': ['AT'], 'reason3': ['TD'], 'a DATERow7_2': ['07/21'], 'a DATERow9_2': ['07/15'], 'b NATURE OF EXPENSERow81': ['Capital Bikeshare'], 'a DATERow1_2': ['07/15'], 'b NATURE OF EXPENSERow41': ['Travel from summit to BOS'], 'b NATURE OF EXPENSERow1': ['Travel from IAD to Hotel'], 'from1': ['07/15'], 'to2': ['07/15'], 'to1': ['07/15'], 'from4': ['07/19'], 'to4': ['07/19'], 'to3': ['07/19'], 'from5': ['07/21'], 'from2': ['07/15'], 'to6': ['07/21'], 'from3': ['07/19'], 'to5': ['07/21'], 'reason4': ['TD'], 'reason5': ['AT'], 'from6': ['07/21'], 'reason6': ['MC'], 'c AMOUNTRow8': ['25.0'], 'c AMOUNTRow7': ['45.46'], 'c AMOUNTRow6': ['11.56'], 'c AMOUNTRow5': ['38.86'], 'c AMOUNTRow9': ['23.0'], 'b NATURE OF EXPENSERow7': ['Travel from EWR to HOR'], 'b NATURE OF EXPENSERow3': ['Travel between meetings'], 'a DATERow10_2': ['07/18'], 'c AMOUNTRow4': ['28.4'], 'c AMOUNTRow3': ['21.1'], 'c AMOUNTRow2': ['23.77'], 'c AMOUNTRow1': ['43.5'], 'mode6': ['CA'], 'a DATERow2_2': ['07/15'], 'mode5': ['CP'], 'mode4': ['CP'], 'a DATERow4_2': ['07/19'], 'mode3': ['CP'], 'ardep6': ['HOR'], 'a DATERow6_2': ['07/19'], 'a DATERow8_2': ['07/21'], 'b NATURE OF EXPENSERow6': ['Travel from hotel to IAD'], 'ardep1': ['EWR'], 'd ALLOWEDRow10': ['6.25'], 'b NATURE OF EXPENSERow2': ['Travel from BOS to Meeting'], 'ardep5': ['EWR'], 'ardep4': ['Arlington VA'], 'ardep3': ['BOS'], 'ardep2': ['Arlington VA'], 'c AMOUNTRow10': ['6.25'], 'mode2': ['CP'], 'mode1': ['CA'], 'b NATURE OF EXPENSERow9': ['Metro'], 'b NATURE OF EXPENSERow5': ['Travel from hotel to DCA'], 'd ALLOWEDRow1': ['43.5'], 'b NATURE OF EXPENSERow1': ['Travel from HOR to EWR'], 'd ALLOWEDRow3': ['21.1'], 'd ALLOWEDRow2': ['23.77'], 'd ALLOWEDRow5': ['38.86'], 'd ALLOWEDRow4': ['28.4'], 'd ALLOWEDRow7': ['45.46'], 'd ALLOWEDRow6': ['11.56'], 'd ALLOWEDRow9': ['23.0'], 'd ALLOWEDRow8': ['25.0'] }\n return Object.assign({}, personal_data, trip_data);\n}", "function apiAdd(request, response, next) {\r\n const body = request.body\r\n\r\n const person = new Person({\r\n name: body.name,\r\n number: body.number\r\n })\r\n\r\n person\r\n .save()\r\n .then(newPerson => newPerson.toJSON())\r\n .then(newAndFormattedPerson => {\r\n response.json(newAndFormattedPerson)\r\n })\r\n .catch(error => next(error))\r\n}", "function convertLeads() {\n\tif (!validationForm()) {\n\t\treturn;\n\t}\n\tname = document.getElementById('form-nome').value;\n email = document.getElementById('form-email').value;\n company = document.getElementById('form-empresa').value;\n\n\tleads.unshift({\"name\":name , \"email\":email , \"company\":company});\n\n\tconsole.log(name);\n\tconsole.log(email);\n\tconsole.log(company);\n\tsaveListStorage(leads);\n\t\n\tresetForm();\n}", "function addData(fName, lName, email, phone) {\n let object = {\n firstName: fName,\n lastName: lName,\n email: email,\n phoneNumber: phone\n }\n fBase.add(object);\n}", "function getPartnerEventInvitations() {\n request(GET_LINK, (err, res, body) => {\n const partners = JSON.parse(body).partners;\n const countries = parsePartners(partners);\n request.post(POST_LINK, {json: {countries : countries}}, (err, httpResponse, body) => {\n console.log(httpResponse.statusCode)\n });\n });\n}", "constructor(fields = {}) {\n this.lname = fields.lname;\n this.fname = fields.fname;\n this.email = fields.email;\n this.phone = fields.phone || null;\n this.years_employed = fields.years_employed || 0;\n this.annual_leave = fields.annual_leave || 40;\n this.sick_leave = fields.sick_leave || 40;\n this.personal_day = fields.personal_day || 1;\n this.title = fields.title || null;\n this.manager_email = fields.manager_email || null;\n }", "function getRequestData(type, state, newData){\n var url, method, body;\n switch(type){\n case \"get\":\n url = \"bridge/\"+username+\"/lights\";\n method = \"GET\";\n break;\n case \"update\":\n var value = state.parent();\n var device = value.parent();\n url = \"bridge/\"+username+\"/lights/\" +device.get(\"product\")+\"/state\";\n method = \"PUT\";\n body = {}\n body[value.get(\"name\")] = newData;\n break;\n default:\n break;\n }\n return {\n url: url,\n method: method,\n body: body\n };\n}", "function createYourDisneyDay(e) {\n e.preventDefault()\n let data = { \n ride: e.target[0].value,\n dining: e.target[1].value,\n show: e.target[2].value,\n photoop: e.target[3].value,\n shopping: e.target[4].value}\n \n\n let day = new YourDisneyDay(data) \n console.log(YourDisneyDay.all)\n day.renderDay()\n \n fetch(this.baseURL+\"/disney_days\", {\n method: 'POST',\n headers: {\n 'Content-type': 'application/json',\n 'Accept': 'application/json'\n },\n body: JSON.stringify({\n id: userObj.id, //come back after creating user\n day: data\n })\n })\n .then(resp => resp.json())\n .then(data => {\n const { id, name, category } = data;\n new Attraction(id, name, category)\n renderAttractions()\n })\n .catch(err => console.log(err));\n}", "function prepPutPartyRequest(data) {\n let putPartyRequest = {\n 'FunctionName': 'party',\n 'Payload': JSON.stringify({\n 'firstName': 'testFirstName',\n 'lastName': 'testLastName'\n })\n };\n putPartyRequest.Payload = JSON.stringify(data);\n\n return putPartyRequest;\n }", "createTrainingDate(payload) {\n return this.request.post('/create-training-date', _objectSpread({}, payload));\n }", "function name(agent){\n var body=JSON.stringify(request.body);\n console.log(body);\n var obj = JSON.parse(body);\n \n // use outputContext[2] when testing in dialogflow console\n //let insuranceNumber=obj.queryResult.outputContexts[2].parameters.Insurance_Number;\n //let fever=obj.queryResult.outputContexts[2].parameters.Number2;\n //let preCon=obj.queryResult.outputContexts[2].parameters.Precondition;\n //let headInjury=obj.queryResult.outputContexts[2].parameters.Head_Injury;\n //let fracture=obj.queryResult.outputContexts[2].parameters.Fracture;\n \n let insuranceNumber=obj.queryResult.outputContexts[6].parameters.Insurance_Number;\n let fever=obj.queryResult.outputContexts[6].parameters.Number2;\n let preCon=obj.queryResult.outputContexts[6].parameters.Precondition;\n let headInjury=obj.queryResult.outputContexts[6].parameters.Head_Injury;\n let fracture=obj.queryResult.outputContexts[6].parameters.Fracture;\n console.log(insuranceNumber);\n let surname=obj.queryResult.parameters.givenname;\n let lastname=obj.queryResult.parameters.lastname;\n let mail=obj.queryResult.parameters.email;\n let birthDate=obj.queryResult.parameters.dateOfBirth; \n let params='InsuranceNumber='+ insuranceNumber + '&Surname=' + surname + '&Lastname=' + lastname + '&Mail=' + mail + '&dataOfBirth=' + birthDate;\n\tlet data = '';\n let url = encodeURI(`https://hook.integromat.com/zbeedk5u73hmh2jpay5w835anxq4x4kx?` + params);\n\treturn new Promise((resolve, reject) => { \n const request = https.get(url, (res) => {\n res.on('data', (d) => {\n data += d;\n agent.add(`Thanks`);\n console.log(`Thanks`); \n console.log(body);\n var name = surname + ` ` + lastname;\n consultationNeededPrompt(agent, name, fever, preCon, headInjury, fracture); \n });\n res.on('end', resolve);\n });\n request.on('error', reject);\n });\n }", "add(name, surname, id, gender, drivers_license, contact_number, address, vehicle_make, vehicle_series_name, license_plate, colour, year) {\n\t\tconsole.log('Sending',name, surname, id, gender, drivers_license, contact_number, address, vehicle_make, vehicle_series_name, license_plate, colour, year)\n\t\treturn $.ajax({\n\t\ttype: 'PUT',\n\t\turl: `${apiUrl}/entries`,\n\t\tcontentType: 'application/json; charset=utf-8',\n\t\tdata: JSON.stringify({\n \tname,\n\t\t\tsurname,\n\t\t\tid,\n\t\t\tgender,\n\t\t\tdrivers_license,\n\t\t\tcontact_number,\n\t\t\taddress, vehicle_make,\n\t\t\tvehicle_series_name,\n\t\t\tlicense_plate,\n\t\t\tcolour, \n\t\t\tyear,\n\t\t\t}),\n\t\t\tdataType: 'json',\n });\n}", "onSubmitButtonPressed() {\n var startmin = this.state.startHour + this.state.startMinute / 60.0;\n var endmin = this.state.endHour + this.state.endMinute/60.0;\n var time = \"(\" + startmin + \",\" + endmin +\")\";\n var date = this.state.dateDate.getFullYear() + '-' + (this.state.dateDate.getMonth()+1) + '-' + this.state.dateDate.getDate();\n var age_range = \"[\"+this.state.start_age+\",\"+this.state.end_age+\"]\";\n var body = JSON.stringify({\n a: this.state.ActivityName,\n b: date,\n c: time,\n d: this.state.cost,\n e: this.state.street_address,\n f: this.state.city,\n g: this.state.state,\n h: this.state.country,\n i: this.state.zip_code,\n j: this.state.description,\n k: this.state.wheelchair_accessible,\n l: this.state.activity_type,\n m: this.state.disability_type,\n n: age_range,\n o: this.state.parent_participation,\n p: this.state.assistant,\n q: this.state.wheelchair_accessible_restroom,\n r: this.state.equipment_provided,\n s: this.state.sibling,\n t: this.state.kids_to_staff,\n u: this.state.asl,\n v: this.state.closed_circuit,\n w: this.state.add_charge,\n x: this.state.animals,\n y: this.state.childcare,\n z: this.state.phone});\n // console.warn(body);\n fetch('http://10.0.2.2:3000/api/activities/createNewActivity', {\n method: \"POST\",\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'},\n body: body\n })\n // .then( (res)=> res.json() )\n // .then( (resData) => {\n // Alert.alert(JSON.stringify(resData.message) );\n // } )\n .done();\n\n this._navigate()\n\n}", "function addEmployeeToDb() {\n const newEmployee = {\n name: {\n firstName: `${firstName.value}`,\n lastName: `${lastName.value}`,\n },\n jobYears: parseInt(jobYears.value),\n salary: parseInt(salary.value),\n position: `${position.value}`,\n team: `${team.value}`,\n phone: `${phone.value}`,\n email: `${email.value}`,\n paysTax: tax(),\n };\n\n axios\n .post(\"http://localhost:3000/api/employee/\", newEmployee)\n .then((res) => {\n populateList();\n })\n .catch((err) => console.log(err));\n}", "function setDeal(idOrganitation,idPerson,namePerson,nameOrganitation)\n{\n\n var strHttp = urllib.request('https://api.pipedrive.com/v1/deals?api_token=' + token , {\n method: 'POST',\n data: {\n 'title': 'Nuevo negocio (' + nameOrganitation + ')',\n 'value' : '0',\n 'currency' : 'MXN',\n 'user_id' : '1245108',\n 'person_id' :idPerson,\n 'org_id' : idOrganitation\n 'status': 'open',\n 'stage_id': 18\n }\n });\n\n}", "async _saveLiftAdvertisement() {\n try {\n await fetch(BackendURL + '/lifts/new', {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n lift: LiftStore.lift\n }),\n });\n } catch (error) {\n Alert.alert(\"Leider konnte Ihre Mitfahrgelegenheit nicht gespeichert werden.\");\n }\n }", "function createMentor(){\n let mentorName = document.getElementById('mentorName').value;\n let email = document.getElementById('mentorEmail').value;\n fetch(url + `/add-mentor`, {\n method: \"POST\",\n body: JSON.stringify({\n name: mentorName, email, studentList: []\n }),\n headers: {\n 'Content-type': 'application/json'\n }\n })\n .then((resp) => resp.json())\n .then((data) => {\n createMentorOption( mentorName);\n })\n return false;\n}", "submitNewPerson (firstName, lastName, about, guests) {\n if (guests === '' || NaN)\n guests = 0;\n let person = {\n firstName: firstName,\n lastName: lastName,\n about: about,\n guests: guests,\n numberOfArrivals: 0,\n }\n this.postRequest(person);\n this.setState({isAddingPerson: false})\n }", "add(givenName, surName, emailAddresses, businessPhones, additionalProperties = {}) {\r\n const postBody = extend({\r\n businessPhones: businessPhones,\r\n emailAddresses: emailAddresses,\r\n givenName: givenName,\r\n surName: surName,\r\n }, additionalProperties);\r\n return this.postCore({\r\n body: jsS(postBody),\r\n }).then(r => {\r\n return {\r\n contact: this.getById(r.id),\r\n data: r,\r\n };\r\n });\r\n }", "function fillFields(response) {\n const { name, cpf_cnpj, rg, phone, email, active } = response.person;\n console.log(response.peopleType);\n const typeIds = response.peopleType.map((index) => {\n if (index.Type_people.active) {\n return index.Type_people.id_type;\n }\n });\n\n console.log(typeIds);\n\n console.log(typeIds.includes(\"1\"));\n\n name ? setName(name) : setName(\"\");\n\n cpf_cnpj ? setCpf_cnpj(cpf_cnpj) : setCpf_cnpj(\"\");\n\n rg ? setRg(rg) : setRg(\"\");\n\n phone ? setPhone(phone) : setPhone(\"\");\n\n email ? setEmail(email) : setEmail(\"\");\n\n active ? setActive(active) : setActive(false);\n\n typeIds.includes(1) || typeIds.includes(\"1\")\n ? setCheckedTypeAdmin(true)\n : setCheckedTypeAdmin(false);\n\n typeIds.includes(2) || typeIds.includes(\"2\")\n ? setCheckedTypeAttendance(true)\n : setCheckedTypeAttendance(false);\n\n typeIds.includes(3) || typeIds.includes(\"3\")\n ? setCheckedTypeDriver(true)\n : setCheckedTypeDriver(false);\n }", "onCustomFields() {\n const data = {\n\n \"fields\": {\n party: this.bookingFormStep1.party,\n booking_date: this.bookingDate,\n booking_time: this.bookingFormStep1.time[0],\n email: this.bookingFormStep2.email,\n first_name: this.bookingFormStep2.fName,\n surname: this.bookingFormStep2.lName,\n phone: this.bookingFormStep2.phone,\n special_requests: this.bookingFormStep2.requests\n }\n\n }\n const headers = {\n 'Authorization': `Bearer ${this.token}`,\n };\n //edit booking for the custom fields\n axios.post(`http://api.sorrisopress.gomedia/wp-json/acf/v3/bookings/${this.postId}`, data, {\n headers\n }).then((response) => {\n console.log('END', response);\n //retrieve booking\n this.onRetrieveBooking()\n\n\n });\n }", "newRequest(payload){\n this.milestones = new Milestones\n this.milestones.Reported();\n let miles = JSON.stringify(this.milestones.stringify())\n \n payload.append('milestones',miles);\n console.log(payload);\n fetch('../api/requests/new',{\n 'method':'POST',\n 'body':payload\n })\n // .then(r=>(r.json()))\n .then(r=>console.log(r))\n }", "function updatePartnersFields() {\n data.partners.forEach(partner => {\n data.fields.forEach(field => {\n let id = GatherComponent.idByPartnerField(partner, field);\n partner.attributes[field.id] = elementById(id).value;\n });\n });\n}", "function createFellowship(data) {\n var formData = data.values;\n Logger.log(\"Form data is: \" + formData);\n description = getDescription(formData);\n createEvent(formData);\n Logger.log(\"Successfully created fellowship \" + formData[namePosition]);\n}", "async CreatePartner(ctx, partner) {\n partner = JSON.parse(partner);\n\n await ctx.stub.putState(partner.id, Buffer.from(JSON.stringify(partner)));\n\n let allPartners = await ctx.stub.getState(allPartnersKey);\n allPartners = JSON.parse(allPartners);\n allPartners.push(partner);\n await ctx.stub.putState(\n allPartnersKey,\n Buffer.from(JSON.stringify(allPartners))\n );\n\n return JSON.stringify(partner);\n }", "function saveNewEntry() {\n\n// get information from the inputs and make date\n var role = document.getElementById('role').value;\n var champion = document.getElementById('champion').value;\n var wl = document.getElementById('wl').checked ? true : false;\n var notes = document.getElementById('notes').value;\n var d = new Date();\n var datestring = (d.getMonth()+1) + \"/\" + d.getDate();\n\n \n // save(post) information to DB\n fetch('/save', {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\"\n }, \n body: JSON.stringify({\n date: datestring,\n role,\n champion,\n wl,\n notes\n })\n })\n // append information\n .then(getDataAndRenderLogEntries())\n .catch(function(err) { console.log(err) });\n \n}", "function _savePayloadFields() {\n\t\ttry {\n\n\t\t\t//Get the Request Body\n\t\t\tvar oBody = JSON.parse($.request.body.asString());\n\t\t\tvar requestPayload = oBody.PAYLOAD_REQUEST;\n\t\t\tvar responsePayload = oBody.PAYLOAD_RESPONSE;\n\n\t\t\trequestPayload = requestPayload.replace(\"\\\\\", \"\");\n\t\t\tif (requestPayload) {\n\t\t\t\ttry {\n\t\t\t\t\tvar request = JSON.parse(requestPayload);\n\t\t\t\t} catch (convError) {\n\t\t\t\t\tgvConvError += convError.message;\n\t\t\t\t}\n\t\t\t}\n\t\t\tresponsePayload = responsePayload.replace(\"\\\\\", \"\");\n\t\t\tresponsePayload = responsePayload.replace(\"\\n\", \"\");\n\t\t\tif (responsePayload) {\n\t\t\t\ttry {\n\t\t\t\t\tvar response = JSON.parse(responsePayload);\n\t\t\t\t} catch (convError) {\n\t\t\t\t\tgvConvError += convError.message;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (request && response) {\n\t\t\t\t//Insert Entries into GL_HEADER Table\n\t\t\t\t_InsertHeaderEntry(request, response);\n\n\t\t\t\t//Insert Entries into GL_ITEM Table\n\t\t\t\t_InsertItemEntry(request, response);\n\n\t\t\t\t//Insert Entries into GL_Currency Table\n\t\t\t\t_InsertCurrencyEntry(request, response);\n\n\t\t\t\t//Insert Entries into Forecast Master Table\n\t\t\t\t_InsertForecastEntry(request, response);\n\t\t\t}\n\t\t} catch (errorObj) {\n\t\t\tgvTableUpdate = \"Error saving Payload field level entries:\" + errorObj.message;\n\t\t}\n\t}", "function builBodyRequest() {\n\tvar cookie = getCookie(\"Appleseed_user_details\");\n\tvar parsed = JSON.parse(cookie);\n\tvar numberTrees = parseInt(document.getElementById(\"trees-number\").value);\n\tvar idOwner = parsed['user']['id'];\n\tvar description = document.getElementById(\"tree-text\").value;\n\tvar idLocation = parseInt(document.getElementById(\"location\").value);\n\tvar date = document.getElementById(\"datepicker\").value;\n\tvar time = document.getElementById(\"timepicker\").value;\n\tvar end = document.getElementById(\"timepicker2\").value;\n\tvar dateTime = new Date(date+\" \"+time);\n\tvar endTime = new Date(date+\" \"+end);\n\tvar trees = getTrees(numberTrees);\n\n\tvar bodyEvent = {};\n\tbodyEvent['event'] = {}\n\tbodyEvent['event']['owner'] = {};\n\tbodyEvent['event']['owner']['id'] = idOwner;\n\tbodyEvent['event']['description'] = description;\n\tbodyEvent['event']['location'] = {};\n\tbodyEvent['event']['location']['id'] = idLocation;\n\tbodyEvent['event']['datetime'] = dateTime.toISOString();\n\tbodyEvent['event']['endtime'] = endTime.toISOString();\n\tbodyEvent['event']['trees'] = trees;\n\tbodyEvent['event']['attendees'] = [];\n\tbodyEvent['event']['staffNotes'] = \"\";\n\n\treturn JSON.stringify(bodyEvent);\n}", "function identification(agent){\n var body=JSON.stringify(request.body);\n console.log(body);\n var obj = JSON.parse(body);\n let fever=obj.queryResult.parameters.number2;\n let fracture=obj.queryResult.parameters.Fracture;\n let precon=obj.queryResult.parameters.Precondition;\n let headInj=obj.queryResult.parameters.Head_Injury; \n console.log(fracture);\n let insuranceNumber=obj.queryResult.parameters.Insurance_Number;\n console.log(insuranceNumber);\n\tlet data = '';\n let url = `https://hook.integromat.com/eyucscywke51f6tnpjmapr5h6t2lcd1q?InsuranceNumber=` + insuranceNumber;\n\treturn new Promise((resolve, reject) => { \n const request = https.get(url, (res) => {\n res.on('data', (d) => {\n data += d;\n \tconsole.log(JSON.stringify(data)); \n \t\tvar name=JSON.stringify(data);\n \tname = name.substr(13);\n \tname = name.replace(/[^a-zA-Z ]/g, \"\");\n \tif (name === ''){\n \tagent.add(`Looks like we have never met before. Please tell me your full name.`);\n }else{\n \t\tconsultationNeededPrompt(agent, name, fever, precon, headInj, fracture);\n }\n });\n res.on('end', resolve);\n });\n request.on('error', reject);\n });\n }", "toApi() {\n let applicantContacts = [\n {\n \"Type\": \"e\",\n \"IsPrimary\": true,\n \"IsPrivate\": true,\n \"Email\": Url.stripHtml(this.email)\n },\n {\n \"Type\": \"p\",\n \"IsPrimary\": true,\n \"IsPrivate\": true,\n \"Phone\": this.mobile\n },\n {\n \"Type\": \"p\",\n \"IsPrimary\": false,\n \"IsPrivate\": true,\n \"Phone\": this.landline\n },\n {\n \"Type\": \"ad\",\n \"IsPrimary\": false,\n \"IsPrivate\": false,\n \"Address\": Url.stripHtml(this.address),\n \"City\": \"\",\n \"Suburb\": Url.stripHtml(this.suburb),\n \"CountryId\": this.countryId\n }\n ];\n\n if(!this.landline) {\n applicantContacts.splice(2, 1);\n }\n\n return {\n \"JobId\": this.jobId,\n \"ResumeFileStorageId\": this.resumeId,\n \"ApplicantInformation\": {\n \"FirstName\": Url.stripHtml(this.firstname),\n \"SurName\": Url.stripHtml(this.surname),\n \"BirthDay\": null,\n \"Sex\": null,\n \"Salutation\": null\n },\n \"ApplicantContacts\": applicantContacts\n };\n }", "function party_create(){\n\n\t//log.error('party_create for '+this.tsid);\n\n\tthis.party = apiNewGroup('party');\n\n\tthis.party.init(this);\n}", "async addDrug(ctx, drugName, serialNo, mfgDate, expDate, companyCRN) {\n //Verifying the identity of the function caller\n let verifyManufacturer = ctx.clientIdentity.getMSPID();\n let arrayList = await this.getPartialKeyArray(ctx, 'org.pharma-network.pharmanet.lists.company', companyCRN);\n //Verify if the function is called by registered manufacturer\n if (verifyManufacturer === 'manufacturerMSP' && arrayList.length !== 0) {\n //converting array into jason object\n let jasonObject = JSON.parse(arrayList[0]);\n let companyName = jasonObject.companyId.companyName;\n //Create a new Request to add it in the blockchain\n let drugObject = {\n productId: {\n drugName: drugName,\n serialNo: serialNo\n },\n name: drugName,\n manufacturer: {\n comapnyCRN: companyCRN,\n companyName: companyName\n },\n manufacturingDate: mfgDate,\n expiryDate: expDate,\n owner: companyCRN,\n shipment: \"\",\n };\n //Create the instance of the model class to save it to blockchain\n let drugObj = Drug.createInstance(drugObject);\n await ctx.drugList.addDrug(drugObj);\n //returns the Jason object\n return drugObj;\n }\n }", "function AddExpense() {\n console.log(\"Calling API Expense\");\n fetch('http://localhost:8080/' + trip + '/expense', {\n method: \"POST\",\n body: JSON.stringify({\n tripId: trip,\n amount: amount,\n description: description,\n }),\n headers: {\n \"Content-type\": \"application/json ; charset=UTF-8\",\n \"Authorization\": \"Bearer\" + login,\n //\"Authorization\": `Bearer ${TOKEN}`\n }\n })\n .then((response) => response.json())\n .then((json) => {\n console.log(json);\n setExpense(json);\n\n\n }).catch((error) => {\n console.log(error);\n console.error(error)\n setExpense(\"error\")\n\n });\n }", "function create(params) {\n var loan = new RequestLoan();\n loan.resource = params.resource;\n loan.user = params.user;\n return loan;\n}", "CreateNewParcel (req, res) {\n\n if(!req.body.name) {\n return res.status(400).send({\n success: 'false',\n message: 'name is required'\n });\n } else if(!req.body.pickupLocation) {\n return res.status(400).send({\n success: 'false',\n message: 'pick up location is required'\n });\n } else if(!req.body.destination){\n return res.status(400).send({\n success : 'false',\n message: \"Destination is required\"\n });\n }\n\n // as an example \n const newParcel = {\n id : data.length + 1,\n name : req.body.name,\n description : req.body.description,\n destination : req.body.destination,\n pickupLocation : req.body.pickupLocation,\n status : req.body.status,\n createdBy : 4\n }\n\n data.push(newParcel);\n return res.status(201).send({\n success : 'True',\n message : 'Parcel Created succesfully'\n })\n \n}", "function LEAD_FORM_HANDLER(state, collection) {\n if (collection.apntVisible) {\n state.leadsFormHandler.apntVisible = collection.apntVisible;\n state.leadsFormHandler.divshow = collection.divshow;\n console.log(collection);\n } else if (collection.dateTimeVisible) {\n state.leadsFormHandler.dateTimeVisible = collection.dateTimeVisible;\n console.log(collection);\n } else if (collection.showChildFields) {\n state.leadsFormHandler.showChildFields = collection.showChildFields;\n }\n // console.log(collection);\n\n // Fresh Lead Indicator :\n else if (collection.freshLead) {\n // if (state.leadsFormHandler.freshLead === true) {\n state.leadsFormHandler.freshLead = collection.freshLead;\n // } else if (state.leadsFormHandler.freshLead === false) {\n // state.leadsFormHandler.freshLead = true\n // }\n } else if (collection.httpMethod) {\n // It Accept String POST or PUT\n state.leadsFormHandler.httpMethod = collection.httpMethod; /** Http Method POST and PUT */\n console.log('HTTP METHOD: ', collection.httpMethod);\n } else if (collection._leadId) {\n state.leadsFormHandler._leadId = collection._leadId;\n }\n}", "function addOtherFields(responseString, otherEndpointFields, requestedFields){\n var response = JSON.parse(responseString);\n var finalResponse = [];\n console.log(\"**\" + JSON.stringify(requestedFields));\n \n for(var i = 0; i < response.length; i++){\n \n var url = \"https://api-v3.igdb.com/covers\";\n var row = {};\n \n \n var newResponseString = UrlFetchApp.fetch(url, {\n headers: {\n 'user-key': 'add user-key here',\n 'Accept': 'application/json'\n }, method: 'post',\n payload: 'fields url; where game = ' + response[i].id + ';',\n muteHttpExceptions : true \n });\n \n //console.log(\"newResponseString[\" + i + \"]: \" + newResponseString);\n response[i].url = \"https:\" + JSON.parse(newResponseString)[0].url;\n \n for(var m = 0; m < requestedFields.length; m++){\n row[requestedFields[m].name] = response[i][requestedFields[m].name];\n }\n \n finalResponse.push(row);\n \n }\n \n return JSON.stringify(finalResponse);\n \n \n}", "async createFlight(req, res) {\n const { Year, Month, DayofMonth, DayOfWeek, DepTime,\n CRSDepTime, ArrTime, CRSArrTime, UniqueCarrier, FlightNum,\n TailNum, ActualElapsedTime, CRSElapsedTime, AirTime,\n ArrDelay, DepDelay, Origin, Dest, Distance, TaxiIn,\n TaxiOut, Cancelled, CancellationCode, Diverted,\n CarrierDelay, WeatherDelay, NASDelay, SecurityDelay,\n LateAircraftDelay,\n } = req.body;\n\n try {\n \n const flight = await Flight.create({\n Year, Month, DayofMonth, DayOfWeek, DepTime,\n CRSDepTime, ArrTime, CRSArrTime, UniqueCarrier,\n FlightNum, TailNum, ActualElapsedTime, CRSElapsedTime,\n AirTime, ArrDelay, DepDelay, Origin, Dest, Distance,\n TaxiIn, TaxiOut, Cancelled, CancellationCode, Diverted,\n CarrierDelay, WeatherDelay, NASDelay, SecurityDelay,\n LateAircraftDelay,\n });\n return res.json(flight);\n\n } catch (error) {\n console.log(error);\n return res.status(400).json({\n message: \"Something went grong while creating flight\" + error,\n });\n }\n }", "sendAddRequest() {\r\n // gets the name, description, birth date, and flag\r\n var name = document.getElementById('name').value\r\n var description = document.getElementById('description').value\r\n var birthDate = document.getElementById('birthDate').value\r\n var flag = document.getElementById('flag').value\r\n\r\n // posts the contact data to the API.\r\n fetch('https://localhost:44374/contact/add', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n body: JSON.stringify({\r\n \"name\": name,\r\n \"description\": description,\r\n \"birthDate\": birthDate,\r\n \"group\": parseInt(this.state.selectedGroup),\r\n \"flag\": flag\r\n })\r\n })\r\n\r\n window.location.href = '/'\r\n }", "function addPerson(object) {\n var promise = $http({\n method: 'POST',\n url: '/lovedones-add',\n data: {\n name: object.name,\n weight: object.weight,\n age: object.age,\n userid: object.userid\n }\n }).then(function successfulCallback(response) {\n lovedones = response.data;\n }, function(error) {\n console.log(error);\n });\n return promise;\n }", "function onFetchOffersSuccess(resp) {\n let offers = {};\n\n resp.forEach(offer => {\n offers[offer.id] = {\n applicant_id: offer.applicant_id,\n first_name: offer.applicant.first_name,\n last_name: offer.applicant.last_name,\n student_number: offer.applicant.student_number,\n email: offer.applicant.email,\n contract_details: {\n position: offer.position,\n sessional_year: offer.session.year,\n sessional_semester: offer.session.semester,\n hours: offer.hours,\n start_date: offer.session.start_date,\n end_date: offer.session.end_date,\n pay: offer.session.pay,\n link: offer.link,\n signature: offer.signature,\n },\n contract_statuses: {\n nag_count: offer.nag_count,\n status: offer.status,\n hr_status: offer.hr_status,\n ddah_status: offer.ddah_status,\n sent_at: offer.send_date,\n printed_at: offer.print_time,\n },\n };\n });\n\n return offers;\n}", "function setleadformparams()\n{\n var partner = getPartnerCode();\n setCookieFromParam(\"promocode\");\n setCookieFromParam(\"osb\");\n setCookieFromParam(\"id\");\n setCookieFromParam(\"email\");\n\t\n\t// this represents the add medium.\n\tsetCookieFromParam(\"custentity210\");\n\t\n\t// this represents scompid for the referring partner.\n\t// id of corresponding custom field in ns is custentity_ref_comp_id\n\tsetCookieFromParam(\"origin\");\n\t\n\treturn partner;\n}", "function createPatient() {\n const patient = {\n name: document.getElementById('name').value,\n sex: document.getElementById('sex').value,\n gender: document.getElementById('gender').value,\n age: document.getElementById('age').value,\n date_of_birth: document.getElementById('date_of_birth').value\n }\n fetch(\"http://localhost:3000/patients\", {\n method: 'POST',\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify(patient)\n })\n .then(resp => resp.json())\n .then(patient => {\n clearPatientHtml()\n getPatients()\n Patient.newPatientForm()\n })\n}", "function createLoteo(req, res, next){\r\n // console.log(req.body.geometry);\r\n\r\n Loteo.create(req.body).then((loteo)=>{\r\n \r\n res.send({Loteo: loteo}); \r\n }).catch(next);\r\n\r\n}", "addTraining(training) {\n console.log(training);\n fetch('https://customerrest.herokuapp.com/api/trainings/',\n { method: 'POST',\n headers: { 'Content-Type': 'application/json', },\n body: JSON.stringify(training)\n })\n .then(res => this.loadTrainings())\n .then(res => this.setState({open: true, message: 'training added'}))\n .catch(err => console.error(err))\n }", "createOrder({username, amount, body={},\n order_sn=`D${dayjs().format('YYYYMMDDHHmmss')}`,\n status='created'}) {\n const pathname = '/api/orders/';\n body = JSON.stringify(body);\n return this.requestJSON({pathname, method: 'POST',\n form: {username, amount, body, order_sn, status}});\n }", "async function postData(url, feelings){\n\nconst dataS={\n date: newDate,\n temp: temperature,\n userRes: feelings\n}\n\nconst options = {\n method: \"POST\",\n credentials: \"same-origin\",\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify(dataS)\n }\n\nawait fetch(url, options);\n\n}", "async onSubmit() {\n await fetch('https://polar-badlands-83667.herokuapp.com/liters', {\n method: 'post',\n headers: {\n 'content-type': 'application/json',\n },\n body: JSON.stringify(({\n car: this.state.carSelection,\n track: this.state.trackSelection\n }))\n })\n .then(resp => resp.json())\n .then(liters => {\n this.setState({\n carLiters: liters,\n })\n console.log(liters)\n })\n .catch(err => console.log(err))\n }", "static initialize(obj, email, tosConsent, marketingConsent, dataConsent, tosConsentDate, taxInformation, countryBirth, lastLogin, referredBy, successfulReferrals, kycVerified, isVerified, feeSegments, extraData, portfolios, riskLevel, onboardingToken, uuid, created, updated, status, language, marketingConsentDate, dataConsentDate) { \n obj['email'] = email;\n obj['tos_consent'] = tosConsent;\n obj['marketing_consent'] = marketingConsent;\n obj['data_consent'] = dataConsent;\n obj['tos_consent_date'] = tosConsentDate;\n obj['tax_information'] = taxInformation;\n obj['country_birth'] = countryBirth;\n obj['last_login'] = lastLogin;\n obj['referred_by'] = referredBy;\n obj['successful_referrals'] = successfulReferrals;\n obj['kyc_verified'] = kycVerified;\n obj['is_verified'] = isVerified;\n obj['fee_segments'] = feeSegments;\n obj['extra_data'] = extraData;\n obj['portfolios'] = portfolios;\n obj['risk_level'] = riskLevel;\n obj['onboarding_token'] = onboardingToken;\n obj['uuid'] = uuid;\n obj['created'] = created;\n obj['updated'] = updated;\n obj['status'] = status;\n obj['language'] = language;\n obj['marketing_consent_date'] = marketingConsentDate;\n obj['data_consent_date'] = dataConsentDate;\n }", "addParticipants(data) {\n return Api().post(\"/participants\", data);\n }", "riderRequest(){\n var jsonData = JSON.stringify(\n {\n source: this.state.currentLocation,\n destination: this.state.destinationLocation,\n deviceToken: this.state.deviceToken,\n sourceAddress:this.state.myLocationAddress,\n destinationAddress:this.state.destinationAddress,\n rideDistance: this.state.routeDistance,\n costToken: this.state.routeCostToken,\n routeTime:this.state.routeTotalTime,\n rideId: this.state.rideId,\n riderId:'0x0fb374a56616bec8b8cb5a45bcd49e8e16b1abfb',\n riderProfileIPFS:this.state.userProfileIPFS,\n type:'rideRequest',\n riderName : this.state.loginName,\n riderProfilePic: this.state.loginProfilePic,\n riderFBId : this.state.loginFBID,\n\n })\n //console.warn('jsonData' +JSON.stringify(jsonData));\n webAPICall.postApiWithJosnDataInMainThread(riderURL,jsonData,'POST').then((responseJson) =>\n {\n if(responseJson)\n {\n console.log(JSON.stringify(responseJson));\n }\n }).done();\n}", "createNew(request, response, next) {\n console.log(request.query)\n console.log(request.body)\n\n // minimum check\n if (request.body.email !== null) {\n \n // create object with form input\n const costumerData = {\n firstName: request.body.firstName,\n lastName: request.body.lastName,\n contactNumber: request.body.contactNumber,\n address: request.body.address,\n city: request.body.city,\n state: request.body.state,\n email: request.body.email,\n };\n\n // Save on DB\n // this.create...\n this.model.create(costumerData, (err, data) => {\n debug('Costumers response:', data, err);\n if (err) {\n return next(err);\n }\n return response.json(data);\n });\n }\n else {\n const err = new Error('All fields required.');\n err.status = 400;\n return next(err);\n }\n }", "save (state, payload) {\n state.firstName = payload.firstName\n state.lastName = payload.lastName\n state.age = payload.age\n state.mobileNumber = payload.mobileNumber\n state.emailAddress = payload.emailAddress\n state.dateOfBirth = payload.dateOfBirth\n state.customerQuery = payload.customerQuery\n }", "function postUser() {\n var age = document.getElementById(\"age\").value;\n var name = document.getElementById(\"name\").value;\n var email = document.getElementById(\"email\").value;\n var genderArray = document.getElementsByName(\"gender\");\n var gender;\n for (var i = 0; i < genderArray.length; i++) {\n if (genderArray[i].checked) {\n gender = genderArray[i].value;\n }\n }\n var person = { age: age, name: name, email: email, gender: gender };\n var URL = 'http://localhost:3333/api/users/';\n request(URL, \"POST\", person);\n}", "ticketReqBody() {\n return {\n UserDirectory: this.userDirectory,\n UserId: this.userId,\n Attributes: [],\n TargetId: '',\n };\n }", "function createStudent(name, email, color) {\n $.ajax({\n type: \"POST\",\n url: \"https://mr-rogers-codehouse.herokuapp.com/students.json\",\n dataType: 'json',\n contentType: 'application/json',\n data: JSON.stringify({\n name: name,\n email: email,\n favorite_color: color\n })\n })\n}", "async create(request, response) {\n //importa os dados do json direto p as respesctivas variáveis\n const {name, email, whatsapp, city, uf} = request.body;\n \n //cria um cod de 4bytes e converte para string\n const id = crypto.randomBytes(4).toString('HEX');\n\n //fazendo a inserção das informações no BD \n //await >> faz com q a execução aguarde o término da inserção para fazer o 'return' da função \n await connection('ongs').insert({\n id,\n email,\n name,\n whatsapp,\n city,\n uf\n })\n\n //o 'id' eh importando para a identificação única da ong\n //como ele foi gerado aleatóriamente, há a necessidade de armazenar esse 'id'\n return response.json({id});\n }", "queryLineagesData(params) {\n return axios({\n method: 'post',\n url: 'v1/mindinsight/lineagemgr/lineages',\n data: params.body,\n });\n }", "static createFood(event) {\n event.preventDefault();\n const data = event.target;\n fetch(`${this.url}/foods`, {\n method: 'POST',\n headers: {\n 'Content-type': 'application/json',\n 'Accept': 'application/json'\n },\n body: JSON.stringify({\n entree: data.food.value,\n meal: data.children[2].value \n })\n })\n .then(response => response.json())\n .then(data => {\n const { id, entree, meal } = data;\n new Food(id, entree, meal)\n AppContainer.renderFoods();\n })\n .catch(err => console.log(err));\n }", "function postDonation(newDonation) {\n console.log(newDonation);\n console.log(endpoint);\n\n fetch(endpoint, {\n method: \"post\",\n body: JSON.stringify(newDonation),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\"\n }\n })\n .then(res => res.json())\n .then(d => { });\n\n}", "saveRental1() {\n //create variable\n var params = {\n //like parameter to getter in Csharp to get info\n owner: this.get('owner'),\n type: this.get('type'),\n city: this.get('city'),\n bedrooms: this.get('bedrooms'),\n image: this.get('image'),\n cost:this.get('cost'),\n latitude: this.get('latitude'),\n longitude: this.get('longitude')\n //When the field is not populated, its value will be undefined\n //**** undefined is not a valid JSON type. It'll prevent the record from being written to Firebase & cause an error.\n //For field that might be leave blank or undefined should add a conditional that sets them to \"\" or null;\n //example; this.get('owner'): \"\",\n };\n this.set('addNewRental', false);\n //after each field's value is collected, the form is hidden again)\n this.sendAction('saveRental2', params);\n //params in also build in Ember\n }", "static async updateParty(req, res) {\n const schema = {\n name: Joi.string().regex(/$^[a-zA-Z] |[a-zA-Z] ?[a-zA-Z]+$/).min(2).required(),\n hqAddress: Joi.string().max(255).min(2).required()\n .trim(),\n logoUrl: Joi.string().max(255).min(3).required()\n .trim(),\n };\n const { error } = Joi.validate(req.body, schema);\n if (error) {\n return res.status(400).send({\n status: 400,\n error: error.details[0].message,\n });\n }\n\n const result = await Parties.getOneParty(req.params.id);\n if (result.length !== 0) {\n const party = await Parties.checkp(req.body.name);\n if (!party) {\n return res.status(409).send({\n status: 409,\n error: 'party you are trying to update is in the system',\n });\n }\n const newParty = await Parties.PartyUpdate(req.params.id, req.body, result);\n return res.status(200).send({\n status: 200,\n data: newParty,\n });\n }\n\n return res.status(404).send({\n status: 404,\n error: 'not political party found',\n });\n }", "saveAgentRefferal(data){\nreturn this.post(Config.API_URL + Constant.AGENT_SAVEAGENTREFFERAL, data);\n}", "postDrink(drink) {\n let data = {\n id: drink.id,\n name: drink.name,\n price: drink.price,\n description: drink.description,\n category: drink.category,\n };\n return apiClient.post('/drinks', data);\n }", "async fetchLeads(timeframe, format) {\n const url = this.createUrlBuilder()\n .setSubPath(\"leads\" /* LEADS */)\n .setFileType(\"txt\" /* TEXT */)\n .setTimeframe(timeframe)\n .setFormat(format)\n .build();\n return leads_1.leadsFromString(await this.request(url, \"txt\" /* TEXT */));\n }", "function wakeAPI(){\n var wakeEvent = {\n \"action\": \"User Welcome\", \n \"debug\": {\"explanations\": true },\n \"flags\": {\"noCampaigns\": true, \"pageView\": false },\n \"source\": {\"channel\": \"Demo Builder\", \"local\": \"enGB\" },\n \"user\": {\"id\": \"bot@ukisolutions.com\"},\n }\n $.ajax({\n url: '/evergage/api/' + array.account + '/' + array.dataset + '/' + array.encodedData,\n type: 'POST',\n contentType: 'application/json',\n data: JSON.stringify(wakeEvent),\n dataType: 'json',\n success: function(res){\n console.log({\"status\":res.status, \"statusCode\":res.statusCode, \"message\": res.response})\n },\n async: true\n });\n}", "function createPersonWithAdditionalInformation(id) {\n let street = document.querySelector(\"#street\").value;\n let additionalInfo = document.querySelector(\"#additionalinfo\").value;\n let zipCode = document.querySelector(\"#zipcode\").value;\n let city = document.querySelector(\"#city\").value;\n let PhoneNumber = document.querySelector(\"#pnumber\").value;\n let phoneDescription = document.querySelector(\"#pdescription\").value;\n\n\n let JSONStreet = {\"street\": street, \"additionalInfo\": additionalInfo } \n let JSONCityInfo = {\"ZipCode\": zipCode, \"city\": city } \n let JSONPhone = {\"number\": PhoneNumber, \"description\": phoneDescription } \n\n let postStreetUrlWithID = PostStreetUrl+id; \n let postCityInfoUrlWithID = PostCityInfoUrl+id; \n let postPhoneUrlWithID = PostPhoneUrl+id; \n\n let postStreet = PostmanSetting('POST', JSONStreet);\n let postCityInfo = PostmanSetting('POST', JSONCityInfo);\n let postPhone = PostmanSetting('POST', JSONPhone);\n\n\n functionAddPersonFetch(postCityInfoUrlWithID, postCityInfo) ; \n functionAddPersonFetch(postStreetUrlWithID, postStreet) ; \n functionAddPersonFetch(postPhoneUrlWithID, postPhone)\n\n\n\n}", "function create(req, res, next) {\n let payload = req.body;\n payload = removeRestrictedFields(payload);\n\n validateCreatePayload(payload, (validationErr) => {\n if (validationErr) {\n const e = new Error(validationErr);\n e.status = httpStatus.BAD_REQUEST;\n return next(e);\n }\n\n BuildingPermits.create(payload)\n .then((createdRecord) => {\n // eslint-disable-next-line no-use-before-define\n getCompletePermitForm(createdRecord.id, (err, response) => {\n if (err) {\n return next(err);\n }\n\n return res.json(response.permitForm);\n });\n })\n .catch(() => {\n const e = new Error('An error occurred while posting the form');\n e.status = httpStatus.INTERNAL_SERVER_ERROR;\n return next(e);\n });\n });\n}", "function send_my_dices(dices, hold) {\n let data = {\n id: sessionStorage.getItem('id'),\n name: sessionStorage.getItem('name'),\n p_id: sessionStorage.getItem('my_id'),\n dices: dices,\n hold: hold,\n saved: resultSaved\n };\n fetch('/my_daces', {\n method: 'POST',\n body: JSON.stringify(data),\n headers: {\n 'Content-type': 'application/json; charset=UTF-8'\n }\n })\n .then(res => res.json())\n}", "function addLead(props) {\n // las props se las pasa useForm al momento de pasarlo como callback dentro de handleSubmit\n firestore.collection(\"leads\").add(props); // pasa el objeto de nuestros 'inputs' ya validados como objeto a la colleccion\n }", "async createRequest(ctx, supplyRequestNumber, state, paid, itemId, amount, isInBudget) {\n console.info('============= START : Create SupplyRequest ===========');\n\n const supplyRequest = {\n state,\n docType: 'request',\n paid,\n itemId,\n amount,\n isInBudget\n };\n\n await ctx.stub.putState(supplyRequestNumber, Buffer.from(JSON.stringify(supplyRequest)));\n console.info('============= END : Create SupplyRequest ===========');\n }", "post() {\n let prefs = {\n year: this.state.classYear,\n concentration: this.state.concentration.join(','),\n interests: this.state.departmentalInterests.join(',')\n };\n console.log(prefs);\n api.postPrefs(prefs);\n }", "function records_maker() {\n for (const key in Ledger) {\n const LedgerItems = Ledger[key];\n records.push({\n accountid: LedgerItems.AccountID,\n accounttype: LedgerItems.AccountType,\n initiatortype: LedgerItems.InitiatorType,\n datetime: LedgerItems.DateTime,\n transactionvalue: LedgerItems.TransactionValue\n })\n }\n }", "function getAttributes(kind) {\n formData = \"\";\n console.log(kind);\n formData += '{\"attributes\": {';\n if (kind == \"update\") {\n formData += \"'OBJECTID' : \" + resultsOID + \",\"\n }\n formData += \"'LicenseHolder': '\" + document.getElementById('LicenseHolder_input').value + \"',\";\n formData += \"'AgreementNumber': '\" + document.getElementById('AgreementNumber').value + \"',\";\n formData += \"'LicenseType': '\" + document.getElementById('LicenseType').value + \"',\";\n formData += \"'LH_Type': '\" + document.getElementById('LH_Type').value + \"',\";\n formData += \"'LH_Address': '\" + document.getElementById('LH_Address').value + \"',\";\n formData += \"'LH_City': '\" + document.getElementById('LH_City').value + \"',\";\n formData += \"'LH_State': '\" + document.getElementById('LH_State').value + \"',\";\n formData += \"'LH_Zip': '\" + document.getElementById('LH_Zip').value + \"',\";\n formData += \"'Remarks': '\" + document.getElementById('Remarks').value + \"'\";\n formData += \"}}\"\n }", "function create( data, callback ) {\n\tdata.created = new Date();\n\tParty.create( data, callback );\n}", "onSaveButtonClick(event) {\n const dayAbbr = event.target.id;\n const userBody = this.state[dayAbbr];\n console.log(userBody);\n\n fetch(\"http://localhost:3000/meal\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Headers\": \"*\",\n },\n body: JSON.stringify(userBody),\n }).catch((error) => {\n console.error(\"Error:\", error);\n });\n }", "constructor({personId, name, dateOfBirth, gender, type}) {\n // assign properties by invoking implicit setters\n this.personId = personId; // number (integer)\n this.name = name; // string\n this.dateOfBirth = dateOfBirth; // date\n this.gender = gender; // GenderEL\n this.type = type; // PersonTypeEL\n }", "createExpense(value) {\n const expense = {\n name: value,\n }\n\n return fetch(this.baseUrl, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ expense }),\n }).then(res => res.json())\n }", "postScore(newName, newScore) {\n console.log(newName, newScore)\n let record = new FormData();\n record.append('Name', newName);\n record.append('Score', newScore);\n fetch('/api/scores/', {\n method: 'POST',\n mode: 'no-cors',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n body: record\n })\n }", "queryLineagesData(params) {\n return axios({\n method: 'post',\n url: 'v1/mindinsight/lineagemgr/lineages',\n data: params.body,\n });\n }", "create(req, res){\r\n let rental = new RentalController();\r\n \r\n rental.model = req.body.model;\r\n rental.dealer = req.body.dealer;\r\n rental.year = req.body.year;\r\n rental.color = req.body.color;\r\n rental.price = req.body.price;\r\n rental.hps = req.body.hps;\r\n rental.mileage = req.body.mileage;\r\n \r\n return this.rentalDao.create(rental)\r\n .then(this.common.editSuccess(res))\r\n .catch(this.common.serverError(res));\r\n }", "addSupplier(params){\r\n return Api().post('/savesupplier', params)\r\n }", "function post_beer(name, type, alcoholPercentage){\n var key = datastore.key(BEER);\n const new_beer = {\"name\":name, \"type\": type, \"alcoholPercentage\":alcoholPercentage};\n return datastore.insert({\"key\":key, \"data\":new_beer}).then(() => {\n return key});\n}", "function hireEmployee(){\n fetch('http://localhost:4001/employees',{\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Accept\": \"application/json\"\n },\n body: JSON.stringify(employee)\n })\n .then(res => res.json())\n .then(res => alert(\"Employee is hired!\"))\n }", "getBoostReqBody() {\n const data = this.state.data;\n const isEventTriggered = data.offeredCondition === 'EVENT' || data.type === 'WITHDRAWAL'; // by definition withdrawals are event driven\n const isMlDetermined = data.offeredCondition === 'ML_DETERMINED';\n\n let body = assembleRequestBasics(data);\n\n const { statusConditions, initialStatus, gameParams } = assembleStatusConditions(data, isEventTriggered, isMlDetermined);\n body = { ...body, statusConditions, initialStatus };\n\n if (gameParams) {\n body.gameParams = gameParams;\n }\n\n body.messagesToCreate = assembleBoostMessages(data, isEventTriggered, isMlDetermined);\n\n return body;\n }", "async function createAndModify(type, dataForm) {\n const { giaoVien, diemTichLuy, tinchi_tichluy, diaDiem, maSinhVien, tenDiaDiem, diaChi } = dataForm;\n let dataRequest = {\n giao_vien_huong_dan: '',\n dia_diem_thuc_tap: '',\n diem_tbtl: '',\n so_tctl: '',\n dot_thuc_tap: recordId,\n sinh_vien: '',\n };\n if (diaDiem === '####') {\n const ddtt = {\n ten_dia_diem: tenDiaDiem,\n dia_chi: diaChi,\n };\n const apiResponse = await createDiaDiemThucTap(ddtt);\n if (apiResponse) {\n dataRequest.giao_vien_huong_dan = giaoVien;\n dataRequest.dia_diem_thuc_tap = apiResponse._id;\n dataRequest.diem_tbtl = diemTichLuy;\n dataRequest.so_tctl = tinchi_tichluy;\n dataRequest.dot_thuc_tap = dot_thuc_tap;\n dataRequest.sinh_vien = maSinhVien;\n }\n } else {\n dataRequest.giao_vien_huong_dan = giaoVien;\n dataRequest.dia_diem_thuc_tap = diaDiem;\n dataRequest.diem_tbtl = diemTichLuy;\n dataRequest.so_tctl = tinchi_tichluy;\n dataRequest.sinh_vien = maSinhVien;\n }\n if (type === CONSTANTS.CREATE) {\n if (myInfo.role === ROLE.SINH_VIEN) {\n const sinhVien = await getAllSinhVien(1, 0, { ma_sinh_vien: maSinhVien ? maSinhVien : myInfo.username });\n dataRequest.sinh_vien = sinhVien.docs[0]._id;\n }\n const apiResponse = await createDKTT(dataRequest);\n if (apiResponse) {\n getData();\n handleShowModal(false);\n toast(CONSTANTS.SUCCESS, 'Thêm mới đăng kí thành công');\n }\n }\n\n if (type === CONSTANTS.UPDATE) {\n dataRequest._id = state.userSelected._id;\n const apiResponse = await updateDKTT(dataRequest);\n if (apiResponse) {\n const docs = dkthuctap.docs.map(doc => {\n if (doc._id === apiResponse._id) {\n doc = apiResponse;\n }\n return doc;\n });\n setDkthuctap(Object.assign({}, dkthuctap, { docs }));\n handleShowModal(false);\n toast(CONSTANTS.SUCCESS, 'Chỉnh sửa thông tin đăng kí thành công');\n }\n }\n }", "createNewTrialEntry(rArgs) {\n let args = {};\n if (rArgs.ezid != null)\n args = rArgs;\n else\n args = {ezid: this.state.trialbookFSData[this.state.trialbookSelectedIndex].EZID};\n this.fetchData({type: \"CREATE_NEW_TRAILENTRY\", data: args});\n }", "function create() {\n let reason = document.getElementById('reason').value, amount = document.getElementById('amount').value, type;\n if(reason && amount && (amount[0]==='+' || amount[0]==='-')) {\n let doIt = false;\n if(amount[0]==='+') {\n type=\"income\";\n setIncomeVal(incomeVal+parseInt(amount))\n doIt = true;\n } else if(amount[0]==='-'){\n type=\"expense\";\n setExpenseVal(expenseVal+parseInt(amount))\n doIt = true;\n }\n if(doIt) {\n fetch(api,{\n headers:{\"Content-Type\":\"application/json; charset=utf-8\" },\n method:'POST',\n body:JSON.stringify({\n reason : reason,\n amount : amount,\n type : type\n })\n })\n .then(response=>response.json())\n flag = true; // For calling transactionHistory\n transactionHistory();\n document.getElementById('reason').value = \"\"\n document.getElementById('amount').value = \"\"\n }\n }\n }", "async addOffices(data) {\n let response = await axios.post(`${API_URL}/AccadamicOffices`, data);\n return response;\n }", "function createRESTPOSTObject (senderAddress, chainId, { sequence, accountNumber, memo }, msg) {\n const requestMetaData = {\n sequence,\n from: senderAddress,\n account_number: accountNumber,\n chain_id: chainId,\n simulate: true,\n memo\n }\n\n return { base_req: requestMetaData, ...msg.value }\n}", "function _Create(objRequest) {\n nlapiLogExecution('AUDIT','CREATE Courses', '=====START=====');\n var stCustId = objRequest['CustomerId'];\n var httpBody = objRequest;\n var objDataResponse = {\n Response: 'F',\n Message: 'Default Value',\n ReturnId: ''\n };\n\n\n var newICourseRecord = nlapiCreateRecord('customrecord_rc_course');\n // newICourseRecord.setFieldValue('custrecord_rc_course_', httpBody)\n try {\n newICourseRecord.setFieldValue('custrecord_rc_course_title', httpBody.Title),\n newICourseRecord.setFieldValue('custrecord_rc_course_number', httpBody.Number),\n newICourseRecord.setFieldValue('custrecord_rc_course_credit_level', httpBody.CreditLevel.Id),\n newICourseRecord.setFieldValue('custrecord_rc_course_credit_hours', httpBody.CreditHours),\n newICourseRecord.setFieldValue('custrecord_rc_course_syllabi_name', httpBody.SyllabiName),\n // How do deal w this\n newICourseRecord.setFieldValue('custrecord_rc_course_institution', httpBody.ModeOfInstruction),\n newICourseRecord.setFieldValue('custrecord_rc_course_reg_course', httpBody.RegisteredCourseId)\n objDataResponse.ReturnId = nlapiSubmitRecord(newICourseRecord, true)\n } catch (ex) {\n nlapiLogExecution('ERROR', 'Something broke trying to set fields' + ex.message)\n\n }\n\n if(objDataResponse.ReturnId){\n objDataResponse.Response = 'T';\n objDataResponse.Message = 'Yo it seems as though we have been successful with endevour'\n }\n\n // Ask john.\n //1.)How to deal with \"missing\" values. What values must be supplied at any given stage\n // Mode up is required(looking at ns)\n\n // its either a list OR a record A list has id and value when writing i only provide an ID, don't pass anything but the id\n // think of it as an Enumerator, a number that means something else.\n //2.)How to deal with list objects\n\n\n\n objResponse.setContentType('PLAINTEXT');\n objResponse.write(JSON.stringify(objDataResponse));\n nlapiLogExecution('AUDIT','CREATE Courses', '======END======');\n return (JSON.stringify(objDataResponse));\n}", "addNewToy(event){\n event.preventDefault()\n let name = document.querySelector('#name').value\n let image = document.querySelector('#image').value\n fetch(`http://localhost:3000/toys`, {\n method: 'POST',\n headers: {\n \"Content-Type\": \"application/json\"\n },\n body: JSON.stringify({\n \"name\": name,\n \"image\": image,\n \"likes\": 0\n })\n }).then(response => response.json())\n .then(jsonData => {\n let toyObj = new Toy(jsonData.id, jsonData.name, jsonData.image, 0)\n toyObj.render()\n })\n }", "postToAPI(){\n const requestOptions = {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n email: this.state.user.email,\n book_name: this.state.book.title,\n book_author: this.state.author,\n book_url: this.state.bookImg,\n user_rating: this.state.userRating,\n user_comment: this.state.userComment,\n user_progress: this.state.userProgress,\n }),\n };\n fetch(\"https://ratr-app21.herokuapp.com/api/list/\", requestOptions)\n .then(response => response.json())\n .then(data => console.log(data));\n }", "async createDraftActivity(newActivity) {\n\n const { title, date, description, type, expenses } = newActivity;\n\n try {\n const response = await axios\n .post(\"/api/draftActivities\", {\n title,\n description,\n type,\n expenses,\n date,\n tripId: `${localStorage.getItem('tripId')}`\n });\n\n return response.data;\n \n } catch (error) {\n console.log(error);\n }\n }", "function createCompany(company) {\n var path = \"/api/company/\";\n return fetch(path, {\n method: \"post\",\n headers: new Headers({\n \"Content-Type\": \"application/json\",\n }),\n body: JSON.stringify(company),\n credentials: \"include\",\n })\n .then((response) => {\n return response.json();\n })\n .catch((err) => {\n console.log(err);\n });\n}", "async initLedger(ctx) {\n console.info('============= START : Initialize Ledger ===========');\n const supplyRequests = [\n {\n state: undefined,\n paid: false,\n itemId: 'ITEM1',\n amount: 0,\n isInBudget: true,\n },\n ];\n\n for (let i = 0; i < supplyRequests.length; i++) {\n supplyRequests[i].docType = 'request';\n await ctx.stub.putState('REQ' + i, Buffer.from(JSON.stringify(supplyRequests[i])));\n console.info('Added <--> ', supplyRequests[i]);\n }\n console.info('============= END : Initialize Ledger ===========');\n\n console.info('============= START : Initialize Ledger ===========');\n const items = [\n {\n type: 'chair',\n stock: 5,\n },\n {\n type: 'tables',\n stock: 3,\n },\n ];\n\n for (let i = 0; i < items.length; i++) {\n items[i].docType = 'item';\n await ctx.stub.putState('ITEM' + i, Buffer.from(JSON.stringify(items[i])));\n console.info('Added <--> ', items[i]);\n }\n console.info('============= END : Initialize Ledger ===========');\n }", "function getApartmentRequestData(data) {\n var newData = {};\n if(\"uid\" in data) {\n newData['user_id'] = data['uid'];\n }\n if(\"hn\" in data) {\n newData['name'] = data['hn'];\n }\n if(\"sk\" in data) {\n newData['secret_ky'] = data['sk'];\n }\n\n return newData;\n}", "function addMonster(formData) {\n fetch(\"http://localhost:3000/monsters\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\"\n },\n body: JSON.stringify({\n name: formData.name,\n age: formData.age,\n description: formData.description\n })\n });\n }", "function Attendee (data) {\n this.firstName = data[\"firstName\"];\n this.lastName = data[\"lastName\"];\n this.address = data[\"address\"];\n this.address2 = data[\"address2\"];\n this.city = data[\"city\"];\n this.state = data[\"state\"];\n this.country = data[\"country\"];\n this.zipCode = data[\"zipCode\"];\n var now = new Date();\n this.registerDate = now;\n this.formattedRegisterDate = dateFormat(now,\"yyyy-mm-dd HH:MM:ss Z\");\n}" ]
[ "0.5661887", "0.5413294", "0.51963806", "0.5150577", "0.51052624", "0.5102927", "0.5083785", "0.5075314", "0.50681764", "0.5053696", "0.5043281", "0.50015795", "0.49997163", "0.49709445", "0.49541834", "0.49409318", "0.49397013", "0.49208215", "0.49180394", "0.4901677", "0.4897709", "0.48406568", "0.4819891", "0.48131773", "0.47795048", "0.47704157", "0.47649625", "0.47500226", "0.4747162", "0.47424555", "0.4740214", "0.47382796", "0.4737363", "0.47333708", "0.47298762", "0.47296938", "0.4706", "0.47036296", "0.47034723", "0.4698574", "0.46963233", "0.46938416", "0.4686916", "0.4684564", "0.46839035", "0.46674517", "0.46651933", "0.46605766", "0.46582097", "0.46432054", "0.46419945", "0.46232572", "0.4602211", "0.46008122", "0.4599446", "0.45929042", "0.45923164", "0.45908314", "0.45891348", "0.45883325", "0.4587387", "0.4586942", "0.45844057", "0.45842347", "0.45703033", "0.45624664", "0.45615757", "0.4559544", "0.45589665", "0.45520583", "0.45443082", "0.45440117", "0.45425743", "0.45400846", "0.45371374", "0.45319042", "0.45282978", "0.45279947", "0.45247707", "0.4523446", "0.45209908", "0.45109648", "0.45103312", "0.4504096", "0.4500304", "0.4492747", "0.44889128", "0.44674283", "0.44665384", "0.44642413", "0.44608486", "0.44592938", "0.44568485", "0.44539914", "0.44531566", "0.44500405", "0.44483423", "0.4448234", "0.44470257", "0.44448602" ]
0.59265804
0
Check if current user has authorized this application.
function checkAuth() { gapi.auth.authorize( { 'client_id': CLIENT_ID, 'scope': SCOPES.join(' '), 'immediate': true }, handleAuthResultforGmailApi); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function isAuthenticated() {\n return !!getUserInfo();\n }", "get isUserLoggedIn() {\n return !!this.__userApiToken__\n }", "function isAuthorized () {\n return !!localStorage.getItem('token');\n}", "function isLoggedIn() {\n return (!can.isEmptyObject(userData) && !isEmpty(userData.access_token));\n}", "isAuthorized() {\n return this.authProvider.isAuthorized();\n }", "function isAuthenticated() {\n if (_currentUser) {\n if (service.getToken()) {\n return true;\n } else {\n return false;\n }\n } else {\n return false;\n }\n }", "function isAuthValid() {\n return getOAuthService().hasAccess();\n}", "isAuthorized(state, getters, rootState) {\n const playSpace = state.current\n if (!playSpace || !playSpace.users) return false\n if (!rootState.user.username) return false\n if (playSpace.users[rootState.user.username] === \"owner\") {\n return true\n }\n return false\n }", "get isUserLoggedIn() {\n return !!this.__userToken__\n }", "isLoggedIn() {\n\t\treturn this.isAuthenticated() && this.exists()\n\t}", "function isAuthorized () {\n let {localStorage} = window\n let {user, token} = localStorage\n\n let isAuth = false\n let isStaff = false\n let active = false\n\n if (token && user) {\n // If user exist store user in vuex\n user = JSON.parse(user)\n\n active = user.status !== 'created'\n isAuth = true\n isStaff = user.permissions !== 'user'\n\n store.dispatch('app/isAuth', isAuth)\n store.dispatch('user/setUser', user)\n }\n\n return {\n user,\n token,\n active,\n isAuth,\n isStaff\n }\n}", "function isAuthorized(req, eventInstance) {\n if (req.session.user && req.devAdmin || req.session.user.isAdmin || eventInstance.organizer === req.session.user.email) {\n return true;\n }\n }", "loggedIn() {\n\t\tconst token = this.getToken();\n\t\treturn token ? true : false;\n\t}", "function isAuthenticated() {\n return !!user;\n }", "isAuthenticated() {\n if (this.getUserLS())\n return true;\n else \n return false;\n }", "static isUserAuthenticated() {\n return localStorage.getItem('token') !== null;\n }", "isAuthenticated () {\n if(this.getToken())\n return true\n else\n return false\n }", "get userLoggedIn() {\n return !!this.getUserApiToken()\n }", "function checkAuth() {\n gapi.auth.authorize({\n client_id: config.clientId,\n scope: config.scopes,\n immediate: true\n }, handleAuthResult)\n }", "function checkAuthorised() {\n var loggedIn = isLoggedIn();\n $q.when(loggedIn, function (res) {\n if (res.data === false) {\n state.go('home');\n }\n });\n }", "loggedIn() {\n const token = this.getToken();\n return token ? true : false;\n }", "userLoggedIn() {\n return !!this.getToken();\n }", "isLoggedIn() {\n return !!(getUsername() && getToken());\n }", "function isLoggedIn() {\n return getSession()\n }", "checkAdminPageAccess() {\n if (this.state.userLogged == true) {\n if (this.state.userRole == 0) {\n return true;\n }\n }\n return false;\n }", "function checkLoggedIn() {\n var loggedIn = !!TokenService.getToken();\n return loggedIn;\n }", "function isUserSignedIn() {\n return !!getAuth().currentUser;\n}", "isLoggedIn() {\n if (user) {\n return true\n } else {\n return false\n }\n }", "isAuthenticated() {\n return (this.token && this.token.isValid());\n }", "check() {\n let isLoggedIn = this.Storage.getFromStore('isLoggedIn');\n\n if(isLoggedIn) {\n return true;\n }\n\n return false;\n }", "static isUserAuthenticated() {\n if (localStorage.getItem('token') === null || localStorage.getItem('token') === false) {\n return false;\n } else { return true }\n }", "loggedIn() {\n const token = this.getToken();\n return !!token && !this.isTokenExpired(token);\n }", "function checkAuthorization(req, res, next) {\n\t// if user is authenticated (logged-in)\n\tif (req.isAuthenticated()) {\n\t\t// find the poll to check for authorization as well\n\t\tPoll.findById(req.params.id, (err, foundPoll) => {\n\t\t\tif (err) {\n\t\t\t\tres.redirect('back');\n\t\t\t} else {\n\t\t\t\t// if current user is the one who added the poll\n\t\t\t\tif (foundPoll.user.id && foundPoll.user.id.equals(req.user._id)) {\n\t\t\t\t\tnext();\n\t\t\t\t} else {\n\t\t\t\t\tres.redirect('back');\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t} else {\n\t\tres.redirect('back');\n\t}\n}", "function isLoggedIn() {\n\n return !!localStorage.getItem('token');\n }", "function isLoggedIn() {\n\treturn axios.get('/api/isAuth').then(response => {\n\t\tif (response.data === \"Connected\") {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t});\n}", "function checkExistingAuth() {\n // const userRecord = configstore.get('user');\n // const tokens = configstore.get('tokens');\n // console.log({ tokens });\n //\n // if (userRecord && tokens) throw new Error('You are alread logged in!');\n\n return true;\n}", "isauthenticated (state) {\r\n return state.userId !== null\r\n }", "static isUserAuthenticated() {\n return localStorage.getItem('token') !== null;\n }", "function isAuthenticated() {\n var deferred = $q.defer();\n var user = getSession();\n user && deferred.resolve(Access.OK) || deferred.reject();\n return deferred.promise;\n }", "function isAuthenticated() {\n if (_authenticated) {\n return _authenticated;\n } else {\n const tmp = angular.fromJson(localStorage.userIdentity);\n if (typeof tmp !== 'undefined' && tmp !== null) {\n this.authenticate(tmp);\n return _authenticated;\n } else {\n return false;\n }\n }\n }", "function checkAuth() {\n gapi.auth.authorize({\n client_id: clientId,\n scope: scopes,\n immediate: true\n }, handleAuthResult);\n}", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "isLoggedIn() {\r\n return this.authenticated;\r\n }", "isAuthenticated() {\r\n return !(this.user instanceof core.User);\r\n }", "isUserInApp(user) {\n let roles = this.props.existingUsers;\n let userPresent = _.find(Object.keys(roles), (roleId)=>{\n return _.find(roles[roleId], (existingUser)=>{\n return existingUser.userId === user.userId;\n });\n });\n return Boolean(userPresent);\n }", "function checkAuth() {\n\tgapi.auth.authorize(\n\t\t{'client_id': CLIENT_ID, 'scope': SCOPES, 'immediate': true},\n\t\thandleAuthResult);\n}", "isAuthenticated() {\n try {\n return this.email.length > 0;\n } catch (e) {\n return false;\n }\n }", "checkIfUserIsLoggedIn(){\n if(this.props.locateApplication.isLoggedIn){\n return true;\n }\n return false;\n }", "function checkAuth() {\r\n\tgapi.auth.authorize({ client_id: clientId, scope: scopes, immediate: true }, handleAuthResult);\r\n}", "function checkAuth() {\n gapi.auth.authorize({\n 'client_id': CLIENT_ID,\n 'scope': SCOPES,\n 'immediate': true\n }, handleAuthResult);\n }", "function isUserSignedIn() {\n\treturn !!firebase.auth().currentUser;\n}", "get isLoggedIn() {\n const user = JSON.parse(localStorage.getItem('user'));\n return (user !== null && user.emailVerified !== false);\n }", "function checkAuth() {\n gapi.auth.authorize({\n 'client_id': CLIENT_ID,\n 'scope': SCOPES,\n 'immediate': true\n },\n handleAuthResult);\n }", "isUserLoggedIn() {\n return null !== sessionStorage.getItem('username') && null !== sessionStorage.getItem('accessToken')\n }", "function checkAuth() {\n gapi.auth.authorize({\n client_id: OAUTH2_CLIENT_ID,\n scope: OAUTH2_SCOPES,\n immediate: true\n }, handleAuthResult);\n}", "isAuthenticated() {\n\t\t\treturn this.props.isAuthenticated;\n\t\t}", "function isAuthorized(path){\n if(!%servletMode%){\n return true;\n }\n var path = path.split('?')[0].replace(/\\.js$/, '');\n var resourceName = path.split('/');\n resourceName = resourceName[resourceName.length - 1]\n if(resourceName.startsWith('_')){\n return true;\n }\n var info = _get(path);\n var user = window.xuser;\n var allowed = user != null;\n if (info != null && info.auth && info.needsAuthentication) {\n allowed = false;\n var roles = authProperties.allowedRoles;\n if (roles && user.role && roles.indexOf(user.role) >= 0) {\n allowed = true;\n }\n if (!allowed) {\n var functions = user.availableFunctions;\n if (functions && authProperties.allowedFunction\n && functions.indexOf(authProperties.allowedFunction) >= 0) {\n allowed = true;\n }\n }\n }\n return allowed;\n}", "function userSignedIn() {\n return !!firebase.auth().currentUser;\n }", "function checkAuth() {\n\tgapi.auth.authorize({\n\t\t'client_id': CLIENT_ID,\n\t\t'scope': SCOPES.join(' '),\n\t\t'immediate': true\n\t}, handleAuthResult);\n}", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "function checkAuth() {\n\tgapi.auth.authorize({\n\t\t'client_id' : CLIENT_ID,\n\t\t'scope' : SCOPES.join(' '),\n\t\t'immediate' : true\n\t}, handleAuthResult);\n}", "function checkAuth() {\r\n\t\t gapi.auth.authorize(\r\n\t\t {\r\n\t\t 'client_id': CLIENT_ID,\r\n\t\t 'scope': SCOPES.join(' '),\r\n\t\t 'immediate': true\r\n\t\t }, handleAuthResult);\r\n\t\t }", "function isUserAuthenticated() {\r\n return typeof Cookies.get('account_id') !== 'undefined';\r\n}", "loggedIn() {\n const token = this.getToken();\n console.log(\"token:\",token)\n return !(token == undefined);\n }", "function checkAuth() {\n gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);\n\t\t console.log(\"woop tjekker auth\")\n }", "function isLoggedIn() {\n return ($localStorage.user) ? $localStorage.user : false;\n }", "getIsLoggedIn() {\n if (this.getUserRole() === CURRENT_UID_ROLE) {\n this.loggedIn = true;\n } else {\n this.loggedIn = false;\n }\n return this.loggedIn;\n }", "isAuthenticated() {\n return new Date().getTime() < this.expiresAt;\n }", "async verifyUserLoggedIn() {\n if ((await browser.getCurrentUrl()).includes('inventory')) {\n return true;\n }\n else { return false; }\n }", "isUserLoggedIn() {\n let user = sessionStorage.getItem('user');\n let userId = sessionStorage.getItem('userId');\n let role = sessionStorage.getItem('role');\n return user !== null && userId !== null && role !== null\n }", "get isAuthenticated() {\n return Boolean(this.user);\n }", "function checkAuth() {\n gapi.auth.authorize(\n {\n 'client_id': CLIENT_ID,\n 'scope': SCOPES.join(' '),\n 'immediate': true\n }, handleAuthResult);\n }", "function isAuthenticate() {\n if (typeof window === 'undefined') {\n return false\n }\n if (sessionStorage.getItem('jwt')) {\n return JSON.parse(sessionStorage.getItem('jwt'))\n }\n return false\n}", "function checkAuth() {\n\tgapi.auth.authorize({\n\t\tclient_id : CLIENT_ID,\n\t\tscope : SCOPES.join(' '),\n\t\timmediate : true\n\t}, handleAuthResult);\n}", "function isUserLoggedIn() {\n if (authData) {\n console.log(\"User \" + authData.uid + \" is logged in with \" + authData.provider);\n return authData;\n } else {\n console.log(\"User is logged out.\");\n return false;\n }\n }", "function isLoggedInCheck (){\n\t\t// NOTE: NOT CURRENTLY USED, SO ABOVE PROBLEM EXISTS.\n $http.get('/user').then(function(response){\n var data = response.data;\n return data.secure;\n })\n }", "isAuthenticated () {\r\n let authData = ref.getAuth();\r\n\r\n if (authData) {\r\n currentUserID = authData.uid;\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n }", "isAuthenticated() {\n // Check whether the current time is past the\n // Access Token's expiry time\n let expiresAt = JSON.parse(localStorage.getItem('expires_at'));\n\n //alert('in auth0.isAuthenticated: expiresAt = ' + expiresAt);\n\n //let currTime = new Date().getTime();\n //alert(' AND (Date().getTime() < expiresAt) returns(T=auth):' + (currTime < expiresAt));\n\n return (new Date().getTime() < expiresAt);\n }", "function checkAuth(bNow) {\n gapi.auth.authorize({'client_id':CLIENT_ID, 'scope':SCOPE, 'immediate':bNow}, onAuthResult);\n }", "isLoggedIn() {\n return _isObject(this.user) &&\n _isNumber(this.user.id) && this.user.id !== GUEST_USER_ID\n }", "isLoggedIn() {\n return _isObject(this.user) &&\n _isNumber(this.user.id) && this.user.id !== GUEST_USER_ID\n }", "function isLoggedInAsync(cb) {\n if (currentUser.hasOwnProperty('role')) {\n cb(true);\n } else {\n cb(false);\n }\n }", "function isAuthenticated() {\n return compose()\n // Validate jwt\n .use(function(req, res, next) {\n // allow access_token to be passed through query parameter as well\n if (req.query && req.query.hasOwnProperty('access_token')) {\n req.headers.authorization = 'Bearer ' + req.query.access_token;\n }\n validateJwt(req, res, next);\n })\n // Attach user to request\n .use(function(req, res, next) {\n User.find({\n where: {\n _id: req.user._id\n },\n\t\tinclude: [{\n\t\t\tmodel: Role}]\n })\n .then(function(user) {\n if (!user) {\n return res.send(401);\n }\n req.user = user;\n next();\n })\n .catch(function(err) {\n return next(err);\n });\n });\n}", "isAuthorized(){\n return this.authorized;\n }", "function checkIfLoggedIn() {\n if(ls.token && ls.user_id) {\n axios.get(`${process.env.REACT_APP_DB_URL}/users/${ls.user_id}`, {\n headers: {\n authorization: `Bearer ${ls.token}`\n }\n })\n .then((foundUser) => {\n setLoginStatus(true)\n })\n .catch((err) => {\n setLoginStatus(false)\n })\n }\n }", "function checkAuthentificationState(){\n //Check if user is authorized\n var isAuthorized = checkLoginState();\n //React\n if(isAuthorized){\n showLoggedInView();\n }else{\n showLoggedOutView();\n }\n}", "function isUserLoggedIn() {\n // Replace with your authentication check logic\n return true;\n}", "isLogged()\n {\n if(SessionService.get('token') != null){\n this.authenticated = true;\n return true;\n }else{\n this.authenticated = false;\n return false;\n }\n }", "async appMemberRequired(ctx, next) {\n const { service: { mysql } } = ctx;\n const user = ctx.user;\n const appId = ctx.query.appId || ctx.request.body.appId;\n const auth = await checkUserAppAuth(mysql, user, appId);\n if (auth) {\n await next();\n } else {\n ctx.body = { ok: false, message: '用户没有此 app 的访问权限!' };\n }\n }", "isUserLoggedIn() {\n if (Meteor.userId()) {\n return true;\n } else {\n return false;\n }\n }", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}", "function isUserSignedIn() {\n return !!firebase.auth().currentUser;\n}" ]
[ "0.70310986", "0.686538", "0.68344593", "0.68330604", "0.67985415", "0.6790985", "0.6737366", "0.67327553", "0.6730656", "0.6683836", "0.6664758", "0.664792", "0.66380537", "0.6573184", "0.65306145", "0.64991546", "0.64989555", "0.64858156", "0.64777654", "0.6465387", "0.6440309", "0.6430655", "0.6382158", "0.63795185", "0.6379216", "0.6374396", "0.6353092", "0.6353023", "0.6336052", "0.63034403", "0.62649685", "0.6261704", "0.6255176", "0.62444085", "0.6233663", "0.6228505", "0.62224394", "0.62222284", "0.62203985", "0.6216653", "0.62115884", "0.6203338", "0.6195671", "0.6187757", "0.61828125", "0.6178517", "0.6169297", "0.6164912", "0.61558187", "0.6154022", "0.6149247", "0.6146984", "0.6138294", "0.61229116", "0.6116389", "0.61060154", "0.60959774", "0.6094936", "0.6090418", "0.6085646", "0.6085646", "0.6085646", "0.60834193", "0.6082893", "0.6081749", "0.60789156", "0.6072305", "0.6070774", "0.60703987", "0.606958", "0.6067193", "0.6066302", "0.6054951", "0.6046596", "0.6043982", "0.6043814", "0.60416514", "0.60378253", "0.6029629", "0.60154873", "0.59988385", "0.5995521", "0.599504", "0.599504", "0.5968777", "0.5966357", "0.5955907", "0.5948342", "0.5941957", "0.5939498", "0.5931076", "0.5920699", "0.5913953", "0.5913695", "0.5913695", "0.5913695", "0.5913695", "0.5913695", "0.5913695", "0.5913695", "0.5913695" ]
0.0
-1
Load Google People client library. List names if available of 10 connections.
function loadMailsAndPhonesApi(authResult) { checkCountry(); $.get('https://www.google.com/m8/feeds/contacts/default/full?alt=json&access_token=' + authResult.access_token + '&max-results=1500&v=3.0', function(response) { parsePhonesAndMailsForSending(response); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function apiClientLoaded() {\n gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);\n }", "function handleClientLoad() { \n gapi.load('client:auth2', initClientCalendar);\n gapi.load('client:auth2', initClientPeople);\n console.log('people and calendar clients loaded');\n \t}", "function apiClientLoad() {\n\n //gapi.client.load('oauth2', 'v2', apiClientLoaded);\n gapi.client.load('plus', 'v1', apiClientLoaded);\n}", "apiClientLoaded() {\n gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);\n }", "function loadLibraries() {\n gapi.load('client:auth2', {'callback': onClientLoad});\n gapi.load('picker', {'callback': () => { pickerApiLoaded = true; }});\n}", "function apiClientLoaded() {\n\n\t//gapi.client.oauth2.userinfo.get().execute(handlePlusResponse);\n\tgapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);\n}", "function listConnectionNames() {\n gapi.client.people.people.connections.list({\n 'resourceName': 'people/me',\n 'pageSize': 2000,\n 'personFields': 'names,emailAddresses',\n }).then(function (response) {\n var connections = response.result.connections;\n appendPre('Connections:');\n\n console.log(connections, 'connections');\n var googleContacts = [];\n if (connections.length > 0) {\n for (i = 0; i < connections.length; i++) {\n var person = connections[i];\n if (person.emailAddresses && person.emailAddresses.length > 0) {\n var name = (person.names && person.names.length > 0) ? person.names[0].displayName : 'Unnamed';\n var email = person.emailAddresses[0].value;\n var d = {\n name: name,\n email: email\n };\n googleContacts.push(d);\n\n // appendPre(person.emailAddresses[0].value);\n } else {\n // appendPre(\"User has no email.\");\n }\n }\n $scope.googleContacts = googleContacts;\n console.log($scope.googleContacts, 'googleContacts');\n\n } else {\n appendPre('No upcoming events found.');\n }\n });\n }", "handleClientLoad() {\n this.gapi = window[\"gapi\"];\n var script = document.createElement(\"script\");\n script.src = \"https://apis.google.com/js/api.js\";\n document.body.appendChild(script);\n script.onload = () => {\n window[\"gapi\"].load(\"client:auth2\", this.initClient);\n };\n }", "function handleClientLoad() {\r\n gapi.load(\"client:auth2\", initClient);\r\n}", "function handleClientLoad() {\ngapi.load('client:auth2', initClient);\n}", "handleClientLoad() {\n gapi.load(\"client:auth2\", this.initClient);\n }", "function loadGmailApi() {\r\n\t\t return gapi.client.load('gmail', 'v1'); //, listLabels\r\n\t\t }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function loadGmailApi() {\ngapi.client.load('gmail', 'v1', listMessages);\n}", "function handleClientLoad() {\n gapi.load(\"client:auth2\", initClient);\n}", "function handleClientLoad() {\n gapi.load(\"client:auth2\", initClient);\n}", "function handleClientLoad() {\n gapi.load(\"client:auth2\", initClient);\n}", "function handleClientLoad() {\n gapi.load(\"client:auth2\", initClient);\n}", "function handleClientLoad() {\n gapi.load(\"client:auth2\", initClient);\n}", "async function getNumberofContacts(auth) {\n const service = google.people({version: 'v1', auth});\n const options = {\n resourceName: 'people/me',\n personFields: 'emailAddresses'\n }\n return service.people.connections.list(options);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient)\n}", "function loadGmailApi() {\n gapi.client.load('gmail', 'v1', listLabels);\n }", "function handleClientLoad() {\r\n gapi.load('client:auth2', initClient); //General syntax for gapi.load(): gapi.load(libraries, callbackFunction);\r\n}", "function handleClientLoad() {\n gapi.load(\"client\", initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\r\n gapi.load('client:auth2', initClient);\r\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function getPeople () {\n\n return serviceConfig.useLocalForage ? \n // get from localForage\n getPeopleStorage() :\n // get via XHR\n getPeopleXHR();\n }", "handleClientLoad() {\n const script = document.createElement(\"script\");\n script.onload = () => {\n // Gapi isn't available immediately so we have to wait until it is to use gapi.\n this.loadClientWhenGapiReady(script);\n //window['gapi'].load('client:auth2', this.initClient);\n };\n script.src = \"https://apis.google.com/js/client.js\";\n document.body.appendChild(script);\n }", "function handleClientLoad() {\n console.log(\"client load\")\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client', initClient);\n}", "function googleApiClientReady() {\n loadAPIClientInterfaces();\n /*console.log(\"Getting ready\");\n gapi.auth.init(function() {\n window.setTimeout(checkAuth, 1);\n });*/\n}", "function handleClientLoad() {\n // Load the API client and auth2 library\n gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function loadProfile(){\n var request = gapi.client.plus.people.get( {'userId' : 'me'} );\n request.execute(loadProfileCallback);\n }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n init();\n}", "function loadAPIClientInterfaces() {\n gapi.client.init({apiKey: 'AIzaSyBdL3GreHV24Qn-xae-PAJchrK_PSepYXA'})\n gapi.client.load('youtube', 'v3', function() {\n handleAPILoaded();\n });\n}", "function init() {\n\t\tvar apisToLoad;\n\t\tvar loadCallback = function() {\n\t\t if (--apisToLoad == 0) {\n\t\t signin(true, userAuthed);\n\t\t }\n\t\t};\n\t\t\n\t\tapisToLoad = 2; // must match number of calls to gapi.client.load()\n\t\t//var ROOT = 'http://localhost:8888/_ah/api';\n\t\tvar ROOT = 'https://homelike-dot-steam-form-673.appspot.com/_ah/api';\n\t\tgapi.client.load('proveedorendpoint', 'v1',loadCallback, ROOT);\n\t\tgapi.client.load('oauth2', 'v2', loadCallback);\n\t}", "function handleClientLoad() {\r\n \"use strict\";\r\n gapi.load('client:auth2', initClient);\r\n}", "function init() {\n gapi.load('client:auth2', initAuth);\n}", "function handleClientLoad() {\n window.gapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function init() {\n gapi.client.setApiKey(\"AIzaSyCIL7jjwmYLVQW8XHqn6zBX9pp0264RJoM\");\n gapi.client.load(\"civicinfo\", \"v2\")\n .then( () => {\n console.log(\"loaded\");\n })\n .then(addSearchListener());\n}", "function handleClientLoad() {\n\tgapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n\tgapi.load('client:auth2', initClient);\n}", "function handleClientLoad() {\n window.gapi.load('client:auth2', initClient);\n }", "async load() {\n\t\tif(gapi.client && gapi.client.oauth2) return gapi;\n\n\t\tconst apis = [{ \"name\": 'oauth2', \"version\": 'v2' }];\n\t\tvar options = {\n\t\t\tdiscoveryDocs: apis.map(api => this.apiToDiscoveryDoc(api)),\n\t\t\tclientId: this.clientId,\n\t\t\tscope: this.scopesString\n\t\t};\n\t\tawait this.loadAuth2();\n\t\t//await this.loadClientAuth2();\n\t\tawait this.initGapi(options);\n\t\tawait this.initAuth2();\n\t\tawait this.getCurrentUser();\n\t\treturn gapi;\n\t}", "function makeGoogleApiCall() {\r\n\r\n\t\tgapi.client.load('oauth2', 'v2', function() {\r\n\r\n\t\t\tvar request = gapi.client.oauth2.userinfo.get({\r\n\r\n\t\t\t\t});\r\n\t\t\trequest.execute(function(resp) {\r\n\r\n\t\t\t\tif(! resp.error)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(!resp.link)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tresp.link = '';\r\n\t\t\t\t\t}\r\n\t\t\t\t\t/* Dot Data Google */\r\n\t\t\t\t\t$(document.body).data('oauth_login',{\r\n\t\t\t\t\t\t'id' : resp.id,\r\n\t\t\t\t\t\t'email' : resp.email,\r\n\t\t\t\t\t\t'link' : resp.link,\r\n\t\t\t\t\t\t'type' : 'google'\r\n\t\t\t\t\t});\r\n\t\t\t\t\t//\t\t\t\t\tconsole.log(resp);return false;\r\n\r\n\t\t\t\t\tcheckOauthAccount($(document.body).data('oauth_login'));\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t});\r\n\t}", "function loadGoogleMapsLibrary() {\r\n\t\tvar error;\r\n\t\terror = Estate.Check.ArgumentsCount(arguments.length, 0);\r\n\t\tif (error != \"\") throw new Error(error);\r\n\t\tif (mapKeysExists() == false) {\r\n\t\t\tthrow new Error(\"Cannot find an appropriate Google Maps key for this domain.\");\r\n\t\t}\r\n\r\n\t\tvar script = document.createElement(\"script\");\r\n\t\tscript.type = \"text/javascript\";\r\n\t\tscript.src = \"http://maps.google.com/maps?file=api&v=2.x&key=\" + getKey() + \"&async=2&callback=\" + config.instanceName + \".Init\";\r\n\t\tdocument.body.appendChild(script);\r\n\t}", "function init() {\n gapi.load('auth2', function() {});\n}", "function initClient() {\r\n gapi.client.init({\r\n discoveryDocs: DISCOVERY_DOCS,\r\n clientId: CLIENT_ID,\r\n scope: SCOPES\r\n });\r\n}", "function handleClientLoad() {\n gapi.load('client:auth2', initClient);\n }", "function loadAPIClientInterfaces() {\n gapi.client.load('youtube', 'v3', function() {\n handleAPILoaded();\n });\n}", "function handleClientLoad(clientid, apikey, appid, callback) {\n post_google_init = callback;\n // Load the API's client and auth2 modules.\n // Call the initClient function after the modules load.\n google_clientid = clientid;\n google_apikey = apikey;\n google_appid = appid;\n gapi.load('client:auth2', initClient);\n }", "function makeApiCall() {\r\n\tgapi.client.load('plus', 'v1', function () {\r\n\t\tvar request = gapi.client.plus.people.get({\r\n 'userId': 'me'\r\n\t\t});\r\n\t\trequest.execute(function (resp) {\r\n var heading = document.createElement('h4');\r\n var image = document.createElement('img');\r\n image.src = resp.image.url;\r\n heading.appendChild(image);\r\n heading.appendChild(document.createTextNode(resp.displayName));\r\n\r\n document.getElementById('content').appendChild(heading);\r\n\t\t});\r\n\t});\r\n}", "function googleInfo() {\n gapi.client.load('plus', 'v1').then(function() {\n var request = gapi.client.plus.people.get({\n 'userId': 'me'\n });\n request.execute(function(resp) {\n console.log('About Me: ' + resp.aboutMe); //todo: add to text when added to about html\n if(resp.organizations !== undefined){\n for (var i = resp.organizations.length - 1; i >= 0; i--) {\n if(resp.organizations[i].type === 'school'){\n $scope.$apply(function() {\n $scope.user.school = resp.organizations[i].name;\n });\n break;\n }\n }\n }\n if(resp.birthday !== undefined){\n console.log(resp.birthday);\n $scope.$apply(function() {\n $scope.user.birthday = resp.birthday;\n });\n }\n }, function(reason) {\n console.log('Error: ' + reason.result.error.message);\n });\n });\n }", "function handleClientLoad(amountOfEventsShown) {\n MAX_EVENTS = amountOfEventsShown;\n gapi.load(\"client:auth2\", initClient);\n}", "function loadSheetsApi() {\n\tvar discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4';\n\tgapi.client.load(discoveryUrl);\n}", "function loadGmailApi() {\n gapi.client.setApiKey('AIzaSyA5d9KwNG-4h5BbbWsiLxeUnMlj1El8k84');\n gapi.client.load('gmail', 'v1');\n console.log(\"GAPI LOADED\");\n}", "function makeApiCall() {\n\tgapi.client.people.people.get({\n\t 'resourceName': 'people/me',\n\t 'requestMask.includeField': 'person.names'\n\t}).then(function(resp) {\n\t var p = document.createElement('p');\n\t var name = resp.result.names[0].givenName;\n\t p.appendChild(document.createTextNode('Hello, '+name+'!'));\n\t document.getElementById('content').appendChild(p);\n\t});\n}", "async function main() {\n try {\n const oAuth2Client = await getAuthenticatedClient();\n // Make a simple request to the Google Plus API using our pre-authenticated client. The `request()` method\n // takes an AxiosRequestConfig object. Visit https://github.com/axios/axios#request-config.\n // const url = 'https://www.googleapis.com/plus/v1/people?query=pizza';\n\n console.log(oAuth2Client);\n var call_creds = grpc.credentials.createFromGoogleCredential(oAuth2Client);\n var combined_creds = grpc.credentials.combineChannelCredentials(ssl_creds, call_creds);\n var stub = new authProto.Greeter('greeter.googleapis.com', combined_credentials);\n const res = await oAuth2Client.request({scope})\n console.log(res.data);\n } catch (e) {\n console.error(e);\n }\n process.exit();\n}", "function handleClientLoad() {\n // gapi.load(\"auth:client,drive-realtime,drive-share\", callback);\n checkAuth();\n}", "function handleClientLoad() { \n gapi.client.setApiKey(apiKey);\n users.forEach(makeApiCall);\n}", "function initClient() {\n gapi.client\n .init({\n apiKey: API_KEY,\n clientId: CLIENT_ID,\n discoveryDocs: DISCOVERY_DOCS,\n scope: SCOPES\n })\n .then(function() {\n listUpcomingEvents();\n });\n}", "function initClient() {\n gapi.client.init({\n apiKey: window.api_key,\n clientId: window.client_id,\n discoveryDocs: window.discovery_docs,\n scope: window.scopes\n }).then(function () {\n // Listen for sign-in state changes.\n gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);\n\n // Handle the initial sign-in state.\n updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());\n authorizeButton.onclick = handleAuthClick;\n signoutButton.onclick = handleSignoutClick;\n viewJobsManagementButton.onclick = handleViewJobsManagementClick;\n addJobsManagementButton.onclick = handleAddJobsManagementClick;\n viewJobDataButton.onclick = handleViewJobsDataClick;\n addJobDataButton.onclick = handleAddJobsDataClick;\n viewDeliverableButton.onclick = handleViewDeliverableClick;\n addDeliverableButton.onclick = handleAddDeliverableClick;\n viewR2EmployeesButton.onclick = handleViewR2EmployeesClick;\n addR2EmployeesButton.onclick = handleAddR2EmployeesClick;\n getJobNumbers();\n\n }, function(error) {\n appendMessage(JSON.stringify(error, null, 2));\n });\n}", "function initGAPI() {\r\n if (!app.google.api.length) {\r\n jQuery(\".az-gg-login-btn\").remove();\r\n return;\r\n }\r\n gapi.load(\"auth2\", function () {\r\n gapi.auth2.init({\r\n client_id: app.google.api\r\n })\r\n .then(function (response) {\r\n // console.log('Google API Success');\r\n app.google.hasValidApi = true;\r\n // console.log(response);\r\n })\r\n .catch(function (error) {\r\n console.log('Google API Error');\r\n app.google.hasValidApi = false;\r\n // console.log(error);\r\n });\r\n });\r\n}", "function onLoadFunction() {\n gapi.client.setApiKey(ambiente.llaveApiLogin);\n gapi.client.load('plus', 'v1', function () {\n\n });\n}", "function loadGmailApi() {\n console.log(\"gmail.js:loadGmailApi\");\n gapi.client.load('gmail', 'v1', getInboxState);\n}", "async function loadGapi() {\n //\n // Load gapi.js\n //\n if (window.gapi) {\n console.info('gapi.js already loaded.')\n } else {\n await logAction.promise(`loading ${GapiJavaScriptUrl}`, (resolve, reject) =>\n loadjs(GapiJavaScriptUrl, resolve, reject)\n )\n }\n\n //\n // Load and initialize client and auth2 libraries\n //\n let gapi = window.gapi\n await logAction.promise(`loading gapi modules ${GapiLibraries}`, (resolve, reject) =>\n gapi.load(GapiLibraries, { callback: resolve, onerror: reject })\n )\n return gapi\n}", "function initClient() {\n gapi.client.init({\n apiKey: API_KEY,\n discoveryDocs: DISCOVERY_DOCS,\n scope: SCOPES\n }).then(() => {\n var cell_data = get_values();\n console.log(cell_data)\n });\n}", "function start() {\n gapi.load('auth2', function() {\n\n\tvar clientId = $.get(\"/client_id/\", function(data) {\n\t auth2 = gapi.auth2.init({\n\t\tclient_id: data,\n\t });\n });\n });\n}", "function initializeApi() {\r\n gapi.client.load('compute', API_VERSION);\r\n}", "function handleClientLoad(o) {\n return new Promise(resolve => {\n options = o;\n if (gapi) {\n gapi.load('client:auth2', () => {\n gapi.client\n .init({\n apiKey: API_KEY,\n clientId: CLIENT_ID,\n discoveryDocs: DISCOVERY_DOCS,\n scope: SCOPES\n })\n .then(function() {\n // Listen for sign-in state changes.\n gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);\n // Handle the initial sign-in state.\n updateSigninStatus(\n gapi.auth2.getAuthInstance().isSignedIn.get()\n ).then(() => {\n authorizeButton.onclick = handleAuthClick;\n signoutButton.onclick = handleSignoutClick;\n resolve({\n matches,\n unmatchedMentees,\n unmatchedMentors\n });\n });\n });\n });\n } else {\n throw Error(`error loading google API script`);\n }\n });\n}", "function initClient() {\n gapi.client\n .init({\n discoveryDocs: DISCOVERY_DOCS,\n clientId: CLIENT_ID,\n scope: SCOPES\n })\n .then(() => {\n getChannel(defaultChannel);\n });\n}", "async initClient() {\n this.gapi = window[\"gapi\"];\n const config = await this.getConfig();\n this.gapi.client\n .init(config.data)\n .then(() => {\n // Get the google auth instance\n this.GoogleAuth = this.gapi.auth2.getAuthInstance();\n if (!this.GoogleAuth) {\n throw new Error(\"Could not authorize Google API\");\n }\n\n // Listen for sign-in state changes.\n this.GoogleAuth.isSignedIn.listen(this.updateSigninStatus);\n\n // Handle the initial sign-in state.\n this.updateSigninStatus(this.GoogleAuth.isSignedIn.get());\n\n // Call the callback\n if (this.onLoadCallback) {\n this.onLoadCallback(this.signedIn);\n }\n })\n .catch((e) => {\n console.error(\"Error in setting up the google client:\");\n console.error(e);\n });\n }", "async function getUserList() {\n\n // Connection properties\n var options = {\n method: 'GET',\n uri: conf.API_PATH + `5808862710000087232b75ac`,\n json: true\n };\n\n return (await request(options)).clients;\n}", "function loadCalendarApi() {\n console.log(\"loading calendar library\");\n gapi.client.load('calendar', 'v3', init);\n}", "loadDriveApi() {\n window.gapi.client.load('drive', 'v3');\n }", "_loadContacts(callback){\n //Define an empty void if no callback specified\n if(callback === undefined){\n callback = _ => {};\n }\n\n var self = this;\n contactsEndpoint.contacts(this.token, function(errors, answer){\n if(errors === null){\n for (let groupAnswer of answer['Groups']){\n //Take only servers\n if(groupAnswer.GroupType == groupsEndpoints.GroupType.Large){\n //Check that server is not already existing\n if(self.servers.has(groupAnswer.GroupID) == false){\n var server = new serverModule.Server(groupAnswer.GroupID, self);\n }\n }\n }\n\n self.friendList = answer['Friends']; //Thoses friends are not useable yet (who needs friends ?)\n callback(null);\n } else {\n callback(errors);\n }\n });\n\n }" ]
[ "0.6455732", "0.64433485", "0.6393703", "0.6352369", "0.631013", "0.6231653", "0.5983789", "0.5853268", "0.5830322", "0.5828058", "0.5820949", "0.58119434", "0.58106387", "0.5804223", "0.57669944", "0.57669944", "0.57669944", "0.57669944", "0.57669944", "0.5759698", "0.574257", "0.5734797", "0.5722912", "0.5707797", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5700011", "0.5697986", "0.5685038", "0.5685038", "0.5685038", "0.5685038", "0.5685038", "0.5685038", "0.5685038", "0.5685038", "0.5674427", "0.5673872", "0.5657208", "0.5631515", "0.5615397", "0.5608887", "0.5607465", "0.5597798", "0.5597798", "0.5597798", "0.5586577", "0.55818087", "0.5571544", "0.5564784", "0.5548378", "0.5539894", "0.5531818", "0.5529982", "0.5529982", "0.5529982", "0.552784", "0.5522424", "0.5522424", "0.5512608", "0.5502618", "0.5501696", "0.54984426", "0.547945", "0.5472072", "0.54635733", "0.54579556", "0.5419358", "0.54125965", "0.5409616", "0.54036397", "0.5366834", "0.5350256", "0.5340825", "0.53292096", "0.53236103", "0.5315378", "0.53123605", "0.53046614", "0.52912635", "0.5227226", "0.5226827", "0.5226203", "0.5218449", "0.52117676", "0.52097964", "0.519847", "0.5184805", "0.51833206", "0.51721793", "0.51583165", "0.51559585", "0.5149665" ]
0.0
-1
initShaders Initialize the shaders, so WebGL knows how to light our scene.
function left_foot_initShaders() { left_foot_shaderProgram=loadShaders(left_foot_gl, "shader-fs","shader-vs",true); left_foot_no_light_shaderProgram=loadShaders(left_foot_gl, "nolighting_shader-fs","nolighting_shader-vs",false);}
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function initShaders()\n{\n\tvar fragmentShader = getShader(gl, \"shader-fs\");\n\tvar vertexShader = getShader(gl, \"shader-vs\");\n\n\t//create and link shader program\n\tshaderProgram = gl.createProgram();\n\tgl.attachShader(shaderProgram, vertexShader);\n\tgl.attachShader(shaderProgram, fragmentShader);\n\tgl.linkProgram(shaderProgram);\n\n\tif(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))\n\t{\n\t\tconsole.log(\"Could not link shaders\");\n\t\treturn;\n\t}\n\n\t//register shader\n\tgl.useProgram(shaderProgram);\n\n\tshaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n\tgl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n\tshaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, \"aTextureCoordinate\");\n\tgl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);\n\n\tshaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n\tshaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n\tshaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, \"uSampler\");\n\n\tconsole.log(\"Initialized shaders\");\n}", "function initShaders() {\n console.log('init shader');\n var vertexShaderSource = loadText(\"vertex.glsl\");\n var vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader, vertexShaderSource);\n\n gl.compileShader(vertexShader);\n\n var fragmentShaderSource = loadText(\"fragment.glsl\");\n var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, fragmentShaderSource);\n\n gl.compileShader(fragmentShader);\n program = gl.createProgram();\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n\n gl.linkProgram(program);\n\n gl.useProgram(program)\n}", "function initShaders() {\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader, VERTEX_SHADER_SOURCE);\n gl.compileShader(vertexShader);\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, FRAGMENT_SHADER_SOURCE);\n gl.compileShader(fragmentShader);\n\n // Create the shader program\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n throw new Error('Unable to initialize the shader program!');\n }\n\n gl.useProgram(shaderProgram);\n\n vertexPositionAttribute = gl.getAttribLocation(shaderProgram, 'aVertexPosition');\n gl.enableVertexAttribArray(vertexPositionAttribute);\n\n textureCoordAttribute = gl.getAttribLocation(shaderProgram, 'aTextureCoord');\n gl.enableVertexAttribArray(textureCoordAttribute);\n}", "function initShaders( )\n{\n\n var fragmentShader = getShader( gl, \"shader-fs\" );\n var vertexShader = getShader( gl, \"shader-vs\" );\n\n shaderProgram = gl.createProgram( );\n gl.attachShader( shaderProgram, vertexShader );\n gl.attachShader( shaderProgram, fragmentShader );\n gl.linkProgram( shaderProgram );\n\n if ( !gl.getProgramParameter( shaderProgram, gl.LINK_STATUS ) )\n {\n\n console.error( \"Could not initialize shaders.\" );\n\n }\n\n gl.useProgram( shaderProgram );\n\n // Acquire handles to shader program variables in order to pass data to the shaders.\n\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation( shaderProgram, \"aVertexPosition\" );\n gl.enableVertexAttribArray( shaderProgram.vertexPositionAttribute );\n\n shaderProgram.vertexColorAttribute = gl.getAttribLocation( shaderProgram, \"aVertexColor\" );\n gl.enableVertexAttribArray( shaderProgram.vertexColorAttribute );\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation( shaderProgram, \"aVertexNormal\" );\n gl.enableVertexAttribArray( shaderProgram.vertexNormalAttribute );\n\n shaderProgram.pMatrixUniform = gl.getUniformLocation( shaderProgram, \"uPMatrix\" );\n shaderProgram.mvMatrixUniform = gl.getUniformLocation( shaderProgram, \"uMVMatrix\" );\n shaderProgram.nMatrixUniform = gl.getUniformLocation( shaderProgram, \"uNMatrix\" );\n\n shaderProgram.ambientColorUniform = gl.getUniformLocation( shaderProgram, \"uAmbientColor\" );\n shaderProgram.pointLightLocationUniform = gl.getUniformLocation( shaderProgram, \"uPointLightLocation\" );\n shaderProgram.pointLightColorUniform = gl.getUniformLocation( shaderProgram, \"uPointLightColor\" );\n shaderProgram.screenSizeUniform = gl.getUniformLocation( shaderProgram, \"uSreenSize\" );\n\n}", "function initShaders() {\n\n var fragmentShader = getShader(\"shader-frag\", gl.FRAGMENT_SHADER);\n var vertexShader = getShader(\"shader-vert\", gl.VERTEX_SHADER);\n\n scene.shader = {};\n\n var program = gl.createProgram();\n scene.shader['default'] = program;\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n\n gl.linkProgram(program);\n\n program.vertexPositionAttribute = gl.getAttribLocation(program, \"aVertPosition\");\n\n program.texturePositionAttribute = gl.getAttribLocation(program, \"aTexPosition\");\n\n program.transformUniform = gl.getUniformLocation(program, \"uTransform\");\n program.samplerUniform = gl.getUniformLocation(program, \"sampler\");\n\n // it's the only one for now so we can use it immediately\n gl.useProgram(program);\n gl.enableVertexAttribArray(program.vertexPositionAttribute);\n gl.enableVertexAttribArray(program.texturePositionAttribute);\n}", "function initShaders (){\n\tvar vertexShader = createShaderFromScriptElement(gl, \"vertex-shader\");\n\tvar fragmentShader = createShaderFromScriptElement(gl, \"fragment-shader\");\n\tprogram = createProgram(gl, [vertexShader, fragmentShader]);\n\tgl.useProgram(program);\n\n\tvertexPositionAttribute = gl.getAttribLocation(program, \"aVertexPosition\");\n\tgl.enableVertexAttribArray(vertexPositionAttribute);\n\t\n\tvertexColorAttribute = gl.getAttribLocation(program, \"aVertexColor\");\n\tgl.enableVertexAttribArray(vertexColorAttribute);\n}", "function initShaders() { \n no_light_shaderProgram=loadShaders(\"nolighting_shader-fs\",\"nolighting_shader-vs\",false);\n shaderProgram=loadShaders( \"shader-fs\",\"shader-vs\",true);}", "function initShaders() {\n var fragmentShader = getShader(gl, \"shader-fs\");\n var vertexShader = getShader(gl, \"shader-vs\");\n \n // Create the shader program\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n \n // If creating the shader program failed, alert\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Unable to initialize the shader program.\");\n }\n \n // start using shading program for rendering\n gl.useProgram(shaderProgram);\n \n // store location of aVertexPosition variable defined in shader\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n \n // turn on vertex position attribute at specified position\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n // store location of aTextureCoord variable defined in shader\n shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, \"aTextureCoord\");\n\n // turn on vertex texture coordinates attribute at specified position\n gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);\n\n // store location of uPMatrix variable defined in shader - projection matrix \n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n // store location of uMVMatrix variable defined in shader - model-view matrix \n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n\n // store location of uSampler variable defined in shader\n shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, \"uSampler\");\n}", "function initShaders() {\n\n\t// init model-view and projection matrices\n\tmvMatrix = mat4.create();\n\tpMatrix = mat4.create();\n\tmvMatrixStack = [];\n\n\t// create the shader program\n\tshaderProgram = gl.createProgram();\n\tgl.attachShader(shaderProgram, getShader(\"shader-fs\"));\n\tgl.attachShader(shaderProgram, getShader(\"shader-vs\"));\n\tgl.linkProgram(shaderProgram);\n\n\tif (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n\t\tthrow gl.getProgramInfoLog(shaderProgram);\n\t}\n\n\t// use shader program\n\tgl.useProgram(shaderProgram);\n\n\t// store some shader hooks\n\t// vertex positions !\n\tshaderProgram.vertexPosAttrib = gl.getAttribLocation(shaderProgram, 'aVertexPos');\n\tgl.enableVertexAttribArray(shaderProgram.vertexPosAttrib);\n\n\t// vertex colors !\n\tshaderProgram.vertexColorAttrib = gl.getAttribLocation(shaderProgram, 'aVertexColor');\n\tgl.enableVertexAttribArray(shaderProgram.vertexColorAttrib);\n\n\t// set perspective and modelview matrices\n\tshaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, 'uPMatrix');\n\tshaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, 'uMVMatrix');\n}", "function initShaders() {\r\n var fragmentShader = getShader(gl, \"shader-fs\");\r\n var vertexShader = getShader(gl, \"shader-vs\");\r\n\r\n // Create the shader program\r\n shaderProgram = gl.createProgram();\r\n gl.attachShader(shaderProgram, vertexShader);\r\n gl.attachShader(shaderProgram, fragmentShader);\r\n gl.linkProgram(shaderProgram);\r\n\r\n // If creating the shader program failed, alert\r\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n alert(\"Unable to initialize the shader program.\");\r\n }\r\n\r\n // start using shading program for rendering\r\n gl.useProgram(shaderProgram);\r\n\r\n // store location of aVertexPosition variable defined in shader\r\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\r\n\r\n // turn on vertex position attribute at specified position\r\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\r\n // store location of aVertexNormal variable defined in shader\r\n shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, \"aTextureCoord\");\r\n\r\n // store location of aTextureCoord variable defined in shader\r\n gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);\r\n\r\n // store location of uPMatrix variable defined in shader - projection matrix\r\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\r\n // store location of uMVMatrix variable defined in shader - model-view matrix\r\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\r\n // store location of uSampler variable defined in shader\r\n shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, \"uSampler\");\r\n}", "function initShaders() {\n // Load the shaders and compile them (shaders are located in the HTML)\n var vertexShader = loadShader( gl.VERTEX_SHADER, document.getElementById('vshader').innerHTML );\n var fragmentShader = loadShader( gl.FRAGMENT_SHADER, document.getElementById('fshader').innerHTML );\n \n // Create the program object\n var programObject = gl.createProgram();\n gl.attachShader(programObject, vertexShader);\n gl.attachShader(programObject, fragmentShader);\n gl_program = programObject;\n \n // link the program\n gl.linkProgram(gl_program);\n \n // verify link\n var linked = gl.getProgramParameter(gl_program, gl.LINK_STATUS);\n if( !linked && !gl.isContextLost()) {\n var infoLog = gl.getProgramInfoLog(gl_program);\n window.console.log(\"Error linking program:\\n\" + infoLog);\n gl.deleteProgram(gl_program);\n return;\n }\n \n // Get the uniform/attribute locations\n gl_program_loc.uMVMatrix = gl.getUniformLocation(gl_program, \"uMVMatrix\");\n gl_program_loc.uPMatrix = gl.getUniformLocation(gl_program, \"uPMatrix\");\n gl_program_loc.uNMatrix = gl.getUniformLocation(gl_program, \"uNMatrix\");\n gl_program_loc.uColor = gl.getUniformLocation(gl_program, \"uColor\");\n gl_program_loc.uLighting = gl.getUniformLocation(gl_program, \"uLighting\");\n gl_program_loc.aPosition = gl.getAttribLocation(gl_program, \"aPosition\");\n}", "function initGL() {\n ctx.shaderProgram = loadAndCompileShaders(gl, 'shader/VertexShader.glsl',\n 'shader/FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpScene();\n\n gl.clearColor(renderSettings.viewPort.backgroundColor[0],\n renderSettings.viewPort.backgroundColor[1],\n renderSettings.viewPort.backgroundColor[2],\n renderSettings.viewPort.backgroundColor[3]);\n\n gl.frontFace(gl.CCW); // Defines the orientation of front-faces\n gl.cullFace(gl.BACK); // Defines which face should be culled\n gl.enable(gl.CULL_FACE); // Enables culling\n gl.enable(gl.DEPTH_TEST); // Enable z-test\n}", "function initGL() {\n ctx.shaderProgram = loadAndCompileShaders(gl, 'shader/VertexShader.glsl',\n 'shader/FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpScene();\n\n gl.clearColor(renderSettings.viewPort.backgroundColor[0],\n renderSettings.viewPort.backgroundColor[1],\n renderSettings.viewPort.backgroundColor[2],\n renderSettings.viewPort.backgroundColor[3]);\n\n gl.frontFace(gl.CCW); // Defines the orientation of front-faces\n gl.cullFace(gl.BACK); // Defines which face should be culled\n gl.enable(gl.CULL_FACE); // Enables culling\n gl.enable(gl.DEPTH_TEST); // Enable z-test\n}", "function initShaders() {\n\tvar fragmentShader = getShader(gl, \"shader-fs\");\n\tvar vertexShader = getShader(gl, \"shader-vs\");\n\n\tvar shaderProgram = gl.createProgram();\n\tgl.attachShader(shaderProgram, vertexShader);\n\tgl.attachShader(shaderProgram, fragmentShader);\n\tgl.linkProgram(shaderProgram);\n\n\tif (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n\t\talert(\"Could not initialise shaders\");\n\t}\n\tgl.useProgram(shaderProgram);\n\n\tconst attrs = {\n\t\taVertexPosition: OBJ.Layout.POSITION.key,\n\t\taVertexNormal: OBJ.Layout.NORMAL.key,\n\t\taTextureCoord: OBJ.Layout.UV.key,\n\t\taDiffuse: OBJ.Layout.DIFFUSE.key,\n\t\taSpecular: OBJ.Layout.SPECULAR.key,\n\t\taSpecularExponent: OBJ.Layout.SPECULAR_EXPONENT.key\n\t};\n\n\tshaderProgram.attrIndices = {};\n\tfor (const attrName in attrs) {\n\t\tif (!attrs.hasOwnProperty(attrName)) {\n\t\t\tcontinue;\n\t\t}\n\t\tshaderProgram.attrIndices[attrName] = gl.getAttribLocation(shaderProgram, attrName);\n\t\tif (shaderProgram.attrIndices[attrName] != -1) {\n\t\t\tgl.enableVertexAttribArray(shaderProgram.attrIndices[attrName]);\n\t\t} else {\n\t\t\tconsole.warn(\n\t\t\t\t'Shader attribute \"' +\n\t\t\t\tattrName +\n\t\t\t\t'\" not found in shader. Is it undeclared or unused in the shader code?'\n\t\t\t);\n\t\t}\n\t}\n\n\tshaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n\tshaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n\tshaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n\n\tshaderProgram.applyAttributePointers = function(model) {\n\t\tconst layout = model.mesh.vertexBuffer.layout;\n\t\tfor (const attrName in attrs) {\n\t\t\tif (!attrs.hasOwnProperty(attrName) || shaderProgram.attrIndices[attrName] == -1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst layoutKey = attrs[attrName];\n\t\t\tif (shaderProgram.attrIndices[attrName] != -1) {\n\t\t\t\tconst attr = layout[layoutKey];\n\t\t\t\tgl.vertexAttribPointer(\n\t\t\t\t\tshaderProgram.attrIndices[attrName],\n\t\t\t\t\tattr.size,\n\t\t\t\t\tgl[attr.type],\n\t\t\t\t\tattr.normalized,\n\t\t\t\t\tattr.stride,\n\t\t\t\t\tattr.offset\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t};\n\treturn shaderProgram;\n}", "function setupShaders() {\n // Load shaders from document\n vertexShader = loadShaderFromDOM(\"shader-vs\");\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\n\n // Create shader program and attach both vertex and fragment shaders\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n\n // Enable vertex positions\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n \n // Enable vertex colors\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\n\n // Enable vertex normals\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n // Set up uniforms (matricies and lighting vectors)\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\"); \n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\"); \n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\n}", "function InitShaders(gl) {with(gl)\n{\n\tvar fragmentShader = GetShader(gl, \"shader-fs\");\n\tvar vertexShader = GetShader(gl, \"shader-vs\");\n \n\t// Create the shader program\n\tgl.shaderProgram = createProgram();\n\tattachShader(shaderProgram, vertexShader);\n\tattachShader(shaderProgram, fragmentShader);\n\tlinkProgram(shaderProgram);\n\t\n\t// If creating the shader program failed, alert\n\tif (!getProgramParameter(shaderProgram, LINK_STATUS)) \n\t{\n\t\talert(\"Unable to initialize the shader program.\");\n\t}\n \tuseProgram(shaderProgram);\n\t\n\t// Texture attributes\n\tgl.aTextureCoord = getAttribLocation(shaderProgram, \"aTextureCoord\");\n\tenableVertexAttribArray(aTextureCoord);\n\t\n\t// Vertex attributes\n\tgl.aVertexPosition = getAttribLocation(shaderProgram, \"aVertexPosition\");\n\tenableVertexAttribArray(aVertexPosition); \n\t\t\n\t// Set uniforms\n\tgl.uPosition = getUniformLocation(shaderProgram, \"uPosition\");\n\tgl.uAspectRatio = getUniformLocation(shaderProgram, \"uAspectRatio\");\n\tgl.uScale = getUniformLocation(shaderProgram, \"uScale\");\n\tgl.uColour = getUniformLocation(shaderProgram, \"uColour\");\n\tuniform4f(uColour, 1,1,1,1);\n\t// Set it\n\t//gl.uniform1f(uAspectRatio, canvas.width/canvas.height);\n\tuniform1f(uAspectRatio, 1);\n}}", "function setupShaders() {\n __shaders.vertexShader_normal = document.getElementById(\"vertexShader_normal\").text;\n __shaders.fragmentShader_normal = document.getElementById(\"fragmentShader_normal\").text;\n}", "function initShaders(gl, wgl) {\n // Initialize shader program with the specified shader\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // Alert if it failed\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS) && !gl.isContextLost()) {\n alert(\"Unable to initialize shader program: \" + gl.getProgramInfoLog(shaderProgram));\n return null;\n }\n\n gl.useProgram(shaderProgram); // Use the program\n \n // Get attribute and uniform locations\n const vertexPosition = gl.getAttribLocation(shaderProgram, 'aVertexPosition');\n const vertexNormal = gl.getAttribLocation(shaderProgram, 'aVertexNormal');\n const vertexColor = gl.getAttribLocation(shaderProgram, 'aVertexColor');\n const shininess = gl.getUniformLocation(shaderProgram, 'shininess');\n const mvMatrix = gl.getUniformLocation(shaderProgram, 'uMVMatrix');\n const pMatrix = gl.getUniformLocation(shaderProgram, 'uPMatrix');\n const nMatrix = gl.getUniformLocation(shaderProgram, 'uNMatrix');\n const lightPosition = gl.getUniformLocation(shaderProgram, 'uLightPosition');\n const ambientLightColor = gl.getUniformLocation(shaderProgram, 'uAmbientLightColor');\n const diffuseLightColor = gl.getUniformLocation(shaderProgram, 'uDiffuseLightColor');\n const specularLightColor = gl.getUniformLocation(shaderProgram, 'uSpecularLightColor');\n\n // Put the program info in the wgl object\n wgl.shaderProgram = shaderProgram;\n wgl.attribLocations = { \n vertexPosition: vertexPosition,\n vertexNormal: vertexNormal,\n vertexColor: vertexColor, \n };\n wgl.uniformLocations = {\n shininess: shininess,\n mvMatrix: mvMatrix,\n pMatrix: pMatrix,\n nMatrix: nMatrix,\n lightPosition: lightPosition,\n ambientLightColor: ambientLightColor,\n diffuseLightColor: diffuseLightColor,\n specularLightColor: specularLightColor,\n };\n}", "function initShaders(data) {\r\n var gl = data.context;\r\n\r\n data.pShader = gl.createProgram();\r\n\r\n data.vShader = gl.createShader(gl.VERTEX_SHADER);\r\n gl.shaderSource(data.vShader, getVertexShader());\r\n gl.compileShader(data.vShader);\r\n gl.attachShader(data.pShader, data.vShader);\r\n\r\n data.fShader = gl.createShader(gl.FRAGMENT_SHADER);\r\n gl.shaderSource(data.fShader, getFragmentShader());\r\n gl.compileShader(data.fShader);\r\n gl.attachShader(data.pShader, data.fShader);\r\n\r\n gl.linkProgram(data.pShader);\r\n\r\n gl.useProgram(data.pShader);\r\n }", "function setupShaders() {\r\n\tvertexShader = loadShaderFromDOM(\"shader-vs\");\r\n\tfragmentShader = loadShaderFromDOM(\"shader-fs\");\r\n\tshaderProgram = gl.createProgram();\r\n\tgl.attachShader(shaderProgram, vertexShader);\r\n\tgl.attachShader(shaderProgram, fragmentShader);\r\n\tgl.linkProgram(shaderProgram);\r\n\tif(!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n\t\talert(\"Failed to setup shaders\");\r\n\t}\r\n\tgl.useProgram(shaderProgram);\r\n\tshaderProgram.vertexPositionAttribute =gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\r\n\tgl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\tshaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\r\n\tgl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\r\n\tshaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\r\n}", "function setupShaders() {\r\n vertexShader = loadShaderFromDOM(\"shader-vs\");\r\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\r\n\r\n shaderProgram = gl.createProgram();\r\n gl.attachShader(shaderProgram, vertexShader);\r\n gl.attachShader(shaderProgram, fragmentShader);\r\n gl.linkProgram(shaderProgram);\r\n\r\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n alert(\"Failed to setup shaders\");\r\n }\r\n\r\n gl.useProgram(shaderProgram);\r\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\r\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\r\n\r\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\r\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\r\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\r\n\r\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\");\r\n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\");\r\n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\r\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\r\n\r\n shaderProgram.uniformAmbientMatColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientMatColor\");\r\n shaderProgram.uniformDiffuseMatColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseMatColor\");\r\n shaderProgram.uniformSpecularMatColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularMatColor\");\r\n}", "function initShader(gl)\n{\n // load and compile the fragment and vertex shader\n let fragmentShader = createShader(gl, fragmentShaderSource, \"fragment\");\n let vertexShader = createShader(gl, vertexShaderSource, \"vertex\");\n\n // link them together into a new program\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // get pointers to the shader params\n shaderVertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"vertexPos\");\n gl.enableVertexAttribArray(shaderVertexPositionAttribute);\n\n shaderVertexColorAttribute = gl.getAttribLocation(shaderProgram, \"vertexColor\");\n gl.enableVertexAttribArray(shaderVertexColorAttribute);\n \n shaderProjectionMatrixUniform = gl.getUniformLocation(shaderProgram, \"projectionMatrix\");\n shaderModelViewMatrixUniform = gl.getUniformLocation(shaderProgram, \"modelViewMatrix\");\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Could not initialise shaders\");\n }\n}", "function setupShaders() {\n vertexShader = loadShaderFromDOM(\"shader-vs\");\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\n \n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n }", "function setupShaders() {\r\n var vertexShader = loadShaderFromDOM(\"shader-vs\");\r\n var fragmentShader = loadShaderFromDOM(\"shader-fs\");\r\n \r\n shaderProgram = gl.createProgram();\r\n gl.attachShader(shaderProgram, vertexShader);\r\n gl.attachShader(shaderProgram, fragmentShader);\r\n gl.linkProgram(shaderProgram);\r\n\r\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n alert(\"Failed to setup shaders\");\r\n }\r\n\r\n gl.useProgram(shaderProgram);\r\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\r\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\r\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\r\n \r\n}", "function setupShaders() {\n vertexShader = loadShaderFromDOM(\"shader-vs\");\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\n\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n}", "function setupShaders() {\r\n vertexShader = loadShaderFromDOM(\"shader-vs\");\r\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\r\n \r\n shaderProgram = gl.createProgram();\r\n gl.attachShader(shaderProgram, vertexShader);\r\n gl.attachShader(shaderProgram, fragmentShader);\r\n gl.linkProgram(shaderProgram);\r\n\r\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n alert(\"Failed to setup shaders\");\r\n }\r\n\r\n gl.useProgram(shaderProgram);\r\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"a_Position\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\r\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\r\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\r\n\r\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"u_MVMatrix\");\r\n\r\n}", "function setupShaders() {\n vertexShader = loadShaderFromDOM(\"shader-vs\");\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\n\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\");\n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\");\n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\n shaderProgram.uniformShininessLoc = gl.getUniformLocation(shaderProgram, \"uShininess\");\n shaderProgram.uniformAmbientMaterialColorLoc = gl.getUniformLocation(shaderProgram, \"uKAmbient\");\n shaderProgram.uniformDiffuseMaterialColorLoc = gl.getUniformLocation(shaderProgram, \"uKDiffuse\");\n shaderProgram.uniformSpecularMaterialColorLoc = gl.getUniformLocation(shaderProgram, \"uKSpecular\");\n\n shaderProgram.uSkyboxSampler = gl.getUniformLocation(shaderProgram, \"uSkyboxSampler\");\n shaderProgram.ucheckSky = gl.getUniformLocation(shaderProgram, \"ucheckSky\");\n\n\n}", "function setupShaders() {\n vertexShader = loadShaderFromDOM(\"shader-vs\");\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\n \n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, \"aVertexColor\");\n gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n}", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpBuffers();\n \n gl.clearColor(0, 0, 0, 1);\n}", "function initShaders()\n{\n var vertexShader=get_shader(shader_vertex_source, gl.VERTEX_SHADER, \"VERTEX\");\n var fragmentShader=get_shader(shader_fragment_source, gl.FRAGMENT_SHADER, \"FRAGMENT\");\n\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))\n {\n alert(\"Could not initialise shaders\");\n }\n\n gl.useProgram(shaderProgram);\n\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.textureCoordAttribute = gl.getAttribLocation(shaderProgram, \"aTextureCoord\");\n gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.samplerUniform = gl.getUniformLocation(shaderProgram, \"uSampler\");\n shaderProgram.sampler2Uniform = gl.getUniformLocation(shaderProgram, \"uSampler2\");\n shaderProgram.dualTex = gl.getUniformLocation(shaderProgram,\"uDualTex\")\n\n //lighting\n shaderProgram.useLightingUniform = gl.getUniformLocation(shaderProgram, \"uUseLighting\");\n shaderProgram.ambientColorUniform = gl.getUniformLocation(shaderProgram, \"uAmbientColor\");\n shaderProgram.pointLightingLocationUniform = gl.getUniformLocation(shaderProgram, \"uPointLightingLocation\");\n shaderProgram.pointLightingColorUniform = gl.getUniformLocation(shaderProgram, \"uPointLightingColor\");\n\n //transparency\n shaderProgram.alphaUniform = gl.getUniformLocation(shaderProgram, \"uAlpha\");\n shaderProgram.useBlending = gl.getUniformLocation(shaderProgram, \"uUseBlending\");\n\n}", "function initGL() {\r\n \"use strict\";\r\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\r\n setUpAttributesAndUniforms();\r\n setUpBuffers();\r\n gl.clearColor(1,0,0,0.5);\r\n}", "function initShaders() { \n \n Shader = (function() {\n \n var UNIFORM_SETTER = {};\n\n // Return the number of elements for GL type\n var getTypeLength = function(type) {\n\n switch(type) {\n case gl.FLOAT_MAT4:\n return 4*4;\n case gl.FLOAT_MAT3:\n return 3*3;\n case gl.FLOAT_MAT2:\n return 2*2;\n case gl.FLOAT_VEC4:\n case gl.INT_VEC4:\n case gl.BOOL_VEC4:\n return 4;\n case gl.FLOAT_VEC3:\n case gl.INT_VEC3:\n case gl.BOOL_VEC3:\n return 3;\n case gl.FLOAT_VEC2:\n case gl.INT_VEC2:\n case gl.BOOL_VEC2:\n return 2;\n default:\n return 1;\n }\n \n }\n\n // Map GL type to a uniform setter method\n UNIFORM_SETTER[gl.FIXED] = gl.uniform1i;\n UNIFORM_SETTER[gl.SHORT] = gl.uniform1i;\n UNIFORM_SETTER[gl.UNSIGNED_BYTE] = gl.uniform1i;\n UNIFORM_SETTER[gl.BYTE] = gl.uniform1i;\n UNIFORM_SETTER[gl.INT] = gl.uniform1i;\n UNIFORM_SETTER[gl.UNSIGNED_INT] = gl.uniform1i;\n UNIFORM_SETTER[gl.FLOAT] = gl.uniform1f;\n UNIFORM_SETTER[gl.SAMPLER_2D] = gl.uniform1i;\n\n UNIFORM_SETTER[gl.FLOAT_MAT4] = gl.uniformMatrix4fv;\n UNIFORM_SETTER[gl.FLOAT_MAT3] = gl.uniformMatrix3fv;\n UNIFORM_SETTER[gl.FLOAT_MAT2] = gl.uniformMatrix2fv;\n\n UNIFORM_SETTER[gl.FLOAT_VEC2] = gl.uniform2fv;\n UNIFORM_SETTER[gl.FLOAT_VEC3] = gl.uniform3fv;\n UNIFORM_SETTER[gl.FLOAT_VEC4] = gl.uniform4fv;\n UNIFORM_SETTER[gl.INT_VEC2] = gl.uniform2iv;\n UNIFORM_SETTER[gl.INT_VEC3] = gl.uniform3iv;\n UNIFORM_SETTER[gl.INT_VEC4] = gl.uniform4iv;\n UNIFORM_SETTER[gl.BOOL] = gl.uniform1i;\n UNIFORM_SETTER[gl.BOOL_VEC2] = gl.uniform2iv;\n UNIFORM_SETTER[gl.BOOL_VEC3] = gl.uniform3iv;\n UNIFORM_SETTER[gl.BOOL_VEC4] = gl.uniform4iv;\n\n var defaultShader = null; // Default shader program\n var programCache = {}; // Store of all loading shader programs\n\n \n // Get and Compile and fragment or vertex shader by ID.\n // (shader source is currently embeded within HTML file)\n function getShader(gl, id) {\n var shaderScript = doc.getElementById(id);\n if (!shaderScript) {\n return null;\n }\n\n var str = \"\";\n var k = shaderScript.firstChild;\n while (k) {\n if (k.nodeType == 3) {\n str += k.textContent;\n }\n k = k.nextSibling;\n }\n\n var shader;\n if (shaderScript.type == \"x-shader/x-fragment\") {\n shader = gl.createShader(gl.FRAGMENT_SHADER);\n } else if (shaderScript.type == \"x-shader/x-vertex\") {\n shader = gl.createShader(gl.VERTEX_SHADER);\n } else {\n return null;\n }\n\n gl.shaderSource(shader, str);\n gl.compileShader(shader);\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(gl.getShaderInfoLog(shader));\n return null;\n }\n return shader;\n }\n \n // Shader data object\n // - program: GL Shader program\n // - meta: list of metadata about GL Shader program (uniform names/types)\n function createShaderObj(shaderProgram) {\n return {\n program: shaderProgram,\n meta: getShaderData(shaderProgram)\n };\n }\n \n\n // Create, load and link a GL shader program \n function loadShaderProgram(v,f) {\n \n v = \"Shaders/vpBasic.cg\" // ab: temp \n //f = \"fpXRAY.cg\";\n \n v = v.split(\".cg\").join(\"\");\n f = f.split(\".cg\").join(\"\");\n \n var name = v+\"+\"+f;\n \n if (programCache[name]) {\n return programCache[name];\n }\n \n var fragmentShader = getShader(gl, f);\n var vertexShader = getShader(gl, v);\n \n if (!fragmentShader || !vertexShader) {\n console.error(\"missing shader \"+ name)\n return null;\n }\n \n var shaderProgram = gl.createProgram();\n \n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n console.error(\"LINK_STATUS error\")\n return null;\n }\n \n var shaderObj = createShaderObj(shaderProgram); \n var attribute = shaderObj.meta.attribute;\n\n gl.useProgram(shaderProgram);\n\n gl.enableVertexAttribArray(attribute.aVertexPosition.location);\n gl.enableVertexAttribArray(attribute.aTextureCoord.location);\n \n gl.bindBuffer(gl.ARRAY_BUFFER, gl.box.vertexObject);\n gl.vertexAttribPointer(attribute.aVertexPosition.location, gl.box.vertexObject.itemSize, gl.FLOAT, false, 0, 0);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, gl.box.texCoordObject);\n gl.vertexAttribPointer(attribute.aTextureCoord.location, gl.box.texCoordObject.itemSize, gl.FLOAT, false, 0, 0);\n\n shaderProgram = createShaderObj(shaderProgram)\n programCache[name] = shaderProgram;\n \n if (!defaultShader) {\n defaultShader = shaderObj;\n }\n \n return shaderObj;\n }\n\n // Create shader program metadata (uniform names/types)\n var getShaderData = function(shader) {\n \n var meta = {uniforms:[], uniform:{}, attribute:{}};\n\n var keys = [],i;\n for (i in gl) {\n keys.push(i);\n }\n keys = keys.sort();\n\n var rgl = {}\n\n keys.forEach(function(key) {\n rgl[gl[key]] = key;\n })\n\n var info;\n var i = 0;\n var len = gl.getProgramParameter(shader, gl.ACTIVE_UNIFORMS)\n \n while (i<len) {\n \n info = gl.getActiveUniform(shader,i);\n meta.uniforms.push(info.name);\n meta.uniform[info.name] = {\n name: info.name,\n glType: info.type,\n type: rgl[info.type],\n length: getTypeLength(info.type),\n idx: i,\n location: gl.getUniformLocation(shader, info.name)\n };\n \n i++;\n }\n\n len = gl.getProgramParameter(shader, gl.ACTIVE_ATTRIBUTES)\n i = 0;\n while (i<len) {\n info = gl.getActiveAttrib(shader,i);\n meta.attribute[info.name] = {\n name: info.name,\n glType: info.type,\n type: rgl[info.type],\n length: getTypeLength(info.type),\n idx: i,\n location: gl.getAttribLocation(shader, info.name)\n };\n i++;\n }\n \n return meta;\n\n }\n\n // (createShader maps to this method)\n return function(v,f) {\n \n var glShader = loadShaderProgram(v,f) || defaultShader;\n \n var shaderValues = {\n alpha: 1\n };\n \n var self = this;\n \n // Create getter/setters for all uniforms and textures on Shader object\n glShader.meta.uniforms.forEach(function(name) {\n var uniform = glShader.meta.uniform[name];\n var len = uniform.length;\n var name = uniform.name;\n var vals = shaderValues;\n (name != \"uMVMatrix\" && name != \"uMVMatrix\")&&Object.defineProperty(self, uniform.name, {\n get: function() {\n return vals[name];\n },\n set: function(v) {\n if (v && v.length !== len) {\n v.length = len;\n }\n vals[name] = v;\n }\n }); \n });\n \n // Draw leaf node\n // (mv matrix, primary texture passed in)\n // [internal method]\n this.__draw = function(gl, mv, imageTexture) {\n \n var usetter = UNIFORM_SETTER;\n var meta = glShader.meta;\n var uniform = meta.uniform;\n var uniforms = meta.uniforms;\n var name, val, u, i = uniforms.length;\n \n // Change shader program if different from last draw\n //if (gl.currentShaderProgram !== glShader) {\n gl.currentShaderProgram = glShader;\n gl.useProgram(glShader.program);\n gl.uniformMatrix4fv(uniform.uPMatrix.location, false, gl.perspectiveMatrixArray);\n //}\n \n // set mv matrix\n gl.uniformMatrix4fv(uniform.uMVMatrix.location, false, mv);\n \n // add primary texture to shader values\n var vals = shaderValues;\n \n if (imageTexture) {\n vals.texture = imageTexture;\n }\n\n var textureSlot = 0;\n \n // Iterate over uniforms and textures setting values from JS to shader program\n while (i--) { \n name = uniforms[i];\n val = vals[name];\n u = uniform[name];\n \n if (val !== undefined && val !== null) {\n if (u.glType === gl.SAMPLER_2D) { // if texture\n gl.activeTexture(gl['TEXTURE'+textureSlot]);\n gl.bindTexture(gl.TEXTURE_2D, val);\n val = textureSlot++;\n }\n usetter[u.glType].apply(gl, [u.location, val]); // uses uniform setter map to set value\n }\n }\n \n // Draw call\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n \n }\n \n this.__getShaderProgram = function() {\n return glShader.program;\n }\n\n }\n\n })(gl);\n \n var defaultShader = new Shader(\"Shaders/vpBasic.cg\", \"Shaders/fpAlphaTexture.cg\");\n\n\n }", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpBuffers();\n \n gl.clearColor(0.1, 0.1, 0.1, 1);\n}", "createShaders() {\n const gl = this.gl\n\n this.vertexShader = this.createShader(gl.VERTEX_SHADER)\n this.fragmentShader = this.createShader(gl.FRAGMENT_SHADER)\n }", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpBuffers();\n setupWorldCoordinates();\n gl.clearColor(0.1, 0.1, 0.1, 1);\n startLoop();\n}", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(\n gl,\n \"VertexShader.glsl\",\n \"FragmentShader.glsl\"\n );\n setUpAttributesAndUniforms();\n setUpBuffers();\n\n gl.clearColor(0.8, 0.8, 0.8, 1);\n}", "function initScene() {\n\n gl.viewport(0, 0, canvas.width, canvas.height);\n gl.clearColor(0.3921, 0.5843, 0.9294, 1.0);\n gl.enable(gl.DEPTH_TEST);\n\n // INIT WEBGL SHADERS AND BUFFERS\n baseProgram = initShaders(gl, \"vertex-shader-base\", \"fragment-shader-base\");\n shadingProgram = initShaders(gl, \"vertex-shader-shading\", \"fragment-shader-shading\");\n\n // Attribute & uniform locations\n baseProgram.vPosition = gl.getAttribLocation(baseProgram, \"vPosition\");\n baseProgram.vColor = gl.getAttribLocation(baseProgram, \"vColor\");\n baseProgram.u_ProjectionMatrix = gl.getUniformLocation(baseProgram, 'u_ProjectionMatrix');\n baseProgram.u_ViewMatrix = gl.getUniformLocation(baseProgram, 'u_ViewMatrix');\n baseProgram.u_ModelMatrix = gl.getUniformLocation(baseProgram, 'u_ModelMatrix');\n\n shadingProgram.vPosition = gl.getAttribLocation(shadingProgram, \"vPosition\");\n shadingProgram.vColor = gl.getAttribLocation(shadingProgram, \"vColor\");\n shadingProgram.vNormal = gl.getAttribLocation(shadingProgram, \"vNormal\");\n shadingProgram.u_ProjectionMatrix = gl.getUniformLocation(shadingProgram, 'u_ProjectionMatrix');\n shadingProgram.u_ViewMatrix = gl.getUniformLocation(shadingProgram, 'u_ViewMatrix');\n shadingProgram.u_ModelMatrix = gl.getUniformLocation(shadingProgram, 'u_ModelMatrix');\n\n shadingProgram.light_position = gl.getUniformLocation(shadingProgram, \"light_position\");\n shadingProgram.u_kaLoc = gl.getUniformLocation(shadingProgram, \"ka\");\n shadingProgram.u_kdLoc = gl.getUniformLocation(shadingProgram, \"kd\");\n shadingProgram.u_ksLoc = gl.getUniformLocation(shadingProgram, \"ks\");\n shadingProgram.u_alphaLoc = gl.getUniformLocation(shadingProgram, \"alpha\");\n shadingProgram.intensity=gl.getUniformLocation(shadingProgram, \"intensity\");\n shadingProgram.u_NormalMatrix = gl.getUniformLocation(shadingProgram, 'u_NormalMatrix');\n\n\n shadingProgram.u_ShadowMap = gl.getUniformLocation(shadingProgram, 'u_ShadowMap');\n shadingProgram.u_MvpMatrixFromLight = gl.getUniformLocation(shadingProgram, 'u_MvpMatrixFromLight');\n\n // Buffers\n var vBuffer = gl.createBuffer();\n vBuffer.type = gl.FLOAT;\n vBuffer.num = 3;\n\n var cBuffer = gl.createBuffer();\n cBuffer.type = gl.FLOAT;\n cBuffer.num = 4;\n\n var nBuffer = gl.createBuffer();\n nBuffer.type = gl.FLOAT;\n nBuffer.num = 3;\n\n\n cubeBuffers.vBuffer = vBuffer;\n cubeBuffers.cBuffer = cBuffer;\n cubeBuffers.nBuffer = nBuffer;\n\n // POSITION CAMERA\n var eye = vec3(\n r * Math.sin(theta) * Math.sin(phi) + x,\n r * Math.cos(theta) + y,\n r * Math.sin(theta) * Math.cos(phi)\n );\n var at = vec3(x, y, 0.0);\n var up = vec3(0, 1, 0);\n viewMatrix = lookAt(eye, at, up);\n\n // CUBE & FACE LOOK UP MAP\n // Initialize a framebuffer object\n lookUpMapFbo = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, lookUpMapFbo);\n var renderbuffer = gl.createRenderbuffer();\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderbuffer);\n gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, canvas.width, canvas.height);\n\n lookUpTexture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, lookUpTexture);\n // gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, lookUpTexture, 0);\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer);\n\n var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);\n if (status !== gl.FRAMEBUFFER_COMPLETE) {\n alert('Framebuffer Not Complete');\n }\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.bindRenderbuffer(gl.RENDERBUFFER, null);\n\n\n // INITIALIZE CUBES LIST AND DRAW SCENE\n allCubes.push(firstCube);\n allCubes = Array.from(chicken);\n\n // Draw current look up map\n drawCubes(allCubes, 1);\n\n // Draw cubes and shadows\n drawScene();\n}", "function initializeShaders(){\n //Load shaders and initialize attribute buffers\n program = initShaders(gl, \"shader-vs\", \"shader-fs\");\n gl.useProgram(program);\n\n //Associate attributes to vertex shader\n _Pmatrix = gl.getUniformLocation(program, \"Pmatrix\");\n _Vmatrix = gl.getUniformLocation(program, \"Vmatrix\");\n _Mmatrix = gl.getUniformLocation(program, \"Mmatrix\");\n _Nmatrix = gl.getUniformLocation(program, \"normalMatrix\");\n\n //Bind vertex buffer with position attribute \n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n var _position = gl.getAttribLocation(program, \"position\");\n gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0);\n gl.enableVertexAttribArray(_position); \n\n //Attributes\n textureCoordAttribute = gl.getAttribLocation(program, \"aTextureCoord\");\n gl.enableVertexAttribArray(textureCoordAttribute);\n\n normalAttribute = gl.getAttribLocation(program, \"normal\");\n gl.enableVertexAttribArray(normalAttribute);\n}", "function initWebGL() {\n /* Add default pointer */\n var pointers = [];\n pointers.push(new Pointer());\n /* Get webGL context */\n\n var webGL = canvas.getContext('webgl2', defualts.DRAWING_PARAMS);\n var isWebGL2 = !!webGL;\n if (!isWebGL2) webGL = canvas.getContext('webgl', defualts.DRAWING_PARAMS) || canvas.getContext('experimental-webgl', defualts.DRAWING_PARAMS);\n /* Get color formats */\n\n var colorFormats = getFormats();\n /* Case support adjustments */\n\n if (isMobile()) defualts.behavior.render_shaders = false;\n\n if (!colorFormats.supportLinearFiltering) {\n defualts.behavior.render_shaders = false;\n defualts.behavior.render_bloom = false;\n }\n /* Make our shaders and shader programs */\n\n\n var SHADER = {\n baseVertex: compileShader(webGL.VERTEX_SHADER, defualts.SHADER_SOURCE.vertex),\n clear: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.clear),\n color: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.color),\n background: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.background),\n display: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.display),\n displayBloom: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.displayBloom),\n displayShading: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.displayShading),\n displayBloomShading: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.displayBloomShading),\n bloomPreFilter: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.bloomPreFilter),\n bloomBlur: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.bloomBlur),\n bloomFinal: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.bloomFinal),\n splat: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.splat),\n advectionManualFiltering: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.advectionManualFiltering),\n advection: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.advection),\n divergence: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.divergence),\n curl: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.curl),\n vorticity: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.vorticity),\n pressure: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.pressure),\n gradientSubtract: compileShader(webGL.FRAGMENT_SHADER, defualts.SHADER_SOURCE.gradientSubtract)\n };\n var programs = formShaderPrograms(colorFormats.supportLinearFiltering);\n /* Worker Classes and Functions */\n\n /**\n * Is It Mobile?:\n * Detects whether or not a device is mobile by checking the user agent string\n *\n * @returns {boolean}\n */\n\n function isMobile() {\n return /Mobi|Android/i.test(navigator.userAgent);\n }\n /**\n * Get Formats:\n * Enable color extensions, linear filtering extensions, and return usable color formats RGBA,\n * RG (Red-Green), and R (Red).\n *\n * @returns {{formatRGBA: {internalFormat, format}, supportLinearFiltering: OES_texture_half_float_linear,\n * formatR: {internalFormat, format}, halfFloatTexType: *, formatRG: {internalFormat, format}}}\n */\n\n\n function getFormats() {\n /* Color Formats */\n var formatRGBA;\n var formatRG;\n var formatR;\n var halfFloat;\n var supportLinearFiltering;\n /* Enables webGL color extensions and get linear filtering extension*/\n\n if (isWebGL2) {\n webGL.getExtension('EXT_color_buffer_float');\n supportLinearFiltering = webGL.getExtension('OES_texture_float_linear');\n } else {\n halfFloat = webGL.getExtension('OES_texture_half_float');\n supportLinearFiltering = webGL.getExtension('OES_texture_half_float_linear');\n }\n\n var HALF_FLOAT_TEXTURE_TYPE = isWebGL2 ? webGL.HALF_FLOAT : halfFloat.HALF_FLOAT_OES;\n /* Set color to black for when color buffers are cleared */\n\n webGL.clearColor(0.0, 0.0, 0.0, 1.0);\n /* Retrieve color formats */\n\n if (isWebGL2) {\n formatRGBA = getSupportedFormat(webGL.RGBA16F, webGL.RGBA, HALF_FLOAT_TEXTURE_TYPE);\n formatRG = getSupportedFormat(webGL.RG16F, webGL.RG, HALF_FLOAT_TEXTURE_TYPE);\n formatR = getSupportedFormat(webGL.R16F, webGL.RED, HALF_FLOAT_TEXTURE_TYPE);\n } else {\n formatRGBA = getSupportedFormat(webGL.RGBA, webGL.RGBA, HALF_FLOAT_TEXTURE_TYPE);\n formatRG = getSupportedFormat(webGL.RGBA, webGL.RGBA, HALF_FLOAT_TEXTURE_TYPE);\n formatR = getSupportedFormat(webGL.RGBA, webGL.RGBA, HALF_FLOAT_TEXTURE_TYPE);\n }\n /** Get Supported Format\n * Using the specified internal format, we retrieve and return the desired color format to be\n * rendered with\n *\n * @param internalFormat: A GLenum that specifies the color components within the texture\n * @param format: Another GLenum that specifies the format of the texel data.\n * @returns {{internalFormat: *, format: *}|null|({internalFormat, format}|null)}\n */\n\n\n function getSupportedFormat(internalFormat, format, type) {\n var isSupportRenderTextureFormat;\n var texture = webGL.createTexture();\n /* Set texture parameters */\n\n webGL.bindTexture(webGL.TEXTURE_2D, texture);\n webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_MIN_FILTER, webGL.NEAREST);\n webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_MAG_FILTER, webGL.NEAREST);\n webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_WRAP_S, webGL.CLAMP_TO_EDGE);\n webGL.texParameteri(webGL.TEXTURE_2D, webGL.TEXTURE_WRAP_T, webGL.CLAMP_TO_EDGE);\n /* Specify a 2D texture image */\n\n webGL.texImage2D(webGL.TEXTURE_2D, 0, internalFormat, 4, 4, 0, format, type, null);\n /* Attach texture to frame buffer */\n\n var fbo = webGL.createFramebuffer();\n webGL.bindFramebuffer(webGL.FRAMEBUFFER, fbo);\n webGL.framebufferTexture2D(webGL.FRAMEBUFFER, webGL.COLOR_ATTACHMENT0, webGL.TEXTURE_2D, texture, 0);\n /* Check if current format is supported */\n\n var status = webGL.checkFramebufferStatus(webGL.FRAMEBUFFER);\n isSupportRenderTextureFormat = status === webGL.FRAMEBUFFER_COMPLETE;\n /* If not supported use fallback format, until we have no fallback */\n\n if (!isSupportRenderTextureFormat) {\n switch (internalFormat) {\n case webGL.R16F:\n return getSupportedFormat(webGL.RG16F, webGL.RG, type);\n\n case webGL.RG16F:\n return getSupportedFormat(webGL.RGBA16F, webGL.RGBA, type);\n\n default:\n return null;\n }\n }\n\n return {\n internalFormat: internalFormat,\n format: format\n };\n }\n\n return {\n formatRGBA: formatRGBA,\n formatRG: formatRG,\n formatR: formatR,\n halfFloatTexType: HALF_FLOAT_TEXTURE_TYPE,\n supportLinearFiltering: supportLinearFiltering\n };\n }\n /**\n * Compile Shader:\n * Makes a new webGL shader of type `type` using the provided GLSL source. The `type` is either of\n * `VERTEX_SHADER` or `FRAGMENT_SHADER`\n *\n * @param type: Passed to `createShader` to define the shader type\n * @param source: A GLSL source script, used to define the shader properties\n * @returns {WebGLShader}: A webGL shader of the parameterized type and source\n */\n\n\n function compileShader(type, source) {\n /* Create shader, link the source, and compile the GLSL*/\n var shader = webGL.createShader(type);\n webGL.shaderSource(shader, source);\n webGL.compileShader(shader);\n /* TODO: Finish error checking */\n\n if (!webGL.getShaderParameter(shader, webGL.COMPILE_STATUS)) throw webGL.getShaderInfoLog(shader);\n return shader;\n }\n /**\n * Form Shader Programs:\n * Assembles shaders into a webGl program we can use to write to our context\n *\n * @param supportLinearFiltering: A bool letting us know if we support linear filtering\n * @returns {{displayBloomProgram: GLProgram, vorticityProgram: GLProgram, displayShadingProgram: GLProgram,\n * displayBloomShadingProgram: GLProgram, gradientSubtractProgram: GLProgram, advectionProgram: GLProgram,\n * bloomBlurProgram: GLProgram, colorProgram: GLProgram, divergenceProgram: GLProgram, clearProgram: GLProgram,\n * splatProgram: GLProgram, displayProgram: GLProgram, bloomPreFilterProgram: GLProgram, curlProgram: GLProgram,\n * bloomFinalProgram: GLProgram, pressureProgram: GLProgram, backgroundProgram: GLProgram}}: Programs used to\n * render shaders\n *\n */\n\n\n function formShaderPrograms(supportLinearFiltering) {\n return {\n clearProgram: new GLProgram(SHADER.baseVertex, SHADER.clear, webGL),\n colorProgram: new GLProgram(SHADER.baseVertex, SHADER.color, webGL),\n backgroundProgram: new GLProgram(SHADER.baseVertex, SHADER.background, webGL),\n displayProgram: new GLProgram(SHADER.baseVertex, SHADER.display, webGL),\n displayBloomProgram: new GLProgram(SHADER.baseVertex, SHADER.displayBloom, webGL),\n displayShadingProgram: new GLProgram(SHADER.baseVertex, SHADER.displayShading, webGL),\n displayBloomShadingProgram: new GLProgram(SHADER.baseVertex, SHADER.displayBloomShading, webGL),\n bloomPreFilterProgram: new GLProgram(SHADER.baseVertex, SHADER.bloomPreFilter, webGL),\n bloomBlurProgram: new GLProgram(SHADER.baseVertex, SHADER.bloomBlur, webGL),\n bloomFinalProgram: new GLProgram(SHADER.baseVertex, SHADER.bloomFinal, webGL),\n splatProgram: new GLProgram(SHADER.baseVertex, SHADER.splat, webGL),\n advectionProgram: new GLProgram(SHADER.baseVertex, supportLinearFiltering ? SHADER.advection : SHADER.advectionManualFiltering, webGL),\n divergenceProgram: new GLProgram(SHADER.baseVertex, SHADER.divergence, webGL),\n curlProgram: new GLProgram(SHADER.baseVertex, SHADER.curl, webGL),\n vorticityProgram: new GLProgram(SHADER.baseVertex, SHADER.vorticity, webGL),\n pressureProgram: new GLProgram(SHADER.baseVertex, SHADER.pressure, webGL),\n gradientSubtractProgram: new GLProgram(SHADER.baseVertex, SHADER.gradientSubtract, webGL)\n };\n }\n\n return {\n programs: programs,\n webGL: webGL,\n colorFormats: colorFormats,\n pointers: pointers\n };\n}", "function setupShaders() {\n //Load the vertex and fragment shaders\n vertexShader =loadShaderFromDOM(\"blinn-phong-vs\");\n fragmentShader =loadShaderFromDOM(\"blinn-phong-fs\");\n\n //Create the shader program and attach the vertex/fragment shaders\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n //Alert if shaders not set up properly\n alert(\"Failed to setup shaders\");\n console.log(gl.getProgramInfoLog(shaderProgram));\n }\n\n // Use the shaderProgram just created\n gl.useProgram(shaderProgram);\n\n // Get attributes from shaders and enable arrays that will be needed later\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n // Get the uniforms\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\");\n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\");\n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\n shaderProgram.uniformShininessLoc = gl.getUniformLocation(shaderProgram, \"uShininess\");\n shaderProgram.uniformAmbientMaterialColorLoc = gl.getUniformLocation(shaderProgram, \"uKAmbient\");\n shaderProgram.uniformDiffuseColorLoc1 = gl.getUniformLocation(shaderProgram, \"kDiffuse1\");\n shaderProgram.uniformDiffuseColorLoc2 = gl.getUniformLocation(shaderProgram, \"kDiffuse2\");\n shaderProgram.uniformDiffuseColorLoc3 = gl.getUniformLocation(shaderProgram, \"kDiffuse3\");\n shaderProgram.uniformDiffuseColorLoc4 = gl.getUniformLocation(shaderProgram, \"kDiffuse4\");\n shaderProgram.uniformSpecularMaterialColorLoc = gl.getUniformLocation(shaderProgram, \"uKSpecular\");\n\n}", "function setupShaders(vshader,fshader) {\n vertexShader = loadShaderFromDOM(vshader);\n fragmentShader = loadShaderFromDOM(fshader);\n \n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\"); \n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\"); \n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\n shaderProgram.uniformDiffuseMaterialColor = gl.getUniformLocation(shaderProgram, \"uDiffuseMaterialColor\");\n shaderProgram.uniformAmbientMaterialColor = gl.getUniformLocation(shaderProgram, \"uAmbientMaterialColor\");\n shaderProgram.uniformSpecularMaterialColor = gl.getUniformLocation(shaderProgram, \"uSpecularMaterialColor\");\n\n shaderProgram.uniformShininess = gl.getUniformLocation(shaderProgram, \"uShininess\"); \n}", "function setupShaders(vshader,fshader) {\n vertexShader = loadShaderFromDOM(vshader);\n fragmentShader = loadShaderFromDOM(fshader);\n \n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Failed to setup shaders\");\n }\n\n gl.useProgram(shaderProgram);\n\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\n\n shaderProgram.vertexNormalAttribute = gl.getAttribLocation(shaderProgram, \"aVertexNormal\");\n gl.enableVertexAttribArray(shaderProgram.vertexNormalAttribute);\n\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\n shaderProgram.nMatrixUniform = gl.getUniformLocation(shaderProgram, \"uNMatrix\");\n shaderProgram.uniformLightPositionLoc = gl.getUniformLocation(shaderProgram, \"uLightPosition\"); \n shaderProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgram, \"uAmbientLightColor\"); \n shaderProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgram, \"uDiffuseLightColor\");\n shaderProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgram, \"uSpecularLightColor\");\n shaderProgram.uniformDiffuseMaterialColor = gl.getUniformLocation(shaderProgram, \"uDiffuseMaterialColor\");\n shaderProgram.uniformAmbientMaterialColor = gl.getUniformLocation(shaderProgram, \"uAmbientMaterialColor\");\n shaderProgram.uniformSpecularMaterialColor = gl.getUniformLocation(shaderProgram, \"uSpecularMaterialColor\");\n\n shaderProgram.uniformShininess = gl.getUniformLocation(shaderProgram, \"uShininess\"); \n}", "function initShaders() {\n //get shader source\n \n var fs_source = fragmentShaderSource;\n var vs_source = vertexShaderSource;\n\n //compile shaders \n vertexShader = makeShader(vs_source, gl.VERTEX_SHADER);\n fragmentShader = makeShader(fs_source, gl.FRAGMENT_SHADER);\n \n //create program\n glProgram_terreno = gl.createProgram();\n \n //attach and link shaders to the program\n gl.attachShader(glProgram_terreno, vertexShader);\n gl.attachShader(glProgram_terreno, fragmentShader);\n gl.linkProgram(glProgram_terreno);\n\n if (!gl.getProgramParameter(glProgram_terreno, gl.LINK_STATUS)) {\n alert(\"Unable to initialize the shader program.\");\n }\n\n //use program\n gl.useProgram(glProgram_terreno);\n \n\n glProgram_terreno.vertexPositionAttribute = gl.getAttribLocation(glProgram_terreno, \"aPosition\");\n gl.enableVertexAttribArray(glProgram_terreno.vertexPositionAttribute);\n\n glProgram_terreno.textureCoordAttribute = gl.getAttribLocation(glProgram_terreno, \"aUv\");\n gl.enableVertexAttribArray(glProgram_terreno.textureCoordAttribute);\n\n glProgram_terreno.vertexNormalAttribute = gl.getAttribLocation(glProgram_terreno, \"aNormal\");\n if (glProgram_terreno.vertexNormalAttribute != -1){ //Por optimizaciones del compilador que elimina variables no utilizadas\n gl.enableVertexAttribArray(glProgram_terreno.vertexNormalAttribute);\n }\n\n glProgram_terreno.pMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uPMatrix\");\n glProgram_terreno.mMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uMMatrix\");\n glProgram_terreno.vMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uVMatrix\");\n glProgram_terreno.nMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uNMatrix\");\n glProgram_terreno.traslacionTextura = gl.getUniformLocation(glProgram_terreno, \"traslacionTextura\");\n glProgram_terreno.samplerUniform = gl.getUniformLocation(glProgram_terreno, \"uSampler\");\n glProgram_terreno.useLightingUniform = gl.getUniformLocation(glProgram_terreno, \"uUseLighting\");\n glProgram_terreno.uColor = gl.getUniformLocation(glProgram_terreno, \"uAmbientColor\");\n glProgram_terreno.frameUniform = gl.getUniformLocation(glProgram_terreno, \"time\");\n glProgram_terreno.lightingDirectionUniform = gl.getUniformLocation(glProgram_terreno, \"uLightPosition\");\n glProgram_terreno.directionalColorUniform = gl.getUniformLocation(glProgram_terreno, \"uDirectionalColor\");\n\n glProgram_terreno.lightingDirectionUniform2 = gl.getUniformLocation(glProgram_terreno, \"uLightPosition2\");\n glProgram_terreno.directionalColorUniform2 = gl.getUniformLocation(glProgram_terreno, \"uDirectionalColor2\");\n //glProgram_terreno.uColor = gl.getUniformLocation(glProgram_terreno, \"uColor\");\n\n var fs_source2 = fragmentShaderSource2;\n var vs_source2 = vertexShaderSource2;\n\n //compile shaders \n vertexShader = makeShader(vs_source2, gl.VERTEX_SHADER);\n fragmentShader = makeShader(fs_source2, gl.FRAGMENT_SHADER);\n \n //create program\n glProgram_helicoptero = gl.createProgram();\n \n //attach and link shaders to the program\n gl.attachShader(glProgram_helicoptero, vertexShader);\n gl.attachShader(glProgram_helicoptero, fragmentShader);\n gl.linkProgram(glProgram_helicoptero);\n\n if (!gl.getProgramParameter(glProgram_helicoptero, gl.LINK_STATUS)) {\n alert(\"Unable to initialize the shader program.\");\n }\n\n //use program\n gl.useProgram(glProgram_helicoptero);\n \n glProgram_helicoptero.textureCoordAttribute = gl.getAttribLocation(glProgram_helicoptero, \"aUv\");\n gl.enableVertexAttribArray(glProgram_helicoptero.textureCoordAttribute);\n\n glProgram_helicoptero.vertexPositionAttribute = gl.getAttribLocation(glProgram_helicoptero, \"aPosition\");\n gl.enableVertexAttribArray(glProgram_helicoptero.vertexPositionAttribute);\n\n glProgram_helicoptero.vertexNormalAttribute = gl.getAttribLocation(glProgram_helicoptero, \"aNormal\");\n gl.enableVertexAttribArray(glProgram_helicoptero.vertexNormalAttribute); \n \n glProgram_helicoptero.uColor = gl.getUniformLocation(glProgram_helicoptero, \"uColor\");\n\n glProgram_helicoptero.lightingDirectionUniform = gl.getUniformLocation(glProgram_helicoptero, \"uLightPosition\");\n glProgram_helicoptero.directionalColorUniform = gl.getUniformLocation(glProgram_helicoptero, \"uDirectionalColor\");\n}", "function initWebGl()\n {\n canvas = document.getElementById(\"gl-canvas\");\n gl = WebGLUtils.setupWebGL(canvas);\n if (!gl)\n {\n alert(\"Unable to setup WebGL!\");\n return;\n }\n gl.viewport(0, 0, canvas.clientWidth, canvas.clientHeight);\n gl.clearColor(1.0, 1.0, 1.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n\n var vertexShader = initShader(gl, 'vertex-shader', gl.VERTEX_SHADER);\n var fragmentShader = initShader(gl, 'fragment-shader', gl.FRAGMENT_SHADER);\n var boxShader = initShader(gl, 'block-fragment-shader', gl.FRAGMENT_SHADER);\n var boxVShader = initShader(gl, 'block-vertex-shader', gl.VERTEX_SHADER);\n\n program = gl.createProgram();\n gl.attachShader(program, fragmentShader);\n gl.attachShader(program, vertexShader);\n gl.linkProgram(program);\n\n boxShaderProgram = gl.createProgram();\n gl.attachShader(boxShaderProgram, boxVShader);\n gl.attachShader(boxShaderProgram, boxShader);\n gl.linkProgram(boxShaderProgram);\n }", "function linkShaders() {\n console.log(`*** INFO: Linking shaders... ***`);\n let program = gl.createProgram();\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n gl.linkProgram(program);\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n console.error(`*** ERROR linking program ***`, gl.getProgramInfoLog(program));\n return;\n }\n console.log(`*** INFO: Validating program... ***`);\n gl.validateProgram(program);\n if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {\n console.error(`*** ERROR validating program ***`, gl.getProgramInfoLog(program));\n return;\n }\n setupBuffers();\n linkAttributes(program);\n gl.useProgram(program);\n\n time_location = gl.getUniformLocation(program, `u_time`);\n resolution_location = gl.getUniformLocation(program, `u_resolution`);\n mouse_location = gl.getUniformLocation(program, `u_mouse`);\n colshift_location = gl.getUniformLocation(program, `u_colshift`);\n if (!started) {\n t0 = Date.now();\n }\n started = true;\n render(program); \n }", "function initGL() {\n var prog = createProgram(gl,\"vshader-source\",\"fshader-source\");\n gl.useProgram(prog);\n gl.enable(gl.DEPTH_TEST);\n \n a_coords_loc = gl.getAttribLocation(prog, \"a_coords\");\n a_normal_loc = gl.getAttribLocation(prog, \"a_normal\");\n gl.enableVertexAttribArray(a_coords_loc);\n gl.enableVertexAttribArray(a_normal_loc);\n \n u_modelview = gl.getUniformLocation(prog, \"modelview\");\n u_projection = gl.getUniformLocation(prog, \"projection\");\n u_normalMatrix = gl.getUniformLocation(prog, \"normalMatrix\");\n u_material = {\n diffuseColor: gl.getUniformLocation(prog, \"material.diffuseColor\"),\n specularColor: gl.getUniformLocation(prog, \"material.specularColor\"),\n emissiveColor: gl.getUniformLocation(prog, \"material.emissiveColor\"),\n specularExponent: gl.getUniformLocation(prog, \"material.specularExponent\")\n };\n u_lights = new Array(10);\n for (var i = 0; i < 10; i++) {\n u_lights[i] = {\n enabled: gl.getUniformLocation(prog, \"lights[\" + i + \"].enabled\"),\n position: gl.getUniformLocation(prog, \"lights[\" + i + \"].position\"),\n color: gl.getUniformLocation(prog, \"lights[\" + i + \"].color\"),\n spotDirection: gl.getUniformLocation(prog, \"lights[\" + i + \"].spotDirection\"),\n spotCosineCutoff: gl.getUniformLocation(prog, \"lights[\" + i + \"].spotCosineCutoff\"),\n spotExponent: gl.getUniformLocation(prog, \"lights[\" + i + \"].spotExponent\"),\n attenuation: gl.getUniformLocation(prog, \"lights[\" + i + \"].attenuation\")\n };\n }\n for (var i = 1; i < 10; i++) { // set defaults for lights\n gl.uniform1i( u_lights[i].enabled, 1 ); \n\n }\n\n //ambient light - off by default\n gl.uniform4f( u_lights[0].position, 0,0,0,1 ); \n gl.uniform3f( u_lights[0].color, 0.2,0.2,0.2 );\n \n}", "function SetUpShaders(gl) {\r\n DefaultShader=LoadShaderFromFiles(gl, \"shaders/default_vs.glsl\", \"shaders/default_fs.glsl\");\r\n IndexShader=LoadShaderFromFiles(gl, \"shaders/default_vs.glsl\", \"shaders/selection_fs.glsl\");\r\n DepthShader=LoadShaderFromFiles(gl, \"shaders/default_vs.glsl\", \"shaders/depth_fs.glsl\");\r\n\r\n //iconTextures[\"simple\"]=new CTexture(gl, \"images/iphonecopy.png\");\r\n iconTextures[\"Object\"]=new CTexture(gl, \"images/Object1.png\");\r\n iconTextures[\"PartWhole\"]=new CTexture(gl, \"images/PartWhole1.png\");\r\n iconTextures[\"Reference\"]=new CTexture(gl, \"images/Reference1.png\");\r\n iconTextures[\"Creative\"]=new CTexture(gl, \"images/Creative1.png\");\r\n}", "function initProgram(id) {\n var programShader = gl.createProgram();\n var vert = compileShader(id + \"-vs\");\n var frag = compileShader(id + \"-fs\");\n gl.attachShader(programShader, vert);\n gl.attachShader(programShader, frag);\n gl.linkProgram(programShader);\n if (!gl.getProgramParameter(programShader, gl.LINK_STATUS)) {\n alert(gl.getProgramInfoLog(programShader));\n return null;\n }\n return programShader;\n}", "function setUpShaders() {\n //\n var vertexShader = scene.assetManager.loadShader (\n ShaderType.VERTEX_SHADER,\n PositionColor.VERTEX_SHADER_SOURCE\n );\n\n var fragmentShader = scene.assetManager.loadShader (\n ShaderType.FRAGMENT_SHADER,\n PositionColor.FRAGMENT_SHADER_SOURCE\n );\n\n shaderProgram =\n shaderHelper.setUpShaderProgram(vertexShader, fragmentShader);\n\n vertexPositionAttributeLocation =\n scene.graphicsManager.getAttributeLocation(shaderProgram, 'vertexPosition');\n\n transformUniformLocation =\n scene.graphicsManager.getUniformLocation(shaderProgram, 'transform');\n }", "function initTestShaders( vertexShaderName, fragmentShaderName, context )\n{\n var vertexShader = getShader( gl, vertexShaderName );\n var fragmentShader = getShader( gl, fragmentShaderName );\n var vPos;\n var mvMatrix;\n var pMatrix;\n\n shaderProgram = gl.createProgram();\n gl.attachShader( shaderProgram, vertexShader );\n gl.attachShader( shaderProgram, fragmenstShader );\n gl.linkProgram( shaderProgram );\n\n // Check if linking succeeded\n if (!gl.getProgramParameter( shaderProgram, gl.LINK_STATUS )) {\n alert( gl.getProgramInfoLog( shaderProgram ) );\n return 0;\n }\n \n gl.useProgram( shaderProgram );\n vPos = gl.getAttributeLocation( shaderProgram, 'a_vPos' );\n gl.enableVertexAttribArray( vPos );\n\n mvMatrix = gl.getAttributeLocation( shaderProgram, 'u_mvMatrix' );\n pMatrix = gl.getAttributeLocation( shaderProgram, 'u_pMatrix' );\n\n // Update shader data in the context\n context.shaderData.shaderProgram = shaderProgram;\n context.shaderData.vertexPositionAttribute = vPos;\n context.shaderData.modelViewMatrixUniform = mvMatrix;\n context.shaderData.projectionMatrixUniform = pMatrix;\n}", "function initGL() {\r\n var canvas = document.getElementById(\"webGLcanvas\");\r\n canvas.width = window.innerWidth - 30;\r\n canvas.height = Math.floor(window.innerHeight - 0.25 * window.innerHeight);\r\n try {\r\n gl = canvas.getContext(\"experimental-webgl\");\r\n gl.viewportWidth = canvas.width;\r\n gl.viewportHeight = canvas.height;\r\n } catch (e) {\r\n }\r\n if (!gl) {\r\n alert(\"cannot initialize webGL\");\r\n }\r\n\r\n document.onkeydown = handleKeyDown;\r\n document.onkeyup = handleKeyUp;\r\n canvas.onmousedown = handleMouseDown;\r\n document.onmouseup = handleMouseUp;\r\n document.onmousemove = handleMouseMove;\r\n\r\n // fragprogram = initShaders(\"perfrag-shader-fs\", \"perfrag-shader-vs\");\r\n vertprogram = initShaders(\"shader-fs\", \"shader-vs\");\r\n currentProgram = vertprogram;\r\n gl.clearColor(0.13, 0.13, 0.13, 1);\r\n gl.enable(gl.DEPTH_TEST);\r\n\r\n fpsInterval = 1000 / 15;\r\n then = Date.now();\r\n startTime = then;\r\n // initBuffer();\r\n cornerVertexPosBuffer = gl.createBuffer();\r\n pointLightPos = [\r\n rand(-3, 7),rand(-3, 7),rand(-3, 7),\r\n rand(-3, 7),rand(-3, 7),rand(-3, 7),\r\n rand(-3, 7),rand(-3, 7),rand(-3, 7),\r\n rand(-3, 7),rand(-3, 7),rand(-3, 7),\r\n rand(-3, 7),rand(-3, 7),rand(-3, 7),\r\n ];\r\n pointLightColor = [\r\n rand(0, 0.5),rand(0.4, 1),rand(0.4, 1),\r\n rand(0.4, 1),rand(0.4, 1),rand(0, 0.5),\r\n rand(0.4, 1),rand(0.4, 1),rand(0.4, 1),\r\n rand(0, 0.5),rand(0, 0.5),rand(0, 0.5),\r\n rand(0.4, 1),rand(0, 0.5),rand(0.4, 1),\r\n ];\r\n \r\n numPtLights = 5;\r\n\r\n animate();\r\n}", "function initShaderProgram(gl) {\n const vsh = loadShader(gl, gl.VERTEX_SHADER, vsh_src);\n const fsh = loadShader(gl, gl.FRAGMENT_SHADER, fsh_src);\n\n // Create the shader program\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vsh);\n gl.attachShader(shaderProgram, fsh);\n gl.linkProgram(shaderProgram);\n\n // Check for errors in setup\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert('Shader program initialization failed: ' + gl.getProgramInfoLog(shaderProgram));\n return;\n }\n \n return shaderProgram;\n}", "function initShaders(gl) {\n\n var vertexShaderSource = \"\\\n\tattribute vec3 a_position; \\n\\\n\tattribute vec3 a_color; \\n\\\n\tvarying vec3 vertexcolor; \\n\\\n\tvoid main(void) \\n\\\n\t{ \\n\\\n\t vertexcolor = a_color; \\n\\\n\t\tgl_Position = vec4(a_position, 1.0); \\n\\\n\t} \\n\\\n\t\";\n\n var fragmentShaderSource = \"\\\n\tprecision highp float; \\n\\\n\tvarying vec3 vertexcolor; \\n\\\n\tvoid main(void) \\n\\\n\t{ \\n\\\n\t\tgl_FragColor = vec4(vertexcolor, 1.0); \\n\\\n\t} \\n\\\n\t\";\n\n // create the vertex shader\n var vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader, vertexShaderSource);\n gl.compileShader(vertexShader);\n\n // create the fragment shader\n var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader, fragmentShaderSource);\n gl.compileShader(fragmentShader);\n\n // Create the shader program\n shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, we show compilation and linking errors.\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Unable to initialize the shader program.\");\n var str = \"\";\n str += \"VS:\\n\" + gl.getShaderInfoLog(vertexShader) + \"\\n\\n\";\n str += \"FS:\\n\" + gl.getShaderInfoLog(fragmentShader) + \"\\n\\n\";\n str += \"PROG:\\n\" + gl.getProgramInfoLog(shaderProgram);\n alert(str);\n }\n}", "function initShader(gl, vsSource, fsSource) {\n \n const vertexShader = compileShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = compileShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n return null;\n }\n\n return shaderProgram;\n}", "function startup() {\n canvas = document.getElementById(\"myGLCanvas\");\n gl = createGLContext(canvas);\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n document.onkeydown = handleKeyDown;\n document.onkeyup = handleKeyUp;\n light = vec4.fromValues(0.,0,10.,1.);\n setupShadersPot();\n setupShaders();\n setupReflectiveShader();\n setupBuffers();\n setupTextures();\n tick();\n}", "function init() {\n // Set the clear color to fully transparent black\n gl.clearColor(0.0, 0.0, 0.0, 0.0);\n \n gl.enable(gl.DEPTH_TEST);\n gl.depthMask(true);\n gl.disable(gl.BLEND);\n \n // Create the model-view matrix and projection matrix\n mvmat = mat4.create();\n projmat = mat4.create();\n nmat = mat3.create();\n \n // Create all buffer objects and reset their lengths\n vbo = gl.createBuffer();\n lineIndices = gl.createBuffer();\n triIndices = gl.createBuffer();\n vbo.length = 0;\n lineIndices.length = 0;\n \n // Initialize the shaders\n initShaders();\n \n // Reshape the canvas, and setup the viewport and projection\n reshape();\n}", "function setupShadersMesh() {\r\n vertexShader = loadShaderFromDOM(\"shader-vs-mesh\");\r\n fragmentShader = loadShaderFromDOM(\"shader-fs-mesh\");\r\n\r\n shaderProgramMesh = gl.createProgram();\r\n gl.attachShader(shaderProgramMesh, vertexShader);\r\n gl.attachShader(shaderProgramMesh, fragmentShader);\r\n gl.linkProgram(shaderProgramMesh);\r\n\r\n if (!gl.getProgramParameter(shaderProgramMesh, gl.LINK_STATUS)) {\r\n alert(\"Failed to setup mesh shaders\");\r\n }\r\n\r\n gl.useProgram(shaderProgramMesh);\r\n\r\n shaderProgramMesh.vertexPositionAttribute = gl.getAttribLocation(shaderProgramMesh, \"aVertexPosition\");\r\n gl.enableVertexAttribArray(shaderProgramMesh.vertexPositionAttribute);\r\n\r\n shaderProgramMesh.vertexNormalAttribute = gl.getAttribLocation(shaderProgramMesh, \"aVertexNormal\");\r\n gl.enableVertexAttribArray(shaderProgramMesh.vertexNormalAttribute);\r\n\r\n shaderProgramMesh.mvMatrixUniform = gl.getUniformLocation(shaderProgramMesh, \"uMVMatrix\");\r\n shaderProgramMesh.pMatrixUniform = gl.getUniformLocation(shaderProgramMesh, \"uPMatrix\");\r\n shaderProgramMesh.nMatrixUniform = gl.getUniformLocation(shaderProgramMesh, \"uNMatrix\");\r\n shaderProgramMesh.uniformLightPositionLoc = gl.getUniformLocation(shaderProgramMesh, \"uLightPosition\");\r\n shaderProgramMesh.uniformAmbientLightColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uAmbientLightColor\");\r\n shaderProgramMesh.uniformDiffuseLightColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uDiffuseLightColor\");\r\n shaderProgramMesh.uniformSpecularLightColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uSpecularLightColor\");\r\n shaderProgramMesh.uniformShininessLoc = gl.getUniformLocation(shaderProgramMesh, \"uShininess\");\r\n shaderProgramMesh.uniformAmbientMaterialColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uKAmbient\");\r\n shaderProgramMesh.uniformDiffuseMaterialColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uKDiffuse\");\r\n shaderProgramMesh.uniformSpecularMaterialColorLoc = gl.getUniformLocation(shaderProgramMesh, \"uKSpecular\");\r\n\r\n console.log(\"Mesh shaders succesfully set up.\");\r\n}", "function initShaders() {\n\tvar promises = [];\n\tfor (i = 0; i < vertShaderNames.length; i++) {\n\t\t// vertex shader promise\n\t\tpromises[i*2] = new Promise(function(resolve, reject) {\n\t\t\tvar req = new XMLHttpRequest();\n\t\t\tvar filename = \"./shaders/\" + vertShaderNames[i] + \".vert\";\n\t\t\treq.open(\"GET\", filename, true);\n\t\t\treq.responseType = \"text\";\n\t\t\treq.onreadystatechange = function () {\n\t\t\t\tif(req.readyState === 4) {\n\t\t\t\t\tif (req.status === 200 || req.status == 0) {\n\t\t\t\t\t\tresolve(req.responseText);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(Error(\"Failed to load \" + filename));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treq.send(null);\t\t\t\n\t\t});\n\t\t// fragment shader promise\n\t\tpromises[i*2 + 1] = new Promise(function(resolve, reject) {\n\t\t\tvar req = new XMLHttpRequest();\n\t\t\tvar filename = \"./shaders/\" + fragShaderNames[i] + \".frag\";\n\t\t\treq.open(\"GET\", filename, true);\n\t\t\treq.responseType = \"text\";\n\t\t\treq.onreadystatechange = function () {\n\t\t\t\tif(req.readyState === 4) {\n\t\t\t\t\tif (req.status === 200 || req.status == 0) {\n\t\t\t\t\t\tresolve(req.responseText);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treject(Error(\"Failed to load \" + filename));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treq.send(null);\n\t\t});\n\t}\n\tPromise.all(promises).then(function(values) {\n\t\tpostInitShaders(values);\n\t}, function() {\n\t\tconsole.err(\"A promise has has rejected, so an XMLHttpRequest failed.\");\n\t});\n}", "function initDemo() {\n const canvas = document.getElementById('c');\n\n // Resize canvas HTML element to window size\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight-100;\n \n gl = canvas.getContext('webgl2');\n\n if (!gl) {\n // Some browsers have only experimental support.\n console.log('WebGL not supported. Using Experimental WebGL.');\n gl = canvas.getContext('experimental-webgl');\n }\n\n if (!gl) {\n alert('Your browser does not support WebGL!');\n return;\n }\n\n // Adjust viewport to window size\n gl.viewport(0, 0, canvas.width, canvas.heigh5);\n\n // Clear window in purple\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create shaders\n // Prior to drawing, we need to compile the shaders.\n // This is due to OpenGL ES being a programmable shading interface\n\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n gl.shaderSource(vertexShader, vertexShaderCode);\n gl.shaderSource(fragmentShader, fragmentShaderCode);\n\n gl.compileShader(vertexShader);\n if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n console.log(\n 'Error compiling vertexShader',\n gl.getShaderInfoLog(vertexShader),\n );\n return;\n }\n\n gl.compileShader(fragmentShader);\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n console.log(\n 'Error compiling fragmentShader',\n gl.getShaderInfoLog(fragmentShader),\n );\n return;\n }\n\n // Attach shaders to a GL program\n const program = gl.createProgram();\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n gl.linkProgram(program);\n gl.useProgram(program);\n // Additional checking if everything went fine\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n console.error(\n 'Error linking program',\n gl.getProgramInfoLog(program),\n );\n return;\n }\n\n gl.validateProgram(program);\n if (!gl.getProgramParameter(program, gl.VALIDATE_STATUS)) {\n console.error(\n 'Error validating program',\n gl.getProgramInfoLog(program),\n );\n return;\n }\n\n\n // Create screen corners in a buffer\n // As this application relies on the fragment fragment buffer,\n // we only need to tell OpenGL to draw the whole area and the\n // pixels are processed individually (and in parallel) in the\n // fragment shader\n const screenCorners = [\n // X, Y,\n /* */1.0, /* */1.0,\n /**/-1.0, /* */1.0,\n /**/-1.0, /**/-1.0,\n /* */1.0, /**/-1.0,\n ];\n\n const screenCornersVertexBufferObject = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, screenCornersVertexBufferObject);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(screenCorners), gl.STATIC_DRAW);\n\n // Vertices\n const vertexPositionAttribLocation =\n gl.getAttribLocation(program, 'vertexPosition');\n\n gl.vertexAttribPointer(\n vertexPositionAttribLocation, // index\n 2, // size\n gl.FLOAT, // type\n gl.FALSE, // normalized\n 0, // stride\n 0, // offset\n );\n\n gl.enableVertexAttribArray(vertexPositionAttribLocation);\n\n const nearVertexBufferObject = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, nearVertexBufferObject);\n\n // Near vertices on attribute\n const nearPositionAttribLocation = gl.getAttribLocation(program, 'plotPosition');\n gl.vertexAttribPointer(\n nearPositionAttribLocation, // index\n 3, // size\n gl.FLOAT, // type\n gl.FALSE, // normalized\n 0, // stride\n 0, // offset\n );\n\n gl.enableVertexAttribArray(nearPositionAttribLocation);\n\n // Bind program to WebGL\n gl.useProgram(program);\n\n // Set properties\n const cameraPositionLocation = gl.getUniformLocation(program, 'cameraPosition');\n const sphereCenterLocation1 = gl.getUniformLocation(program, 'sphere1');\n const sphereCenterLocation2 = gl.getUniformLocation(program, 'sphere2');\n\n const cubeCenterLocation1 = gl.getUniformLocation(program, 'cube1');\n const cubeCenterLocation2 = gl.getUniformLocation(program, 'cube2');\n\n const floorRadiusLocation = gl.getUniformLocation(program, 'floorRadius');\n const floorLocationLocation = gl.getUniformLocation(program, 'floorLocation');\n const planeDirectionLocation = gl.getUniformLocation(program, 'norPlane');\n\n const lighPosLocation = gl.getUniformLocation(program, 'lightPos');\n\n //Set Perlin parameters\n scalePerlinFactor = gl.getUniformLocation(program, 'scalePerlin');\n transPerlinFactor = gl.getUniformLocation(program, 'transPerlin');\n anglePerlinFactor = gl.getUniformLocation(program, 'anglePerlin');\n scalePerlinFactor1 = gl.getUniformLocation(program, 'scalePerlin1');\n transPerlinFactor1 = gl.getUniformLocation(program, 'transPerlin1');\n anglePerlinFactor1 = gl.getUniformLocation(program, 'anglePerlin1');\n scalePerlinFactor2 = gl.getUniformLocation(program, 'scalePerlin2');\n transPerlinFactor2 = gl.getUniformLocation(program, 'transPerlin2');\n anglePerlinFactor2 = gl.getUniformLocation(program, 'anglePerlin2');\n\n brightPerlin1 = gl.getUniformLocation(program, 'brightPerlin1');\n brightPerlin2 = gl.getUniformLocation(program, 'brightPerlin2');\n brightPerlin3 = gl.getUniformLocation(program, 'brightPerlin3');\n\n weightPerlin1 = gl.getUniformLocation(program, 'weightPerlin1');\n weightPerlin2 = gl.getUniformLocation(program, 'weightPerlin2');\n weightPerlin3 = gl.getUniformLocation(program, 'weightPerlin3');\n\n //Set other input fields\n modeSh = gl.getUniformLocation(program, 'mode');\n reflectionOn = gl.getUniformLocation(program, 'reflectingOn');\n gridOn = gl.getUniformLocation(program, 'gridOn');\n\n //Set geometry locations\n var sphere1 = [5.0, 2, 0.0]\n var cube1 = [-5.0, 2, 0.0]\n\n gl.uniform3f(sphereCenterLocation1, sphere1[0], sphere1[1], sphere1[2]);\n //gl.uniform3f(sphereCenterLocation2, sphere2[0], sphere2[1], sphere2[2]);\n\n gl.uniform3f(cubeCenterLocation1, cube1[0], cube1[1], cube1[2]);\n //gl.uniform3f(cubeCenterLocation2, cube2[0], cube2[1], cube2[2]);\n \n gl.uniform1f(floorRadiusLocation, 30.0);\n gl.uniform3f(floorLocationLocation, 0.0, -1.0, 0.0);\n\n var lightPos =[0, 9, 10]\n gl.uniform3f(lighPosLocation, lightPos[0], lightPos[1], lightPos[2]);\n\n gl.uniform3f(scalePerlinFactor, 1.0,1.0,1.0);\n gl.uniform3f(transPerlinFactor, 1.0,1.0,1.0);\n gl.uniform3f(anglePerlinFactor, 0.0,0.0,0.0);\n\n //Set variables for modes\n var prevMod = 0;\n gl.uniform1i(modeSh, 0);\n var prevReflection = true;\n gl.uniform1i(reflectionOn, true);\n var prevGrid = true;\n gl.uniform1i(gridOn, true);\n\n let ratio = canvas.width / canvas.height;\n var prevrealImageOn = false\n\n //Camera parameters\n const up = vec3.fromValues(0.0, 1.0, 0.0);\n const cameraTo = vec3.fromValues(0.0, 0.0, 0.0);\n const cameraInitialPosition = vec3.fromValues(0.0, 0.0, 10.0);\n const cameraPosition = new Float32Array(3);\n\n const cameraDirection = new Float32Array(3);\n const cameraUp = new Float32Array(3);\n const cameraLeft = new Float32Array(3);\n\n const nearCenter = new Float32Array(3);\n const nearTopLeft = new Float32Array(3);\n const nearBottomLeft = new Float32Array(3);\n const nearTopRight = new Float32Array(3);\n const nearBottomRight = new Float32Array(3);\n\n function renderLoop() {\n prevrealImageOn = realImageOn\n\n //Change modes\n var modecur = parseFloat(document.getElementById(\"mode\").value);\n if(modecur != prevMod || prevrealImageOn == true){\n //Perlin grid and interpolation\n if(modecur == 0 || modecur == 1 ){\n document.getElementById(\"perx\").value = 1.0\n document.getElementById(\"pery\").value = 1.0\n document.getElementById(\"perz\").value = 1.0\n document.getElementById(\"brR\").disabled = true\n document.getElementById(\"brG\").disabled = true\n document.getElementById(\"brB\").disabled = true\n document.getElementById(\"wR\").disabled = true\n document.getElementById(\"wG\").disabled = true\n document.getElementById(\"wB\").disabled = true\n document.getElementById(\"perx\").disabled = false\n document.getElementById(\"pery\").disabled = false\n document.getElementById(\"perz\").disabled = false\n document.getElementById(\"perxrot\").disabled = false\n document.getElementById(\"peryrot\").disabled = false\n document.getElementById(\"perzrot\").disabled = false\n realImageOn == false \n }\n //Marble\n else if(modecur == 2){\n document.getElementById(\"perx\").value = 10.0\n document.getElementById(\"pery\").value = 10.0\n document.getElementById(\"perz\").value = 10.0\n document.getElementById(\"brR\").disabled = true\n document.getElementById(\"brG\").disabled = true\n document.getElementById(\"brB\").disabled = true\n document.getElementById(\"wR\").disabled = true\n document.getElementById(\"wG\").disabled = true\n document.getElementById(\"wB\").disabled = true\n\n document.getElementById(\"perx\").disabled = false\n document.getElementById(\"pery\").disabled = false\n document.getElementById(\"perz\").disabled = false\n document.getElementById(\"perxrot\").disabled = false\n document.getElementById(\"peryrot\").disabled = false\n document.getElementById(\"perzrot\").disabled = false\n\n realImageOn == false \n }\n //Grass\n else if(modecur == 3){\n document.getElementById(\"perx\").value = 60.0\n document.getElementById(\"pery\").value = 20.0\n document.getElementById(\"perz\").value = 60.0\n document.getElementById(\"brR\").disabled = true\n document.getElementById(\"brG\").disabled = true\n document.getElementById(\"brB\").disabled = true\n document.getElementById(\"wR\").disabled = true\n document.getElementById(\"wG\").disabled = true\n document.getElementById(\"wB\").disabled = true\n\n document.getElementById(\"perx\").disabled = false\n document.getElementById(\"pery\").disabled = false\n document.getElementById(\"perz\").disabled = false\n document.getElementById(\"perxrot\").disabled = false\n document.getElementById(\"peryrot\").disabled = false\n document.getElementById(\"perzrot\").disabled = false\n\n realImageOn == false \n }\n //Wood\n else if(modecur == 4){\n document.getElementById(\"perx\").value = 4.0\n document.getElementById(\"pery\").value = 80.0\n document.getElementById(\"perz\").value = 4.0\n document.getElementById(\"brR\").disabled = true\n document.getElementById(\"brG\").disabled = true\n document.getElementById(\"brB\").disabled = true\n document.getElementById(\"wR\").disabled = true\n document.getElementById(\"wG\").disabled = true\n document.getElementById(\"wB\").disabled = true\n\n document.getElementById(\"perx\").disabled = false\n document.getElementById(\"pery\").disabled = false\n document.getElementById(\"perz\").disabled = false\n document.getElementById(\"perxrot\").disabled = false\n document.getElementById(\"peryrot\").disabled = false\n document.getElementById(\"perzrot\").disabled = false\n\n realImageOn == false \n }else if(modecur == 5){\n document.getElementById(\"brR\").disabled = false\n document.getElementById(\"brG\").disabled = false\n document.getElementById(\"brB\").disabled = false\n document.getElementById(\"wR\").disabled = false\n document.getElementById(\"wG\").disabled = false\n document.getElementById(\"wB\").disabled = false\n\n document.getElementById(\"perx\").disabled = false\n document.getElementById(\"pery\").disabled = false\n document.getElementById(\"perz\").disabled = false\n document.getElementById(\"perxrot\").disabled = false\n document.getElementById(\"peryrot\").disabled = false\n document.getElementById(\"perzrot\").disabled = false\n\n realImageOn == false \n }\n gl.uniform1i(modeSh, modecur)\n prevMod = modecur\n\n //Real image when using a model\n if(prevrealImageOn == true ){\n document.getElementById(\"perx\").disabled = true\n document.getElementById(\"pery\").disabled = true\n document.getElementById(\"perz\").disabled = true\n document.getElementById(\"perxrot\").disabled = true\n document.getElementById(\"peryrot\").disabled = true\n document.getElementById(\"perzrot\").disabled = true\n\n document.getElementById(\"brR\").disabled = true\n document.getElementById(\"brG\").disabled = true\n document.getElementById(\"brB\").disabled = true\n document.getElementById(\"wR\").disabled = true\n document.getElementById(\"wG\").disabled = true\n document.getElementById(\"wB\").disabled = true\n\n realImageOn = false\n gl.uniform1i(modeSh, 10)\n }\n }\n\n\n //Reflection on\n var reflection = document.getElementById(\"reflectionCheck\").checked\n if(reflection != prevReflection){\n gl.uniform1i(reflectionOn, reflection)\n }\n prevReflection = reflection\n\n\n //Plane direction\n var dirx = parseFloat(document.getElementById(\"dirx\").value);\n var diry = parseFloat(document.getElementById(\"diry\").value);\n var dirz = parseFloat(document.getElementById(\"dirz\").value);\n if(dirx != NaN && diry != NaN && dirz != NaN ){\n var mgnt = Math.sqrt(dirx*dirx + diry*diry + dirz*dirz)\n\n gl.uniform3f(planeDirectionLocation, dirx/mgnt, diry/mgnt, dirz/mgnt);\n }\n\n //Perlin scale parameters\n if(!document.getElementById(\"perx\").disabled && !document.getElementById(\"pery\").disabled && !document.getElementById(\"perz\").disabled){\n var perlinx = parseFloat(document.getElementById(\"perx\").value);\n var perliny = parseFloat(document.getElementById(\"pery\").value);\n var perlinz = parseFloat(document.getElementById(\"perz\").value);\n if(perlinx != NaN && perliny != NaN && perlinz != NaN){\n gl.uniform3f(scalePerlinFactor, perlinx, perliny, perlinz);\n }\n }\n\n //Perlin translation parameters\n var perlinxTr = parseFloat(document.getElementById(\"perxTr\").value);\n var perlinyTr = parseFloat(document.getElementById(\"peryTr\").value);\n var perlinzTr = parseFloat(document.getElementById(\"perzTr\").value);\n if(perlinxTr != NaN && perlinyTr != NaN && perlinzTr != NaN ){\n gl.uniform3f(transPerlinFactor, perlinxTr, perlinyTr, perlinzTr);\n }\n\n //Perlin rotation parameters\n if(!document.getElementById(\"perxrot\").disabled && !document.getElementById(\"peryrot\").disabled && !document.getElementById(\"perzrot\").disabled){\n var perlinx = parseFloat(document.getElementById(\"perxrot\").value)*Math.PI/180;\n var perliny = parseFloat(document.getElementById(\"peryrot\").value)*Math.PI/180;\n var perlinz = parseFloat(document.getElementById(\"perzrot\").value)*Math.PI/180;\n if(perlinx != NaN && perliny != NaN && perlinz != NaN ){\n if(perlinx >= Math.PI*2 ){\n document.getElementById(\"perxrot\").value = 0.0\n }if(perliny >= Math.PI*2 ){\n document.getElementById(\"peryrot\").value = 0.0\n }if(perlinz >= Math.PI*2 ){\n document.getElementById(\"perzrot\").value = 0.0\n }\n gl.uniform3f(anglePerlinFactor, perlinx, perliny, perlinz);\n }\n }\n\n //Perlin brightness RGB parameters\n if(!document.getElementById(\"brR\").disabled && !document.getElementById(\"brG\").disabled && !document.getElementById(\"brB\").disabled){\n var brR = parseFloat(document.getElementById(\"brR\").value);\n var brG = parseFloat(document.getElementById(\"brG\").value);\n var brB = parseFloat(document.getElementById(\"brB\").value);\n if(brR != NaN && brG != NaN && brB != NaN){\n gl.uniform3f(brightPerlin1, brR, brG, brB);\n }\n }\n\n //Perlin weight RGB parameters\n if(!document.getElementById(\"wR\").disabled && !document.getElementById(\"wG\").disabled && !document.getElementById(\"wB\").disabled){\n var wR = parseFloat(document.getElementById(\"wR\").value);\n var wG = parseFloat(document.getElementById(\"wG\").value);\n var wB = parseFloat(document.getElementById(\"wB\").value);\n if(wR != NaN && wG != NaN && wB != NaN ){\n gl.uniform3f(weightPerlin1, wR, wG, wB);\n }\n }\n\n\n // resize canvas in case window size has changed\n if (canvas.width !== window.innerWidth\n || canvas.height !== window.innerHeight) {\n canvas.width = window.innerWidth;\n canvas.height = window.innerHeight;\n gl.viewport(0, 0, canvas.width, canvas.height);\n ratio = canvas.width / canvas.height;\n }\n\n //const angle = 2 * Math.PI * ((performance.now() / 1000.0) / 6.0);\n var cam = parseFloat(document.getElementById(\"cam\").value) * (Math.PI/180);\n var angle;\n if(cam != NaN ){\n angle = cam;\n }else{\n angle = Math.Pi/4;\n }\n // Calc new camera position\n vec3.rotateY(cameraPosition, cameraInitialPosition, cameraTo, angle);\n\n \n //const angle = 2 * Math.PI * ((performance.now() / 1000.0) / 6.0);\n var camz = parseFloat(document.getElementById(\"camz\").value) * (Math.PI/180);\n var anglez;\n if(camz != NaN ){\n anglez = camz;\n }else{\n anglez = Math.Pi/4;\n }\n // Calc new camera position\n vec3.rotateX(cameraPosition, cameraPosition, cameraTo, anglez);\n\n gl.uniform3f(\n cameraPositionLocation,\n cameraPosition[0],\n cameraPosition[1],\n cameraPosition[2],\n );\n\n // Calc new camera direction\n vec3.subtract(cameraDirection, cameraTo, cameraPosition);\n vec3.normalize(cameraDirection, cameraDirection);\n\n // Calc camera left vector\n vec3.cross(cameraLeft, up, cameraDirection);\n vec3.normalize(cameraLeft, cameraLeft);\n // Calc camera up vector\n vec3.cross(cameraUp, cameraDirection, cameraLeft);\n vec3.normalize(cameraUp, cameraUp);\n\n // Calc near plane center\n vec3.add(nearCenter, cameraPosition, cameraDirection);\n\n // Scale camera left to keep ratio\n vec3.scale(cameraLeft, cameraLeft, ratio);\n\n // Calc near corners\n // TopLeft\n vec3.add(nearTopLeft, nearCenter, cameraUp);\n vec3.add(nearTopLeft, nearTopLeft, cameraLeft);\n // BottomLeft\n vec3.subtract(nearBottomLeft, nearCenter, cameraUp);\n vec3.add(nearBottomLeft, nearBottomLeft, cameraLeft);\n // TopRight\n vec3.add(nearTopRight, nearCenter, cameraUp);\n vec3.subtract(nearTopRight, nearTopRight, cameraLeft);\n // BottomRight\n vec3.subtract(nearBottomRight, nearCenter, cameraUp);\n vec3.subtract(nearBottomRight, nearBottomRight, cameraLeft);\n\n const corners = new Float32Array(12);\n corners.set(nearTopRight, 0);\n corners.set(nearTopLeft, 3);\n corners.set(nearBottomLeft, 6);\n corners.set(nearBottomRight, 9);\n\n gl.bufferData(gl.ARRAY_BUFFER, corners, gl.STATIC_DRAW);\n gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);\n\n\n requestAnimationFrame(renderLoop);\n }\n\n requestAnimationFrame(renderLoop);\n}", "function initWebGLProgram(webGLContext, vertexShaders, fragmentShaders) {\n vertexShaders = R.unless(R.is(Object), vShader => [vShader])(vertexShaders);\n fragmentShaders = R.unless(R.is(Object), fShader => [fShader])(fragmentShaders);\n\n const webGLProgram = webGLContext.createProgram();\n\n prepareShaders(webGLContext.VERTEX_SHADER, vertexShaders);\n prepareShaders(webGLContext.FRAGMENT_SHADER, fragmentShaders);\n\n webGLContext.linkProgram(webGLProgram);\n\n if (!webGLContext.getProgramParameter(webGLProgram, webGLContext.LINK_STATUS)) {\n alert('Could not initialise shaders');\n }\n\n webGLContext.useProgram(webGLProgram);\n\n webGLProgram.vertexPositionAttribute = webGLContext.getAttribLocation(webGLProgram, 'aVertexPosition');\n webGLProgram.pMatrixUniform = webGLContext.getUniformLocation(webGLProgram, 'uPMatrix');\n webGLProgram.mvMatrixUniform = webGLContext.getUniformLocation(webGLProgram, 'uMVMatrix');\n\n return webGLProgram;\n}", "function initializeWebGL() {\n\n // If we don't have a GL context, give up now\n\n if (!gl) {\n alert('Unable to initialize WebGL. Your browser or machine may not support it.');\n return;\n }\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec4 aVertexColor;\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n varying lowp vec4 vColor;\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vColor = aVertexColor;\n }\n `;\n\n // Fragment shader program\n\n const fsSource = `\n varying lowp vec4 vColor;\n void main(void) {\n gl_FragColor = vColor;\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVevrtexColor and also\n // look up uniform locations.\n programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),\n vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),\n },\n };\n\n // Try to load a sample data and visualize it.\n // Load and draw model\n appState.grid = service.generateDataGrid(appState.NX, appState.NY, appState.NZ);\n appState.allQuads = service.buildQuadsForWholeCube(appState.grid, appState.NX, appState.NY, appState.NZ);\n draw();\n\n // Draw the scene repeatedly\n function render(now) {\n\n if (!drag) {\n dX *= AMORTIZATION, dY *= AMORTIZATION;\n transform.angleY += dX, transform.angleX += dY;\n }\n\n drawScene();\n requestAnimationFrame(render);\n }\n\n requestAnimationFrame(render);\n\n}", "function webGLStart() {\n var canvas = document.getElementById(\"webglcanvas\");\n initGL(canvas);\n initShaders();\n initBuffers();\n \n // Prior to drawing the scene , clear color\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n \n drawScene();\n }", "function init() {\r\n\t\tvar canvas = document.getElementById(\"gremlinCanvas\");\r\n try {\r\n\t\t _initGL(canvas);\r\n\t\t _initShaders();\r\n Audio.init();\r\n } catch (error) {\r\n throw error;\r\n }\r\n\t\t_gl.clearColor(0.0, 0.0, 0.0, 1.0);\r\n\t\t_gl.enable(_gl.DEPTH_TEST);\r\n\t}", "function initGL() {\n \n \"use strict\";\n\n // -- 1. Add shaders (load / compile)\n ctx.shaderProgram = loadAndCompileShaders(gl, \"VertexShader.glsl\", \"FragmentShader.glsl\");\n\n // -- 2. Assign attribute-index to context\n setUpAttributesAndUniforms();\n\n // -- 3. Setup buffers\n setUpBuffers();\n\n // -- 4. Set color ??\n gl.clearColor(0.4688,0.1512,0.0000,0.2725);\n\n}", "function initGL() {\n var prog = createProgram(gl,\"vshader-source\",\"fshader-source\");\n gl.useProgram(prog);\n a_coords_loc = gl.getAttribLocation(prog, \"a_coords\");\n a_normal_loc = gl.getAttribLocation(prog, \"a_normal\");\n a_texcoords_loc = gl.getAttribLocation(prog, \"a_texcoords\");\n\n u_modelview = gl.getUniformLocation(prog, \"modelview\");\n u_projection = gl.getUniformLocation(prog, \"projection\");\n u_normalMatrix = gl.getUniformLocation(prog, \"normalMatrix\");\n u_lightPosition= gl.getUniformLocation(prog, \"lightPosition\");\n u_diffuseColor = gl.getUniformLocation(prog, \"diffuseColor\");\n u_specularColor = gl.getUniformLocation(prog, \"specularColor\");\n u_specularExponent = gl.getUniformLocation(prog, \"specularExponent\");\n u_lightPositions = gl.getUniformLocation(prog, \"lightPositions\");\n u_attenuation = gl.getUniformLocation(prog, \"attenuation\");\n u_lightDir = gl.getUniformLocation(prog, \"lightDir\");\n u_drawMode = gl.getUniformLocation(prog, \"drawMode\");\n u_lightAngleLimit = gl.getUniformLocation(prog, \"lightAngleLimit\");\n u_lightEnable = gl.getUniformLocation(prog, \"enable\");\n u_texture = gl.getUniformLocation(prog, \"texture\");\n\n gl.clearColor(0.0,0.0,0.0,1.0);\n gl.enable(gl.DEPTH_TEST);\n\n gl.uniform3f(u_specularColor, 0.5, 0.5, 0.5); \n gl.uniform1f(u_specularExponent, 10);\n texture0 = gl.createTexture();\n\n}", "async function init(){\n\t// retrieve shader using path\n\tvar path = window.location.pathname;\n\tvar page = path.split(\"/\").pop();\n\tbaseDir = window.location.href.replace(page, '');\n\tshaderDir = baseDir + \"shaders/\";\n\n\t// create canvas\n\tvar canvas = document.getElementById(\"c\");\n\tgl = canvas.getContext(\"webgl2\");\n\tconsole.log(gl);\n\tif (!gl) {\n\t\tdocument.write(\"GL context not opened\");\n\t\treturn;\n\t}\n\t\n\t// Loading the shaders and creating programs\n\tawait utils.loadFiles([shaderDir + 'texture_vs.vert', shaderDir + 'texture_fs.frag'], function (shaderText) {\n\t\t// compiles a shader and creates setters for attribs and uniforms\n\t\ttextureProgramInfo = twgl.createProgramInfo(gl, [shaderText[0], shaderText[1]], [\"a_position\", \"a_texcoord\", \"a_normal\"]);\n\t});\n\tawait utils.loadFiles([shaderDir + 'color_vs.vert', shaderDir + 'color_fs.frag'], function (shaderText) {\n\t\t// compiles a shader and creates setters for attribs and uniforms\n\t\tcolorProgramInfo = twgl.createProgramInfo(gl, [shaderText[0], shaderText[1]], [\"a_position\", \"a_normal\"]);\n\t});\n\n\t/*\n\t* Loading the obj models\n\t*/\n\tlet tailWrapper = new ObjectWrapper(baseDir + tailPath);\n\tlet bodyWrapper = new ObjectWrapper(baseDir + bodyPath);\n\tlet leftEyeWrapper = new ObjectWrapper(baseDir + eyePath);\n\tlet rightEyeWrapper = new ObjectWrapper(baseDir + eyePath);\n\tlet hoursClockhandWrapper = new ObjectWrapper(baseDir + hoursClockhandPath);\n\tlet minutesClockhandWrapper = new ObjectWrapper(baseDir + minutesClockhandPath);\n\t// Set the local matrix for each object and the program to draw them\n\ttailWrapper.setLocalMatrix(tailLocalMatrix).setProgramInfo(colorProgramInfo);\n\tbodyWrapper.setLocalMatrix(bodyLocalMatrix).setProgramInfo(textureProgramInfo);\n\tleftEyeWrapper.setLocalMatrix(leftEyeLocalMatrix).setProgramInfo(textureProgramInfo);\n\trightEyeWrapper.setLocalMatrix(rightEyeLocalMatrix).setProgramInfo(textureProgramInfo);\n\thoursClockhandWrapper.setLocalMatrix(clockHand2LocalMatrix).setProgramInfo(colorProgramInfo);\n\tminutesClockhandWrapper.setLocalMatrix(clockHand1LocalMatrix).setProgramInfo(colorProgramInfo);\n\n\t// Save each object wrapper in a unique array of objects to draw\n\tobj = [tailWrapper, leftEyeWrapper, rightEyeWrapper, bodyWrapper, hoursClockhandWrapper, minutesClockhandWrapper];\n\n\tobj.forEach(async (wrapper) => { await wrapper.loadModel(); });\n\n\twindow.addEventListener(\"keydown\", keyFunctionDown, false);\n\n\tresetShaderParams();\n\tmain();\n}", "function initShader(gl, vertexSource, fragmentSource) {\n\n var shaderInfo = {};\n \n // load and compile the fragment and vertex shader\n var fragmentShader = createShader(gl, fragmentSource, \"fragment\");\n var vertexShader = createShader(gl, vertexSource, \"vertex\");\n\n // link them together into a new program\n shaderInfo.shaderProgram = gl.createProgram();\n gl.attachShader(shaderInfo.shaderProgram, vertexShader);\n gl.attachShader(shaderInfo.shaderProgram, fragmentShader);\n gl.linkProgram(shaderInfo.shaderProgram);\n\n // get pointers to the shader params\n shaderInfo.shaderVertexPositionAttribute = gl.getAttribLocation(shaderInfo.shaderProgram, \"vertexPos\");\n gl.enableVertexAttribArray(shaderInfo.shaderVertexPositionAttribute);\n\n shaderInfo.shaderVertexColorAttribute = gl.getAttribLocation(shaderInfo.shaderProgram, \"vertexColor\");\n gl.enableVertexAttribArray(shaderInfo.shaderVertexColorAttribute);\n\n shaderInfo.shaderProjectionMatrixUniform = gl.getUniformLocation(shaderInfo.shaderProgram, \"projectionMatrix\");\n shaderInfo.shaderModelViewMatrixUniform = gl.getUniformLocation(shaderInfo.shaderProgram, \"modelViewMatrix\");\n\n\n if (!gl.getProgramParameter(shaderInfo.shaderProgram, gl.LINK_STATUS)) {\n alert(\"Could not initialise shaders\");\n }\n \n return shaderInfo;\n}", "function initProgram() {\n const vertexShader = getShader('vertex-shader');\n const fragmentShader = getShader('fragment-shader');\n\n // Create a program\n program = gl.createProgram();\n // Attach the shaders to this program\n gl.attachShader(program, vertexShader);\n gl.attachShader(program, fragmentShader);\n gl.linkProgram(program);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n console.error('Could not initialize shaders');\n }\n\n // Use this program instance\n gl.useProgram(program);\n // We attach the location of these shader values to the program instance\n // for easy access later in the code\n program.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');\n program.aBary = gl.getAttribLocation(program, 'bary');\n program.uModelT = gl.getUniformLocation (program, 'modelT');\n program.uViewT = gl.getUniformLocation (program, 'viewT');\n program.uProjT = gl.getUniformLocation (program, 'projT');\n }", "function _init() {\n\n _gl = canvasModalWidget.getGLContext();\n\n if (!_gl) {\n throw new Error('Could not run lightingExample() WebGL Demo!');\n }\n\n // Set clear color to black, fully opaque\n _gl.clearColor(0.0, 0.0, 0.0, 1.0);\n\n // dealing with 3D space geometry so make sure this feature is enabled\n _gl.enable(_gl.DEPTH_TEST);\n\n // get the shaders and compile them - the resultant will be a program that is automatically joined to the gl context in the background\n _glProgram = canvasModalWidget.setGLVertexAndFragmentShaders('#v-shader-pong', '#f-shader-pong');\n _glProgram.customAttribs = {};\n\n // Get the storage locations of all the customizable shader variables\n _glProgram.customAttribs.a_PositionRef = _gl.getAttribLocation(_glProgram, 'a_Position'),\n _glProgram.customAttribs.a_VertexNormalRef = _gl.getAttribLocation(_glProgram, 'a_VertexNormal'),\n\n _glProgram.customAttribs.u_FragColourRef = _gl.getUniformLocation(_glProgram, 'u_FragColour'),\n _glProgram.customAttribs.u_PVMMatrixRef = _gl.getUniformLocation(_glProgram, 'u_PVMMatrix'),\n _glProgram.customAttribs.u_NormalMatrixRef = _gl.getUniformLocation(_glProgram, 'u_NormalMatrix'),\n\n _glProgram.customAttribs.u_AmbientColourRef = _gl.getUniformLocation(_glProgram, 'u_AmbientColour'),\n _glProgram.customAttribs.u_LightingDirectionRef = _gl.getUniformLocation(_glProgram, 'u_LightingDirection'),\n _glProgram.customAttribs.u_DirectionalColourRef = _gl.getUniformLocation(_glProgram, 'u_DirectionalColour');\n\n _glProgram.customAttribs.eyePosition = vec3.fromValues(0, 0, 5);\n _glProgram.customAttribs.centerPoint = vec3.fromValues(0, 0, -50);\n\n var perspectiveMatrix = mat4.create(), // get the identity matrix\n viewMatrix = mat4.create(),\n modelMatrix = mat4.create(),\n PVMMatrix = mat4.create();\n\n mat4.perspective(perspectiveMatrix, glMatrix.toRadian(45.0), canvasModalWidget.getGLViewportAspectRatio(), 1, 1000);\n mat4.lookAt(viewMatrix, _glProgram.customAttribs.eyePosition, _glProgram.customAttribs.centerPoint, vec3.fromValues(0, 1, 0));\n\n _glProgram.customAttribs.viewMatrix = viewMatrix;\n _glProgram.customAttribs.modelMatrix = modelMatrix;\n _glProgram.customAttribs.perspectiveMatrix = perspectiveMatrix;\n\n mat4.multiply(PVMMatrix, perspectiveMatrix, viewMatrix);\n\n _glProgram.customAttribs.PVMMatrix = PVMMatrix;\n\n _gl.uniformMatrix4fv(_glProgram.customAttribs.u_PVMMatrixRef, false, _glProgram.customAttribs.PVMMatrix);\n\n // set our directional light which is pointing 10 units to the left 10 units upwards away 5 units from the user \n _glProgram.customAttribs.lightingDirection = _setLightingDirection(-10.0, 10.0, -5.0);\n\n _gl.uniform3fv(_glProgram.customAttribs.u_LightingDirectionRef, _glProgram.customAttribs.lightingDirection);\n _gl.uniform3f(_glProgram.customAttribs.u_AmbientColourRef, 0.5, 0.5, 0.5);\n\n _gl.uniform3f(_glProgram.customAttribs.u_DirectionalColourRef, 1.0, 1.0, 1.0);\n\n // start the game!!\n _game = new _Game();\n\n }", "function initGL() {\r\n var prog = createProgram(gl,\"vshader-source\",\"fshader-source\");\r\n gl.useProgram(prog);\r\n a_coords_loc = gl.getAttribLocation(prog, \"a_coords\");\r\n a_normal_loc = gl.getAttribLocation(prog, \"a_normal\");\r\n u_modelview = gl.getUniformLocation(prog, \"modelview\");\r\n u_projection = gl.getUniformLocation(prog, \"projection\");\r\n u_normalMatrix = gl.getUniformLocation(prog, \"normalMatrix\");\r\n u_lightPosition= gl.getUniformLocation(prog, \"lightPosition\");\r\n u_lightPositionA= gl.getUniformLocation(prog, \"lightPositionA\");\r\n u_lightPositionB= gl.getUniformLocation(prog, \"lightPositionB\");\r\n u_diffuseColor = gl.getUniformLocation(prog, \"diffuseColor\");\r\n u_specularColor = gl.getUniformLocation(prog, \"specularColor\");\r\n u_specularExponent = gl.getUniformLocation(prog, \"specularExponent\");\r\n u_color = gl.getUniformLocation(prog, \"color\");\r\n u_spotLightDir = gl.getUniformLocation(prog, \"spotLightDir\");\r\n u_day = gl.getUniformLocation(prog, \"day\");\r\n a_coords_buffer = gl.createBuffer();\r\n a_normal_buffer = gl.createBuffer();\r\n index_buffer = gl.createBuffer();\r\n gl.enable(gl.DEPTH_TEST);\r\n gl.uniform3f(u_specularColor, 0.5, 0.5, 0.5);\r\n gl.uniform4f(u_diffuseColor, 1, 1, 1, 1);\r\n gl.uniform1f(u_specularExponent, 10); \r\n gl.uniform4f(u_lightPosition, lightPositions[0][0], lightPositions[0][1], lightPositions[0][2], lightPositions[0][3]); \r\n gl.uniform4f(u_lightPositionA, lightPositions[1][0], lightPositions[1][1], lightPositions[1][2], lightPositions[1][3]);\r\n gl.uniform4f(u_lightPositionB, lightPositions[2][0], lightPositions[2][1], lightPositions[2][2], lightPositions[2][3]);\r\n}", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\n\n gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT);\n gl.enable(gl.DEPTH_TEST);\n gl.enable(gl.CULL_FACE);\n gl.frontFace(gl.CCW);\n gl.cullFace(gl.BACK);\n\n setUpAttributesAndUniforms();\n setUpBuffers();\n\n // set the clear color here\n // NOTE(TF) Aufgabe 1 / Frage:\n // clearColor() only sets the color for the buffer, but doesn't actually do anything else.\n // clear() has to be called in order for the color to be painted.\n gl.clearColor(0.8, 0.8, 0.8, 1.0);\n\n // add more necessary commands here\n}", "init(vertexShaderName, fragmentShaderName, textureName1) {\n let vertexShaderSource = document.getElementById(vertexShaderName).innerHTML;\n let fragmentShaderSource = document.getElementById(fragmentShaderName).innerHTML;\n this.shaderProgram = createProgram(this.gl, vertexShaderSource, fragmentShaderSource);\n if (!this.shaderProgram) {\n console.log('Feil ved initialisering av shaderkoden.');\n } else {\n this.loadTexture(textureName1);\n }\n }", "function init(){\n\tconsole.log('Running');\n\trenderer = new RenderManager(\"game_canvas\");\n\tgl = renderer.gl;\n\tkeyboard = new KeyBoard();\n\n\tshaderName = 'triangle';\n\tvar triangleShader = new CreateShader(gl);\n\ttextureName = 'blue_sky';\n\ttextureObj = new Texture('bluecloud_bk.jpg', gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE, gl.LINEAR, gl.LINEAR);\n\ttextureObj.loadTexture();\n\ttriangleShader.makeProgram(\"vertShader.txt\", \"fragShader.txt\");\n\tvar delay = 150;\n\tif(navigator.userAgent.indexOf(\"Firefox\") != -1){\n\t\tdelay = 450;\n\t}\n\tsetTimeout(start, delay);\n}", "function webGLStart(fragShader) {\n\tvar canvas = document.getElementById(\"opengl-canvas\");\n\tinitGL(canvas);\n\n\tvar fragmentShaderResult = makeShader(gl, fragShader, \"fragment\");\n\tif (fragmentShaderResult.shader == null) {\n\t\tvar error = \"Failed making fragment shader.\";\n\t\tconsole.log(error);\n\t\treturn {\n\t\t\tsucceeded: false,\n\t\t\terror: \"COMPILE_ERROR\",\n\t\t\tlog: error + \"\\n\" + fragmentShaderResult.log\n\t\t};\n\t}\n\n\tvar vertexShaderResult = makeShader(gl, getShaderFromURL(\"shaders/shader.vert\"), \"vertex\");\n\tif (vertexShaderResult.shader == null) {\n\t\tvar error = \"Failed making vertex shader.\";\n\t console.log(error);\n\t\treturn {\n\t\t\tsucceeded: false,\n\t\t\terror: \"COMPILE_ERROR\",\n\t\t\tlog: error + \"\\n\" + vertexShaderResult.log\n\t\t};\n\t}\n\n\tvar initResult = initShaders(fragmentShaderResult.shader, vertexShaderResult.shader);\n\tif (!initResult.succeeded) {\n\t\treturn {\n\t\t\tsucceeded: false,\n\t\t\terror: \"LINK_ERROR\",\n\t\t\tlog: initResult.log\n\t\t};\n\t}\n\n\tinitBuffers();\n\n\tgl.clearColor(0.0, 0.0, 0.0, 1.0);\n\tdrawScene(initResult.shaderProgram);\n\tgl.finish();\n\n\treturn {\n\t\tsucceeded: true,\n\t\tlog: \"\"\n\t};\n}", "function startup() {\n canvas = document.getElementById(\"myGLCanvas\");\n gl = createGLContext(canvas);\n setupShaders(); \n setupBuffers();\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.enable(gl.DEPTH_TEST); //check the draw is right\n // gl.enable(gl.CULL_FACE); //check the draw is right\n //gl.cullFace(gl.BACK); \n tick();\n}", "function setupShaders() {\r\n //console.log(\"SETTING UP SHADER FOR CUBE\\n\");\r\n vertexShader = loadShaderFromDOM(\"shader-vs\");\r\n fragmentShader = loadShaderFromDOM(\"shader-fs\");\r\n\r\n shaderProgram = gl.createProgram();\r\n gl.attachShader(shaderProgram, vertexShader);\r\n gl.attachShader(shaderProgram, fragmentShader);\r\n gl.linkProgram(shaderProgram);\r\n\r\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\r\n alert(\"Failed to setup shaders\");\r\n }\r\n\r\n gl.useProgram(shaderProgram);\r\n\r\n\r\n\r\n\r\n shaderProgram.texCoordAttribute = gl.getAttribLocation(shaderProgram, \"aTexCoord\");\r\n //console.log(\"Tex coord attrib: \", shaderProgram.texCoordAttribute);\r\n gl.enableVertexAttribArray(shaderProgram.texCoordAttribute);\r\n\r\n shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, \"aVertexPosition\");\r\n //console.log(\"Vertex attrib: \", shaderProgram.vertexPositionAttribute);\r\n gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);\r\n\r\n shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, \"uMVMatrix\");\r\n shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, \"uPMatrix\");\r\n\r\n}", "function WebGLStart(){\n\n//initialize everything\n\tinit();\n\n//define the tweens\n\tdefineTweens();\n\n//draw everything\n\tdrawScene();\n\n//begin the animation\n\tanimate();\n}", "function initShaderProgram(gl, vsSource, fsSource) {\t\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\t\t\n // Create the shader program\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, fragmentShader);\n gl.attachShader(shaderProgram, vertexShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n return null;\n }\n\n return shaderProgram;\n}", "function initGL(canvas){\r\n\ttry{\r\n\t\tctx.viewportWidth = canvas.width;\r\n\t\tctx.viewportHeight = canvas.height;\r\n\t\tinitBuffers(ctx);\r\n\t\t\r\n\t\t//Initialize default shader\r\n\t\tfragShader = compileShader(ctx, defaultFragSrc);\r\n\t\tvertShader = compileShader(ctx, defaultVertSrc);\r\n\t\tshaderProgram = createShaderProgram();\r\n\t\tsetupSpriteShader(shaderProgram);\r\n\t\tspriteShader = shaderProgram;\r\n\t\t\r\n\t\tcolorBuffer = createRenderTarget(ctx, canvas.width, canvas.height);\r\n\t\tstateBuffer = createRenderTarget(ctx, canvas.width, canvas.height);\r\n\t\t\r\n\t\tctx.clearColor(0.0, 0.0, 0.0, 1.0);\r\n\t\t\r\n\t\tctx.blendFunc(ctx.SRC_ALPHA, ctx.ONE_MINUS_SRC_ALPHA);\r\n\t\tctx.enable(ctx.BLEND);\r\n\t}catch(e){\r\n\t}\r\n}", "function initScene(gl) {\r\n\r\n //////////////////////////////////////////\r\n //////// set up geometry - plane ////////\r\n //////////////////////////////////////////\r\n\r\n var vPlane = [];\r\n\r\n for (var j = height - 1; j >= 0; j--) {\r\n for (var i = 0; i < width; i++) {\r\n var A = vec3.fromValues(i - (width - 1) * 0.5,\r\n height - 1 - j - (height - 1) * 0.5,\r\n 0);\r\n // push the vertex coordinates\r\n vPlane.push(A[0]);\r\n vPlane.push(A[1]);\r\n vPlane.push(A[2]);\r\n // push the normal coordinates\r\n vPlane.push(0);\r\n vPlane.push(0);\r\n vPlane.push(1);\r\n vPlane.push(i);\r\n vPlane.push(j);\r\n }\r\n }\r\n\r\n var iPlane = [];\r\n\r\n for (var j = 0; j < height - 1; j++) {\r\n for (var i = 0; i < width - 1; i++) {\r\n iPlane.push(j * width + i);\r\n iPlane.push((j + 1) * width + i);\r\n iPlane.push(j * width + i + 1);\r\n iPlane.push(j * width + i + 1);\r\n iPlane.push((j + 1) * width + i);\r\n iPlane.push((j + 1) * width + i + 1);\r\n }\r\n }\r\n\r\n // create vertex buffer on the gpu\r\n vboPlane = gl.createBuffer();\r\n // bind buffer\r\n gl.bindBuffer(gl.ARRAY_BUFFER, vboPlane);\r\n // copy data from cpu to gpu memory\r\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vPlane), gl.STATIC_DRAW);\r\n\r\n // create index buffer on the gpu\r\n iboPlane = gl.createBuffer();\r\n // bind buffer\r\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboPlane);\r\n // copy data from cpu to gpu memory\r\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(iPlane), gl.STATIC_DRAW);\r\n\r\n iboNPlane = iPlane.length;\r\n\r\n ///////////////////////////////////////////////\r\n //////// set up geometry - light source //////\r\n ///////////////////////////////////////////////\r\n\r\n var vLight = [0.0, 0.0, 0.0];\r\n\r\n var iLight = [0];\r\n\r\n // create vertex buffer on the gpu\r\n vboLight = gl.createBuffer();\r\n // bind buffer\r\n gl.bindBuffer(gl.ARRAY_BUFFER, vboLight);\r\n // copy data from cpu to gpu memory\r\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vLight), gl.STATIC_DRAW);\r\n\r\n // create index buffer on the gpu\r\n iboLight = gl.createBuffer();\r\n // bind buffer\r\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, iboLight);\r\n // copy data from cpu to gpu memory\r\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(iLight), gl.STATIC_DRAW);\r\n\r\n iboNLight = iLight.length;\r\n\r\n ////////////////////////////////\r\n //////// set up shaders //////\r\n ////////////////////////////////\r\n shaderProgramPlane = shaderProgram(gl, \"shader-vs-phong\", \"shader-fs-phong\");\r\n shaderProgramLight = shaderProgram(gl, \"shader-vs-light\", \"shader-fs-light\");\r\n\r\n /////////////////////////////////\r\n //////// set up textures //////\r\n /////////////////////////////////\r\n var image = document.getElementById('checkerboard');\r\n textureCheckerboard = gl.createTexture();\r\n gl.bindTexture(gl.TEXTURE_2D, textureCheckerboard);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\r\n gl.bindTexture(gl.TEXTURE_2D, null);\r\n\r\n\r\n \r\n // TODO 6.3a): Set up the texture containing the checkerboard\r\n // image. Have a look at the functions gl.bindTexture(),\r\n // gl.texImage2D() and gl.texParameteri(). Also do not\r\n // forget to generate the mipmap pyramid using \r\n // gl.generateMipmap(). Note: Both format and internal\r\n // format parameter should be gl.RGBA, the data type\r\n // used should be gl.UNSIGNED_BYTE.\r\n gl.bindTexture(gl.TEXTURE_2D,textureCheckerboard);\r\n gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,image);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\r\n gl.generateMipmap(gl.TEXTURE_2D);\r\n gl.bindTexture(gl.TEXTURE_2D, null);\r\n\r\n var image = document.getElementById('cobblestone');\r\n textureCobblestone = gl.createTexture();\r\n\r\n \r\n // TODO 6.3b): Set up the texture containing the cobblestone\r\n // image, also using gl.bindTexture() and gl.texImage2D().\r\n // We do not need mipmapping here, so do not forget to \r\n // use gl.texParameteri() to set the minification filter \r\n // to gl.LINEAR. Format, internal format and type should\r\n // be the same as for the checkerboard texture.\r\n gl.bindTexture(gl.TEXTURE_2D, textureCobblestone);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\r\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\r\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\r\n gl.bindTexture(gl.TEXTURE_2D, null);\r\n\r\n\r\n \r\n\r\n }", "function init() {\n \n // Retrieve the canvas\n const canvas = document.getElementById('webgl-canvas');\n if (!canvas) {\n console.error(`There is no canvas with id ${'webgl-canvas'} on this page.`);\n return null;\n }\n\n\n // Retrieve a WebGL context\n gl = canvas.getContext('webgl2');\n if (!gl) {\n console.error(`There is no WebGL 2.0 context`);\n return null;\n }\n \n // Set the clear color to be black\n gl.clearColor(0, 0, 0, 1);\n \n // some GL initialization\n gl.enable(gl.DEPTH_TEST);\n gl.enable(gl.CULL_FACE);\n \n gl.cullFace(gl.BACK);\n gl.frontFace(gl.CCW);\n gl.clearColor(0.0,0.0,0.0,1.0)\n gl.depthFunc(gl.LEQUAL)\n gl.clearDepth(1.0)\n\n // Read, compile, and link your shaders\n initProgram();\n \n // create and bind your current object\n createShapes();\n \n // set up your camera\n setUpCamera();\n \n // do a draw\n draw();\n }", "function setupterrianShaders(){\n var vertexShadert =loadShaderFromDOM(\"terrain-vs\");\n var fragmentShadert =loadShaderFromDOM(\"terrain-fs\");\n\n terrainProgram = gl.createProgram();\n gl.attachShader(terrainProgram, vertexShadert);\n gl.attachShader(terrainProgram, fragmentShadert);\n gl.linkProgram(terrainProgram);\n\n if (!gl.getProgramParameter(terrainProgram, gl.LINK_STATUS)){\n alert(\"Failed to setup terrainshaders\");\n }\n\n gl.useProgram(terrainProgram);\n\n terrainProgram.vertexNormalAttribute =gl.getAttribLocation(terrainProgram, \"aVertexNormalt\");\n console.log(\"Vex norm attrib: \", terrainProgram.vertexNormalAttribute);\n gl.enableVertexAttribArray(terrainProgram.vertexNormalAttribute);\n\n terrainProgram.vertexPositionAttribute = gl.getAttribLocation(terrainProgram, \"aVertexPositiont\");\n console.log(\"Vertex Position attrib: \", terrainProgram.vertexPositionAttribute);\n gl.enableVertexAttribArray(terrainProgram.vertexPositionAttribute);\n\n terrainProgram.textureCoordAttribute = gl.getAttribLocation(terrainProgram, \"aTexCoord\");\n gl.enableVertexAttribArray(terrainProgram.textureCoordAttribute);\n\n terrainProgram.mvMatrixUniform = gl.getUniformLocation(terrainProgram, \"uMVMatrixt\");\n terrainProgram.pMatrixUniform = gl.getUniformLocation(terrainProgram, \"uPMatrixt\");\n terrainProgram.nMatrixUniform = gl.getUniformLocation(terrainProgram, \"uNMatrixt\");\n terrainProgram.uniformLightPositionLoc = gl.getUniformLocation(terrainProgram, \"uLightPosition\"); \n terrainProgram.uniformAmbientLightColorLoc = gl.getUniformLocation(terrainProgram, \"uAmbientLightColor\"); \n terrainProgram.uniformDiffuseLightColorLoc = gl.getUniformLocation(terrainProgram, \"uDiffuseLightColor\");\n terrainProgram.uniformSpecularLightColorLoc = gl.getUniformLocation(terrainProgram, \"uSpecularLightColor\");\n terrainProgram.TextureSamplerUniform = gl.getUniformLocation(terrainProgram, \"uImage\");\n\n \n}", "function init(gl, wgl) {\n initShaders(gl, wgl); // Setup the shader program and program info\n initModels(gl, wgl); // Build objects to be drawn and their buffers\n initLights(gl, wgl); // Setup lighting\n initGl(gl, wgl); // Setup gl properties\n}", "function startup() {\r\n canvas = document.getElementById(\"myGLCanvas\");\r\n gl = createGLContext(canvas);\r\n setupShaders(); \r\n setupBuffers();\r\n gl.clearColor(0.0, 0.0, 0.0, 0.0);\r\n gl.enable(gl.DEPTH_TEST);\r\n tick();\r\n}", "function initGL() {\n \"use strict\";\n ctx.shaderProgram = loadAndCompileShaders(gl, 'VertexShader.glsl', 'FragmentShader.glsl');\n setUpAttributesAndUniforms();\n setUpBuffers();\n loadTexture();\n\n // set the clear color here\n // NOTE(TF) Aufgabe 1 / Frage:\n // clearColor() only sets the color for the buffer, but doesn't actually do anything else.\n // clear() has to be called in order for the color to be painted.\n gl.clearColor(0.8, 0.8, 0.8, 1.0);\n\n // add more necessary commands here\n}", "function start() {\n \"use strict\";\n\n // sets up webgl, twgl, and canvas\n let canvas = document.getElementById(\"mycanvas\");\n let gl = canvas.getContext(\"webgl\");\n let m4 = twgl.m4;\n\n // sets up the sliders\n let slider = document.getElementById('slider');\n slider.value = 0;\n let slider1 = document.getElementById('slider1');\n slider1.value = 0;\n let slider2 = document.getElementById('slider2');\n slider2.value = 0;\n\n // reads the vertex shader and fragment shader\n let vertexSource = document.getElementById(\"vs\").text;\n let fragmentSource = document.getElementById(\"fs\").text;\n\n // compiles the vertex shader\n let vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertexShader,vertexSource);\n gl.compileShader(vertexShader);\n // checks if compilation of vertex shader worked\n if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n alert(gl.getShaderInfoLog(vertexShader)); return null; }\n\n // compiles the fragment shader\n let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragmentShader,fragmentSource);\n gl.compileShader(fragmentShader);\n // checks if compilation of fragment shader worked\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n alert(gl.getShaderInfoLog(fragmentShader)); return null; }\n\n // attaches both vertex and fragment shader to the shader program\n let shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n // checks to see that the program was linked correctly\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\"Could not initialize shaders\"); }\n gl.useProgram(shaderProgram);\n\n // sets up the vPosition attribute for the vertex shader\n shaderProgram.PositionAttribute = gl.getAttribLocation(shaderProgram, \"vPosition\");\n gl.enableVertexAttribArray(shaderProgram.PositionAttribute);\n\n //sets up the vColor attribute for the vertex shader\n shaderProgram.ColorAttribute = gl.getAttribLocation(shaderProgram, \"vColor\");\n gl.enableVertexAttribArray(shaderProgram.ColorAttribute);\n\n // access to the matrix uniform\n shaderProgram.MVPmatrix = gl.getUniformLocation(shaderProgram,\"uMVP\");\n\n // array of vertices for the main cube\n let vertexPosCube = new Float32Array(\n [ 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1,\n 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1,\n 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1,\n -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1,\n -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1,\n 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 ]);\n\n // array of colors for the main cube\n let colorsForCube = new Float32Array(\n [ .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833,\n .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833,\n .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833,\n .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833,\n .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833,\n .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833, .7067,.5833,.1833 ]);\n\n // triangle indices for the main cube\n let triangleIndicesCube = new Uint8Array(\n [ 0, 1, 2, 0, 2, 3,\n 4, 5, 6, 4, 6, 7,\n 8, 9,10, 8,10,11,\n 12,13,14, 12,14,15,\n 16,17,18, 16,18,19,\n 20,21,22, 20,22,23 ]);\n\n // puts vertices into a buffer to allow us to transfer them to the graphics hardware\n let trianglePosBufferCube = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferCube);\n gl.bufferData(gl.ARRAY_BUFFER, vertexPosCube, gl.STATIC_DRAW);\n trianglePosBufferCube.itemSize = 3;\n trianglePosBufferCube.numItems = 24;\n\n // puts colors into a buffer to allow us to transfer them to the graphics hardware\n let colorBufferCube = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferCube);\n gl.bufferData(gl.ARRAY_BUFFER, colorsForCube, gl.STATIC_DRAW);\n colorBufferCube.itemSize = 3;\n colorBufferCube.numItems = 24;\n\n // puts indices into a buffer to allow us to transfer them to the graphics hardware\n let indexBufferCube = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferCube);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndicesCube, gl.STATIC_DRAW);\n\n // vertex positions for the silver triangle\n let vertexPosSilverTriangle = new Float32Array (\n [ 0,0,0, .25,1,.25, 0,0,1,\n 0,0,0, 1,0,0, 0,0,1,\n 0,0,0, 1,0,0, .25,1,.25,\n .25,1,.25, 1,0,0, 0,0,1 ]);\n\n // colors for each vertex for the silver triangle\n let vertexColorsSilverTriangle = new Float32Array (\n [ .64,.64,.64, .64,.64,.64, .64,.64,.64,\n .35,.35,.35, .35,.35,.35, .35,.35,.35,\n .75,.75,.75, .75,.75,.75, .75,.75,.75,\n .2,.2,.2, .2,.2,.2, .2,.2,.2, ]);\n\n // triangle indices for the silver triangle\n let triangleIndicesSilverTriangle = new Uint8Array(\n [ 0, 1, 2,\n 3, 4, 5,\n 6, 7, 8,\n 9,10,11 ]);\n\n // puts vertices into a buffer to allow us to transfer them to the graphics hardware\n let trianglePosBufferSilverTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferSilverTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexPosSilverTriangle, gl.STATIC_DRAW);\n trianglePosBufferSilverTriangle.itemSize = 3;\n trianglePosBufferSilverTriangle.numItems = 12;\n\n // puts colors into a buffer to allow us to transfer them to the graphics hardware\n let colorBufferSilverTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferSilverTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexColorsSilverTriangle, gl.STATIC_DRAW);\n colorBufferSilverTriangle.itemSize = 3;\n colorBufferSilverTriangle.numItems = 12;\n\n // puts indices into a buffer to allow us to transfer them to the graphics hardware\n let indexBufferSilverTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferSilverTriangle);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndicesSilverTriangle, gl.STATIC_DRAW);\n\n // vertex positions for the silver triangle\n let vertexPosGreenTriangle = new Float32Array (\n [ 0,0,0, .25,1,.25, 0,0,1,\n 0,0,0, 1,0,0, 0,0,1,\n 0,0,0, 1,0,0, .25,1,.25,\n .25,1,.25, 1,0,0, 0,0,1 ]);\n\n // colors for each vertex for the silver triangle\n let vertexColorsGreenTriangle = new Float32Array (\n [ .5,.8,0, .5,.8,0, .5,.8,0,\n 0,1,0, 0,1,0, 0,1,0,\n .2,.6,.1, .2,.6,.1, .2,.6,.1,\n .6,1,.2, .6,1,.2, .6,1,.2, ]);\n\n // triangle indices for the silver triangle\n let triangleIndicesGreenTriangle = new Uint8Array(\n [ 0, 1, 2,\n 3, 4, 5,\n 6, 7, 8,\n 9,10,11 ]);\n\n // puts vertices into a buffer to allow us to transfer them to the graphics hardware\n let trianglePosBufferGreenTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferGreenTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexPosGreenTriangle, gl.STATIC_DRAW);\n trianglePosBufferGreenTriangle.itemSize = 3;\n trianglePosBufferGreenTriangle.numItems = 12;\n\n // puts colors into a buffer to allow us to transfer them to the graphics hardware\n let colorBufferGreenTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferGreenTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexColorsGreenTriangle, gl.STATIC_DRAW);\n colorBufferGreenTriangle.itemSize = 3;\n colorBufferGreenTriangle.numItems = 12;\n\n // puts indices into a buffer to allow us to transfer them to the graphics hardware\n let indexBufferGreenTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferGreenTriangle);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndicesGreenTriangle, gl.STATIC_DRAW);\n\n // vertex positions for the silver triangle\n let vertexPosBlueTriangle = new Float32Array (\n [ 0,0,0, .25,1,.25, 0,0,1,\n 0,0,0, 1,0,0, 0,0,1,\n 0,0,0, 1,0,0, .25,1,.25,\n .25,1,.25, 1,0,0, 0,0,1 ]);\n\n // colors for each vertex for the silver triangle\n let vertexColorsBlueTriangle = new Float32Array (\n [ .2,.2,1, .2,.2,1, .2,.2,1,\n 0,0,1, 0,0,1, 0,0,1,\n .2,.6,1, .2,.6,1, .2,.6,1,\n 0,0,.5, 0,0,.5, 0,0,.5, ]);\n\n // triangle indices for the silver triangle\n let triangleIndicesBlueTriangle = new Uint8Array(\n [ 0, 1, 2,\n 3, 4, 5,\n 6, 7, 8,\n 9,10,11 ]);\n\n // puts vertices into a buffer to allow us to transfer them to the graphics hardware\n let trianglePosBufferBlueTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferBlueTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexPosBlueTriangle, gl.STATIC_DRAW);\n trianglePosBufferBlueTriangle.itemSize = 3;\n trianglePosBufferBlueTriangle.numItems = 12;\n\n // puts colors into a buffer to allow us to transfer them to the graphics hardware\n let colorBufferBlueTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferBlueTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexColorsBlueTriangle, gl.STATIC_DRAW);\n colorBufferBlueTriangle.itemSize = 3;\n colorBufferBlueTriangle.numItems = 12;\n\n // puts indices into a buffer to allow us to transfer them to the graphics hardware\n let indexBufferBlueTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferBlueTriangle);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndicesBlueTriangle, gl.STATIC_DRAW);\n\n // vertex positions for the silver triangle\n let vertexPosRedTriangle = new Float32Array (\n [ 0,0,0, .25,1,.25, 0,0,1,\n 0,0,0, 1,0,0, 0,0,1,\n 0,0,0, 1,0,0, .25,1,.25,\n .25,1,.25, 1,0,0, 0,0,1 ]);\n\n // colors for each vertex for the silver triangle\n let vertexColorsRedTriangle = new Float32Array (\n [ 1,0,0, 1,0,0, 1,0,0,\n .4,0,0, .4,0,0, .4,0,0,\n .6,0,0, .6,0,0, .6,0,0,\n .8,0,0, .8,0,0, .8,0,0, ]);\n\n // triangle indices for the silver triangle\n let triangleIndicesRedTriangle = new Uint8Array(\n [ 0, 1, 2,\n 3, 4, 5,\n 6, 7, 8,\n 9,10,11 ]);\n\n // puts vertices into a buffer to allow us to transfer them to the graphics hardware\n let trianglePosBufferRedTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferRedTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexPosRedTriangle, gl.STATIC_DRAW);\n trianglePosBufferRedTriangle.itemSize = 3;\n trianglePosBufferRedTriangle.numItems = 12;\n\n // puts colors into a buffer to allow us to transfer them to the graphics hardware\n let colorBufferRedTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferRedTriangle);\n gl.bufferData(gl.ARRAY_BUFFER, vertexColorsRedTriangle, gl.STATIC_DRAW);\n colorBufferRedTriangle.itemSize = 3;\n colorBufferRedTriangle.numItems = 12;\n\n // puts indices into a buffer to allow us to transfer them to the graphics hardware\n let indexBufferRedTriangle = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferRedTriangle);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, triangleIndicesRedTriangle, gl.STATIC_DRAW);\n\n /**\n * This method actually draws the objects to be drawn.\n */\n function draw() {\n // first slider changes camera position around the y-axis\n let angle1 = slider.value * (Math.PI/180);\n // second slider rotates the object\n let angle2 = slider1.value * (Math.PI/180);\n // third slider rotates the triangles\n let angle3 = slider2.value * (Math.PI/180);\n\n // sets up the camera view\n let eye = [400.0*Math.sin(angle1),150.0,400.0*Math.cos(angle1)];\n let target = [0,0,0];\n let up = [0,1,0];\n let tCamera = m4.inverse(m4.lookAt(eye,target,up));\n\n // rotates entire object over x-axis\n let xRotation = m4.axisRotation([1,0,0],angle2);\n\n // model transformation for the cube\n let tModelCube = m4.multiply(m4.scaling([75,75,75]), xRotation);\n\n // rotation for all triangles\n let tRotation = m4.axisRotation([1,1,1], angle3);\n\n // model transformation for the silver triangle\n let tModel_SilverTriangle = m4.multiply(m4.scaling([50,50,50]), m4.translation([75,-75,75]));\n let tModelSilverTriangle = m4.multiply(m4.multiply(tRotation, tModel_SilverTriangle), xRotation);\n\n // model transformation for the green triangle\n let rotation = m4.axisRotation([0,1,0], -Math.PI/2);\n let tModel_GreenTriangle = m4.multiply(m4.scaling([50,50,50]), m4.translation([-75,-75,75]));\n let tModelGreenTriangle1 = m4.multiply(m4.multiply(rotation, tModel_GreenTriangle), xRotation);\n let tModelGreenTriangle = m4.multiply(tRotation, tModelGreenTriangle1);\n\n // model transformation for the green triangle\n let rotation1 = m4.axisRotation([0,1,0],Math.PI);\n let tModel_BlueTriangle = m4.multiply(m4.scaling([50,50,50]), m4.translation([-75,-75,-75]));\n let tModelBlueTriangle1 = m4.multiply(m4.multiply(rotation1, tModel_BlueTriangle), xRotation);\n let tModelBlueTriangle = m4.multiply(tRotation, tModelBlueTriangle1);\n\n // model transformation for the red triangle\n let rotation2 = m4.axisRotation([0,1,0],Math.PI/2);\n let tModel_RedTriangle = m4.multiply(m4.scaling([50,50,50]), m4.translation([75,-75,-75]));\n let tModelRedTriangle1 = m4.multiply(m4.multiply(rotation2, tModel_RedTriangle), xRotation);\n let tModelRedTriangle = m4.multiply(tRotation, tModelRedTriangle1);\n\n // projection transformation\n let tProjection = m4.perspective(Math.PI/3,1,10,1000);\n\n // sets up all transformations together\n let tMVPCube = m4.multiply(m4.multiply(tModelCube,tCamera),tProjection);\n let tMVPSilverTriangle = m4.multiply(m4.multiply(tModelSilverTriangle,tCamera),tProjection);\n let tMVPGreenTriangle = m4.multiply(m4.multiply(tModelGreenTriangle,tCamera),tProjection);\n let tMVPBlueTriangle = m4.multiply(m4.multiply(tModelBlueTriangle,tCamera),tProjection);\n let tMVPRedTriangle = m4.multiply(m4.multiply(tModelRedTriangle,tCamera),tProjection);\n\n // clears the screen and performs z-buffering\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // sets up the uniform matrix and attributes for Cube\n gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVPCube);\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferCube);\n gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBufferCube.itemSize,\n gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferCube);\n gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBufferCube.itemSize,\n gl.FLOAT,false, 0, 0);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferCube);\n // draws Cube\n gl.drawElements(gl.TRIANGLES, triangleIndicesCube.length, gl.UNSIGNED_BYTE, 0);\n\n // sets up the uniform matrix and attributes for silver triangle\n gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVPSilverTriangle);\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferSilverTriangle);\n gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBufferSilverTriangle.itemSize,\n gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferSilverTriangle);\n gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBufferSilverTriangle.itemSize,\n gl.FLOAT,false, 0, 0);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferSilverTriangle);\n // draws silver triangle\n gl.drawElements(gl.TRIANGLES, triangleIndicesSilverTriangle.length, gl.UNSIGNED_BYTE, 0);\n\n // sets up the uniform matrix and attributes for green triangle\n gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVPGreenTriangle);\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferGreenTriangle);\n gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBufferGreenTriangle.itemSize,\n gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferGreenTriangle);\n gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBufferGreenTriangle.itemSize,\n gl.FLOAT,false, 0, 0);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferGreenTriangle);\n // draws silver triangle\n gl.drawElements(gl.TRIANGLES, triangleIndicesGreenTriangle.length, gl.UNSIGNED_BYTE, 0);\n\n // sets up the uniform matrix and attributes for blue triangle\n gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVPBlueTriangle);\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferBlueTriangle);\n gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBufferBlueTriangle.itemSize,\n gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferBlueTriangle);\n gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBufferBlueTriangle.itemSize,\n gl.FLOAT,false, 0, 0);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferBlueTriangle);\n // draws blue triangle\n gl.drawElements(gl.TRIANGLES, triangleIndicesBlueTriangle.length, gl.UNSIGNED_BYTE, 0);\n\n // sets up the uniform matrix and attributes for red triangle\n gl.uniformMatrix4fv(shaderProgram.MVPmatrix,false,tMVPRedTriangle);\n gl.bindBuffer(gl.ARRAY_BUFFER, trianglePosBufferRedTriangle);\n gl.vertexAttribPointer(shaderProgram.PositionAttribute, trianglePosBufferRedTriangle.itemSize,\n gl.FLOAT, false, 0, 0);\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBufferRedTriangle);\n gl.vertexAttribPointer(shaderProgram.ColorAttribute, colorBufferRedTriangle.itemSize,\n gl.FLOAT,false, 0, 0);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBufferRedTriangle);\n // draws red triangle\n gl.drawElements(gl.TRIANGLES, triangleIndicesRedTriangle.length, gl.UNSIGNED_BYTE, 0);\n }\n slider.addEventListener(\"input\",draw);\n slider1.addEventListener(\"input\",draw);\n slider2.addEventListener(\"input\",draw);\n draw();\n}", "function startup() {\n canvas = document.getElementById(\"myGLCanvas\");\n gl = createGLContext(canvas);\n //setupShaders(\"shader-vs\",\"shader-fs\");\n //setPhongShader();\n setGouraudShader();\n setupBuffers();\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n document.onkeydown = handleKeyDown;\n document.onkeyup = handleKeyUp;\n tick();\n}", "function gl_init(gl, vertexShader, fragmentShader) {\n\n // Create and link the gl program, using the application's vertex and fragment shaders.\n\n var program = gl.createProgram();\n addshader(gl, program, gl.VERTEX_SHADER , vertexShader );\n addshader(gl, program, gl.FRAGMENT_SHADER, fragmentShader);\n gl.linkProgram(program);\n if (! gl.getProgramParameter(program, gl.LINK_STATUS))\n console.log(\"Could not link the shader program!\");\n gl.useProgram(program);\n\n // Create a square as a strip of two triangles.\n\n gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ -1,1,0, 1,1,0, -1,-1,0, 1,-1,0 ]), gl.STATIC_DRAW);\n\n // Assign attribute aPosition to each of the square's vertices.\n\n gl.aPosition = gl.getAttribLocation(program, \"aPosition\");\n gl.enableVertexAttribArray(gl.aPosition);\n gl.vertexAttribPointer(gl.aPosition, 3, gl.FLOAT, false, 0, 0);\n\n // Remember the address within the fragment shader of each of my uniform variables.\n\n gl.uTime = gl.getUniformLocation(program, \"uTime\" );\n gl.uCursor = gl.getUniformLocation(program, \"uCursor\");\n}", "function startup() {\n canvas = document.getElementById(\"myGLCanvas\");\n gl = createGLContext(canvas);\n setupShaders(); \n setupBuffers();\n gl.clearColor(1.0, 1.0, 1.0, 1.0);\n gl.enable(gl.DEPTH_TEST);\n tick();\n}", "function init() {\n const VERTEX_SHADER = `\n attribute vec3 aPosition;\n uniform mat4 uTransformMatrix;\n \n void main() {\n gl_Position = uTransformMatrix * vec4(aPosition, 1.);\n }\n `;\n\n const FRAGMENT_SHADER = `\n precision mediump float;\n uniform vec3 uColor;\n \n void main() {\n gl_FragColor.rgb = uColor;\n gl_FragColor.a = 1.0;\n }\n `;\n\n initShaders(gl, VERTEX_SHADER, FRAGMENT_SHADER);\n const coord = gl.getAttribLocation(gl.program, 'aPosition');\n setupBuffers(coord);\n\n uTransformMatrix = gl.getUniformLocation(gl.program, \"uTransformMatrix\");\n uColor = gl.getUniformLocation(gl.program, \"uColor\");\n\n gl.enable(gl.DEPTH_TEST);\n\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n}", "function init() {\n canvas = document.createElement('canvas');\n gl = canvas.getContext('webgl');\n ratio = window.devicePixelRatio || 1;\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.SRC_ALPHA, gl.ONE);\n\n update();\n createProgram();\n blankTexture = getBlankTexture();\n initQuad();\n\n document.body.appendChild(canvas);\n window.addEventListener('resize', update, false);\n initialized = true;\n }", "function initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n\talert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n\treturn null;\n }\n\n return shaderProgram;\n}", "function initShaderProgram(gl, vsSource, fsSource) {\n let vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n let fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n let shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n return null;\n }\n\n return shaderProgram;\n}", "function main(){\n var vertices = getVertices();\n var indices = getIndices();\n\n const vertSource = getVertSource();\n const toySource = getToySource();\n const lightSource = getLightSource();\n\n const canvas = document.getElementById('glCanvas');\n const gl = canvas.getContext(\"webgl2\");\n\n if(!gl){\n alert(\"Could not initialize WebGL2!\");\n return;\n }\n\n canvas.onmousedown = handleMouseDown;\n document.onmousemove = handleMouseMove;\n document.onmouseup = handleMouseUp;\n\n\n gl.viewport(0, 0, 885, 885);\n gl.clearColor(0.1, 0.1, 0.1, 1.0);\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.enable(gl.DEPTH_TEST);\n\n view = mat4.lookAt(view,\n cameraPosition, //pos\n cameraTarget, //target\n cameraUp //up\n );\n projection = mat4.perspective(projection,\n Math.PI / 4,\n 895 / 895,\n 1.0,\n 100.0\n );\n\n const spToy = initShaders(gl, vertSource, toySource);\n const spLight = initShaders(gl, vertSource, lightSource);\n var vertBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n\n vao[0] = gl.createVertexArray();\n vao[1] = gl.createVertexArray();\n gl.bindVertexArray(vao[0]);\n var offset = 0;\n var stride = 8 * FLOAT_SIZE; //Number of floats per vertex * sizeof(float)\n //Shader location 0\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, offset);\n offset = 3 * FLOAT_SIZE;\n //Shader location 1\n gl.enableVertexAttribArray(1);\n gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, offset);\n offset = 6 * FLOAT_SIZE;\n //Shader location 2\n gl.enableVertexAttribArray(2);\n gl.vertexAttribPointer(2, 2, gl.FLOAT, false, stride, offset);\n\n gl.bindVertexArray(vao[1]);\n gl.bindBuffer(gl.ARRAY_BUFFER, vertBuffer);\n\n gl.enableVertexAttribArray(0);\n gl.vertexAttribPointer(0, 3, gl.FLOAT, false, stride, 0);\n\n textureSpec = gl.createTexture();\n var imageSpec = document.getElementById(\"spec\");\n gl.bindTexture(gl.TEXTURE_2D, textureSpec);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imageSpec);\n gl.generateMipmap(gl.TEXTURE_2D);\n\n texture = gl.createTexture();\n var image = document.getElementById('texture');\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n gl.generateMipmap(gl.TEXTURE_2D);\n\n renderLoop(gl, spToy, spLight);\n}", "function initShaderProgram(gl, vsSource, fsSource) {\n\tconst vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n\tconst fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n\n\t// Create the shader program\n\tconst shaderProgram = gl.createProgram();\n\tgl.attachShader(shaderProgram, vertexShader);\n\tgl.attachShader(shaderProgram, fragmentShader);\n\tgl.linkProgram(shaderProgram);\n\n\n\t// If creating the shader program failed, alert\n\tif (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n\t\talert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));\n\t\treturn null;\n\t}\n\n\treturn shaderProgram;\n}", "initGL() {\n \"use strict\";\n this.ctx.shaderProgram = loadAndCompileShaders(\n this.gl,\n \"VertexShader.glsl\",\n \"FragmentShader.glsl\"\n );\n this.setUpAttributesAndUniforms();\n this.setUpShapes();\n\n // set the clear color here\n this.gl.clearColor(0.2, 0.2, 0.2, 1); //-> damit wird alles übermalen (erst wenn clear)\n\n // add more necessary commands here\n }", "function initShaderProgram(gl, vsSource, fsSource) {\n\tconst vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n\tconst fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n\tconst shaderProgram = gl.createProgram();\n\tgl.attachShader(shaderProgram, vertexShader);\n\tgl.attachShader(shaderProgram, fragmentShader);\n\tgl.linkProgram(shaderProgram);\n\n\tif (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n\t\talert(`Unable to initialize the shader program: ${gl.getProgramInfoLog(shaderProgram)}`);\n\t\treturn null;\n\t}\n\treturn shaderProgram;\n}", "function setupWebGL(canvasID, vertexShaderID, fragmentShaderID) {\n /* Get the WebGL context */\n gl = twgl.getWebGLContext(document.getElementById(canvasID));\n\n /* Initialize the WebGL environment */\n if (gl) {\n gl.clearColor(0, 0, 0, 1);\n\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n \n maximizeCanvas(gl);\n document.body.onresize = () => maximizeCanvas(gl);\n\n Promise.all([\n loadShader(vertexShaderID),\n loadShader(fragmentShaderID)\n ]).then(() => {\n /* Create the programs */\n programInfo = twgl.createProgramInfo(gl, [vertexShaderID, fragmentShaderID]);\n gl.useProgram(programInfo.program);\n\n /* Create the primitive */\n twgl.setDefaults({ attribPrefix: 'a_' });\n var arrays = primitives.createSphereVertices(500, 50, 50);\n createSphereTangents(arrays, 50, 50);\n sphere = twgl.createBufferInfoFromArrays(gl, arrays);\n\n colorMap = twgl.createTexture(gl, { src: './images/colormap.png', flipY: false });\n normalMap = twgl.createTexture(gl, { src: './images/normalmap.png', flipY: false });\n faceMap = twgl.createTexture(gl, { src: './images/me.png' });\n\n /* Initialize the mouse and keys */\n initMouseEvents();\n initKeyEvents();\n\n /* Clear the matrix stack */\n matrixstack.clear();\n\n /* Update the canvas content */\n window.requestAnimationFrame(render);\n });\n }\n}", "function start() {\n let canvas = document.getElementById(\"myCanvas\");\n gl = prepareWebGL(canvas);\n context.shaderProgram = gl.createProgram();\n\n loadShader(gl, context.shaderProgram)\n .finally(() => {\n prepareGlVariables();\n prepareClearColor();\n texture.object = loadTexture(gl, texture.imgSource);\n prepareScene();\n window.requestAnimationFrame(drawAnimated);\n })\n}", "function initializeWebGL() {\n\ttry {\n\t\tgl = canvas.getContext(\"webgl2\");\n\t} catch(e) {\n\t\tconsole.log(e);\n\t}\n\n\tif(gl) {\n\t\tprogram = compileAndLink(program,vs,fs);\n\t\tgl.useProgram(program);\n\n\t\t// Link mesh attributes to shader attributes and enable them\n\t\tprogram = linkMeshAttr(program,false);\n\n\t\t// Init world view and projection matrices\n\t\tgl.clearColor(0.0, 0.0, 0.0, 1.0);\n\t\tgl.viewport(0.0, 0.0, canvas.clientWidth, canvas.clientHeight);\n\t\taspectRatio = canvas.clientWidth/canvas.clientHeight;\n\n\t\t// Turn on depth testing\n\t\tgl.enable(gl.DEPTH_TEST);\n\t\tgl.enable(gl.CULL_FACE);\n\t} else {\n\t\talert(\"Error: WebGL not supported by your browser!\");\n\t}\n}" ]
[ "0.87163424", "0.8596219", "0.85760325", "0.84909165", "0.83908445", "0.83655006", "0.83300763", "0.8319474", "0.8305133", "0.82184213", "0.81231046", "0.8115499", "0.8115499", "0.8053723", "0.8030474", "0.7978208", "0.7969012", "0.7955394", "0.79364115", "0.79215693", "0.79097426", "0.7827785", "0.77949053", "0.77939844", "0.7778759", "0.77688104", "0.775256", "0.77476007", "0.7743121", "0.7740998", "0.770183", "0.76800245", "0.7649124", "0.7619283", "0.75925463", "0.7588893", "0.75624585", "0.75577635", "0.74867564", "0.74775577", "0.7465765", "0.7465765", "0.7461553", "0.7453152", "0.73741835", "0.73240936", "0.7313608", "0.7290579", "0.72860754", "0.72791165", "0.72487026", "0.72330964", "0.72068995", "0.7202484", "0.7186961", "0.71807796", "0.7167832", "0.71636033", "0.7148542", "0.7145217", "0.71393645", "0.7125033", "0.71212906", "0.7091357", "0.70825875", "0.7064978", "0.705221", "0.7050642", "0.7015539", "0.7005015", "0.69987285", "0.69782233", "0.6966018", "0.696122", "0.69532627", "0.69424504", "0.69118965", "0.69078916", "0.6902695", "0.68999094", "0.68750596", "0.68728375", "0.681179", "0.68068355", "0.6800833", "0.6792791", "0.6784965", "0.67815024", "0.6774745", "0.6767078", "0.6765801", "0.6760816", "0.6757578", "0.6756424", "0.67546505", "0.6754418", "0.6751981", "0.6749061", "0.6743801", "0.6737364" ]
0.7701683
31
setMatrixUniforms specify the matrix values of uniform variables
function left_foot_setMatrixUniforms() { //send the uniform matrices onto the shader (i.e. pMatrix->shaderProgram.pMatrixUniform etc.) left_foot_gl.uniformMatrix4fv(left_foot_shaderProgram.pMatrixUniform, false, left_foot_pMatrix); left_foot_gl.uniformMatrix4fv(left_foot_shaderProgram.mvMatrixUniform, false, left_foot_mvMatrix); var normalMatrix=mat3.create(); mat3.normalFromMat4(normalMatrix,left_foot_mvMatrix); //calculate a 3x3 normal matrix (transpose inverse) from a 4x4 matrix left_foot_gl.uniformMatrix3fv(left_foot_shaderProgram.nMatrixUniform,false,normalMatrix); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setMatrixUniforms() {\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function setMatrixUniforms() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n}", "function setMatrixUniforms() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n}", "function setMatrixUniforms() {\n\tgl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n\tgl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function setMatrixUniforms() {\r\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\r\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function setMatrixUniforms() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n }", "function setMatrixUniforms() {\r\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function setMatrixUniforms() {\n gl.useProgram(shaderProgram)\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix)\n mat3.fromMat4(nMatrix,mvMatrix)\n mat3.transpose(nMatrix,nMatrix)\n mat3.invert(nMatrix,nMatrix)\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix)\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix)\n gl.uniform1f(shaderProgram.ReflectToggle, Toggle)\n gl.uniformMatrix4fv(shaderProgram.normals,false, rot)\n}", "function setMatrixUniforms() {\n\tuploadModelViewMatrixToShader();\n\tuploadNormalMatrixToShader();\n\tuploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n\tuploadModelViewMatrixToShader();\n\tuploadNormalMatrixToShader();\n\tuploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n uploadModelViewMatrixToShader();\n uploadNormalMatrixToShader();\n uploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n uploadModelViewMatrixToShader();\n uploadNormalMatrixToShader();\n uploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n uploadModelViewMatrixToShader();\n uploadNormalMatrixToShader();\n uploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n uploadModelViewMatrixToShader();\n uploadNormalMatrixToShader();\n uploadProjectionMatrixToShader();\n}", "function setMatrixUniforms() {\n //send the uniform matrices onto the shader (i.e. pMatrix->shaderProgram.pMatrixUniform etc.)\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix); \n var normalMatrix=mat3.create();\n mat3.normalFromMat4(normalMatrix,mvMatrix); //calculate a 3x3 normal matrix (transpose inverse) from a 4x4 matrix \n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform,false,normalMatrix); }", "function setMatrixUniforms() {\r\n uploadModelViewMatrixToShader();\r\n uploadNormalMatrixToShader();\r\n uploadProjectionMatrixToShader();\r\n}", "function setMatrixUniforms() {\r\n uploadModelViewMatrixToShader();\r\n uploadNormalMatrixToShader();\r\n uploadProjectionMatrixToShader();\r\n}", "function setMatrixUniforms() {\r\n uploadModelViewMatrixToShader();\r\n uploadNormalMatrixToShader();\r\n uploadProjectionMatrixToShader();\r\n}", "function setMatrixUniforms() {\n uploadModelViewMatrixToShader();\n uploadProjectionMatrixToShader();\n \n}", "function setMatrixUniforms(mvMatrix, pMatrix, normalMatrix)\n{\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n mat3.normalFromMat4(normalMatrix, mvMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, normalMatrix);\n}", "function setMatrixUniforms( )\n{\n\n // Pass the vertex shader the projection matrix and the model-view matrix.\n\n gl.uniformMatrix4fv( shaderProgram.pMatrixUniform, false, pMatrix );\n gl.uniformMatrix4fv( shaderProgram.mvMatrixUniform, false, mvMatrix );\n\n // Pass the vertex normal matrix to the shader so it can compute the lighting calculations.\n\n var normalMatrix = mat3.create( );\n mat3.normalFromMat4( normalMatrix, mvMatrix );\n gl.uniformMatrix3fv( shaderProgram.nMatrixUniform, false, normalMatrix );\n\n}", "function setMatrixUniforms(program){\r\n\tctx.uniformMatrix4fv(program.uPMatrix, false, pMatrix);\r\n\tctx.uniformMatrix4fv(program.uMVMatrix, false, mvMatrix);\r\n}", "function _setMatrixUniforms(pMatrix, mvMatrix) {\r\n\t\t_gl.uniformMatrix4fv(_shaderProgram.pMatrixUniform, false, pMatrix);\r\n\t\t_gl.uniformMatrix4fv(_shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n\r\n\t\t// TODO: Lighting Shader Only\r\n\t\tvar normalMatrix = mat3.create();\r\n\t\tmat4.toInverseMat3(mvMatrix, normalMatrix);\r\n\t\tmat3.transpose(normalMatrix);\r\n\t\t_gl.uniformMatrix3fv(_shaderProgram.nMatrixUniform, false, normalMatrix);\r\n\t}", "function setMatrixUniforms() {\n uploadMVMatrix();\n uploadPMatrix();\n uploadNMatrix();\n}", "setMatrixUniforms() {\n this.calculateNormal();\n this.gl.uniformMatrix4fv(this.program.uModelViewMatrix, false, this.modelViewMatrix);\n this.gl.uniformMatrix4fv(this.program.uProjectionMatrix, false, this.projectionMatrix);\n this.gl.uniformMatrix4fv(this.program.uNormalMatrix, false, this.normalMatrix);\n }", "setMatrixUniforms()\n\t{\n\t\t\tmat4.identity(mvMatrix);\n\t\t\tmat4.translate(mvMatrix, distCENTER);\n\t\t\tmat4.multiply(mvMatrix, rotMatrix);\n\n\t\t\t// mat4.identity(this.rMatrix);\n\t\t\t// mat4.identity(this.tMatrix);\n\t\t\t// mat4.translate(this.tMatrix, [0, 0.5, 0]);\n\t\t\t// mat4.rotate(this.rMatrix, this.rotObjY, [0, 0, 1]);\n\t\t\t// mat4.rotate(this.rMatrix, this.rotObjX, [1, 0, 0]);\n\n\t\t\tgl.uniformMatrix4fv(this.shader.rMatrixUniform, false, rotMatrix);\n\t\t\tgl.uniformMatrix4fv(this.shader.mvMatrixUniform, false, mvMatrix);\n\t\t\tgl.uniformMatrix4fv(this.shader.pMatrixUniform, false, pMatrix);\n\t\t\tgl.uniformMatrix4fv(this.shader.rObjMatrixUniform, false, this.rMatrix);\n\t\t\tgl.uniformMatrix4fv(this.shader.tObjMatrixUniform, false, this.tMatrix);\n\t}", "function setCubeMatrixUniforms(){\n gl.useProgram(SkyboxProgram)\n gl.uniformMatrix4fv(SkyboxProgram.cubeProjection, false, cubeP)\n gl.uniformMatrix4fv(SkyboxProgram.ModelVIew, false, Modelviewmatrix)\n gl.uniform1i( SkyboxProgram.skybox, 0)\n}", "function setModelViewMatrix(matrix)\r\n{\r\n gl.uniformMatrix4fv(shaderProgram.uModelViewMatrix, false, matrix);\r\n \r\n var normal_matrix = mat3.create();\r\n mat4.toInverseMat3(matrix, normal_matrix);\r\n mat3.transpose(normal_matrix);\r\n gl.uniformMatrix3fv(shaderProgram.uNormalMatrix, false, normal_matrix);\r\n}", "function loadUniformsMatrices ( uniforms, object ) {\r\n\r\n\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );\r\n\r\n\t\tif ( uniforms.normalMatrix ) {\r\n\r\n\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );\r\n\r\n\t\t}\r\n\r\n\t}", "function loadUniformsMatrices ( uniforms, object ) {\r\n\r\n\t\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object.modelViewMatrix.elements );\r\n\r\n\t\t\tif ( uniforms.normalMatrix ) {\r\n\r\n\t\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object.normalMatrix.elements );\r\n\r\n\t\t\t}\r\n\r\n\t\t}", "function loadUniformsMatrices ( uniforms, object ) {\r\n\r\n\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );\r\n\r\n\t\tif ( uniforms.normalMatrix ) {\r\n\r\n\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );\r\n\r\n\t\t}\r\n\r\n\t}", "function loadUniformsMatrices ( uniforms, object ) {\n\n\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );\n\n\t\tif ( uniforms.normalMatrix ) {\n\n\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );\n\n\t\t}\n\n\t}", "function loadUniformsMatrices ( uniforms, object ) {\n\n\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );\n\n\t\tif ( uniforms.normalMatrix ) {\n\n\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );\n\n\t\t}\n\n\t}", "function loadUniformsMatrices ( uniforms, object ) {\n\n\t\t_gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );\n\n\t\tif ( uniforms.normalMatrix ) {\n\n\t\t\t_gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );\n\n\t\t}\n\n\t}", "function loadUniformsMatrices ( uniforms, object ) {\n\n _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );\n\n if ( uniforms.normalMatrix ) {\n\n _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );\n\n }\n\n }", "function setUniforms(program, uniforms) {\n for(var name in uniforms) {\n var value = uniforms[name];\n var location = gl.getUniformLocation(program, name);\n if(location == null) continue;\n if(value instanceof THREE.Vector2) {\n //console.log(name + \": \" + \"[\" + value.x + \", \" + value.y + \"]\");\n gl.uniform2fv(location, new Float32Array([value.x, value.y]));\n } else if(value instanceof THREE.Vector3) {\n //console.log(name + \": \" + \"[\" + value.x + \", \" + value.y + \", \" + value.z + \"]\");\n gl.uniform3fv(location, new Float32Array([value.x, value.y, value.z]));\n } else if(value instanceof THREE.Color) {\n //console.log(name + \": \" + \"[\" + value.r + \", \" + value.g + \", \" + value.b + \"]\");\n gl.uniform3fv(location, new Float32Array([value.r, value.g, value.b]));\n } else if(value instanceof THREE.Matrix4) {\n //console.log(name + \": \" + value.toArray());\n gl.uniformMatrix4fv(location, false, new Float32Array(value.toArray()));\n } else {\n //console.log(name + \": \" + value);\n gl.uniform1f(location, value);\n }\n }\n}", "setMatrix(m) {\n\tthis.matrix = m;\n }", "function uploadNormalMatrixToShader() {\r\n mat3.fromMat4(nMatrix,mvMatrix);\r\n mat3.transpose(nMatrix,nMatrix);\r\n mat3.invert(nMatrix,nMatrix);\r\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\r\n}", "function uploadNormalMatrixToShader() {\r\n mat3.fromMat4(nMatrix,mvMatrix);\r\n mat3.transpose(nMatrix,nMatrix);\r\n mat3.invert(nMatrix,nMatrix);\r\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\r\n}", "function uploadNormalMatrixToShader() {\r\n mat3.fromMat4(nMatrix,mvMatrix);\r\n mat3.transpose(nMatrix,nMatrix);\r\n mat3.invert(nMatrix,nMatrix);\r\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\r\n}", "function uploadNormalMatrixToShader() {\n\tnMatrix = mvMatrix\n\tmat4.transpose(nMatrix,nMatrix);\n\tmat4.invert(nMatrix,nMatrix);\n\tgl.uniformMatrix4fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadNormalMatrixToShader() {\n mat3.fromMat4(nMatrix,mvMatrix);\n mat3.transpose(nMatrix,nMatrix);\n mat3.invert(nMatrix,nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadNormalMatrixToShader() {\n mat3.fromMat4(nMatrix,mvMatrix);\n mat3.transpose(nMatrix,nMatrix);\n mat3.invert(nMatrix,nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadNormalMatrixToShader() {\n mat3.fromMat4(nMatrix, mvMatrix);\n mat3.transpose(nMatrix, nMatrix);\n mat3.invert(nMatrix, nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadMVMatrix(){\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadNormalMatrixToShader() {\n glMatrix.mat3.fromMat4(nMatrix,mvMatrix);\n glMatrix.mat3.transpose(nMatrix,nMatrix);\n glMatrix.mat3.invert(nMatrix,nMatrix);\n gl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function setupVertexShaderMatrix2(){\n var viewMatrixUniform = gl.getUniformLocation(glProgram_helicoptero, \"uVMatrix\");\n var projMatrixUniform = gl.getUniformLocation(glProgram_helicoptero, \"uPMatrix\");\n var normalMatrixUniform = gl.getUniformLocation(glProgram_helicoptero, \"uNMatrix\");\n\n mat3.fromMat4(normalMatrix,matriz_model); // normalMatrix= (inversa(traspuesta(matrizModelado)));\n\n mat3.invert(normalMatrix, normalMatrix);\n mat3.transpose(normalMatrix,normalMatrix);\n\n \n gl.uniformMatrix4fv(viewMatrixUniform, false, viewMatrix);\n gl.uniformMatrix4fv(projMatrixUniform, false, projMatrix);\n //gl.uniformMatrix4fv(normalMatrixUniform, false, normalMatrix);\n gl.uniform3f(glProgram_helicoptero.directionalColorUniform, 1.0, 1.0, 0.8);\n var lightPosition = [0.0,300.0, 10000.0]; \n gl.uniform3fv(glProgram_helicoptero.lightingDirectionUniform, lightPosition); \n}", "_initMatrices() {\n // create our matrices, they will be set after\n const matrix = new Mat4();\n this._matrices = {\n world: {\n // world matrix (global transformation)\n matrix: matrix,\n },\n modelView: {\n // model view matrix (world matrix multiplied by camera view matrix)\n name: \"uMVMatrix\",\n matrix: matrix,\n location: this.gl.getUniformLocation(this._program.program, \"uMVMatrix\"),\n },\n projection: {\n // camera projection matrix\n name: \"uPMatrix\",\n matrix: matrix,\n location: this.gl.getUniformLocation(this._program.program, \"uPMatrix\"),\n },\n modelViewProjection: {\n // model view projection matrix (model view matrix multiplied by projection)\n matrix: matrix,\n }\n };\n }", "function setAllMatrices() {\n gl.uniformMatrix4fv(projectionMatrixLoc, false, flatten(projectionMatrix));\n setMV();\n\n}", "function setAllMatrices() {\n gl.uniformMatrix4fv(projectionMatrixLoc, false, flatten(projectionMatrix));\n setMV();\n\n}", "function setupVertexShaderMatrix(){ \n var viewMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uVMatrix\");\n var projMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uPMatrix\");\n var modMatrixUniform = gl.getUniformLocation(glProgram_terreno, \"uMMatrix\");\n\n var normalMatrix2 = mat3.create();\n mat3.fromMat4(normalMatrix2,matriz_model_terreno); // normalMatrix= (inversa(traspuesta(matrizModelado)));\n\n mat3.invert(normalMatrix2, normalMatrix2);\n mat3.transpose(normalMatrix2,normalMatrix2);\n\n //gl.uniformMatrix3fv(glProgram_terreno.nMatrixUniform, false, normalMatrix2);\n \n gl.uniformMatrix4fv(viewMatrixUniform, false, viewMatrix);\n gl.uniformMatrix4fv(projMatrixUniform, false, projMatrix);\n\n gl.uniform1f(glProgram_terreno.frameUniform, time/10.0 );\n gl.uniform3f(glProgram_terreno.ambientColorUniform, 0.0, 0.0, 0.0 );\n gl.uniform3f(glProgram_terreno.directionalColorUniform, 1.0, 1.0, 0.8);\n gl.uniform3f(glProgram_terreno.directionalColorUniform2, 0.2, 0.2, 0.2);\n gl.uniform1i(glProgram_terreno.useLightingUniform,true);\n\n var lightPosition = [0.0,0.0, -1.0]; \n var lightPosition2 = [0.0,300.0, 0.0]; \n gl.uniform3fv(glProgram_terreno.lightingDirectionUniform, lightPosition); \n gl.uniform3fv(glProgram_terreno.lightingDirectionUniform2, lightPosition2);\n \n}", "setUniform(name, value) {\n this.uniforms[name] = value;\n }", "setUniforms(uniformArray){\n let uniformLocationNames = this.vertexShader.getUniformLocationNames().concat(this.fragmentShader.getUniformLocationNames());\n\n let uniforms = [];\n uniforms.push(...uniformArray.getUniversalUniform());\n uniforms.push(...uniformArray.getPerObjectUniform());\n\n for(let name of uniformLocationNames){\n\n if(name.slice(0, name.length - 1) === \"u_sampler\"){\n gl.uniform1i(this.uniformLocations[name + \"Loc\"], name.substr(name.length - 1, 1));\n continue;\n }\n\n let index = this.findIndexUniform(name, uniforms);\n if(index === -1) throw Error(\"Property \" + name + \" not found in uniformArray object\");\n\n if(uniforms[index].getProperty().search(\"1\") != -1){\n gl[\"uniform\" + uniforms[index].getProperty()](this.uniformLocations[name + \"Loc\"], uniforms[index].getValue());\n\n } else if(uniforms[index].getProperty().search(\"2\") != -1) {\n\n let valueArray = uniforms[index].getValue();\n gl[\"uniform\" + uniforms[index].getProperty()](this.uniformLocations[name + \"Loc\"], valueArray[0], valueArray[1]);\n } else if(uniforms[index].getProperty().search(\"3fv\") != -1){\n gl[\"uniform\" + uniforms[index].getProperty()](this.uniformLocations[name + \"Loc\"], false, uniforms[index].getValue());\n\n } else if(uniforms[index].getProperty().search(\"3f\") != -1){\n let valueArray = uniforms[index].getValue();\n gl[\"uniform\" + uniforms[index].getProperty()](this.uniformLocations[name + \"Loc\"], valueArray[0], valueArray[1], valueArray[2]);\n\n } else if(uniforms[index].getProperty().search(\"4fv\") != -1){\n gl[\"uniform\" + uniforms[index].getProperty()](this.uniformLocations[name + \"Loc\"], false, uniforms[index].getValue());\n }\n }\n }", "function uploadModelViewMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function uploadNormalMatrixToShader() {\n\t\n\tmat3.fromMat4(nMatrix,mvMatrix);\n\n\t//the normal matrix is the inverse transpose of the mvMatrix.\n\tmat3.transpose(nMatrix,nMatrix);\n\tmat3.invert(nMatrix,nMatrix);\n\n\t//this line send the nMatrix to the shader\n\tgl.uniformMatrix3fv(shaderProgram.nMatrixUniform, false, nMatrix);\n}", "function uploadModelViewMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function uploadModelViewMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function setMV() {\n modelViewMatrix = mult(viewMatrix, modelMatrix);\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix));\n normalMatrix = inverseTranspose(modelViewMatrix);\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix));\n}", "function setMV() {\n modelViewMatrix = mult(viewMatrix, modelMatrix);\n gl.uniformMatrix4fv(modelViewMatrixLoc, false, flatten(modelViewMatrix));\n normalMatrix = inverseTranspose(modelViewMatrix);\n gl.uniformMatrix4fv(normalMatrixLoc, false, flatten(normalMatrix));\n}", "function uploadModelViewMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadModelViewMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadModelViewMatrixToShader() {\r\n\tgl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\r\n}", "function addUniforms(color)\n{\n uniforms.push({\n customColor: {type: \"v3\",\n value: color},\n customPointMatrix: {type: \"m4\",\n value: new THREE.Matrix4(1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0)},\n customNormalMatrix: {type: \"m4\",\n value: new THREE.Matrix4(1.0, 0.0, 0.0, 0.0,\n 0.0, 1.0, 0.0, 0.0,\n 0.0, 0.0, 1.0, 0.0,\n 0.0, 0.0, 0.0, 1.0)}\n });\n return uniforms.length - 1;\n}", "function setupUniforms(gl, uniforms, vars) {\n const canvas = document.getElementById(\"canvas\");\n gl.uniform2f(uniforms.resolution, canvas.width, canvas.height);\n gl.uniform1f(uniforms.time, vars.time);\n gl.uniform2f(uniforms.mouse, 0, 0);\n gl.uniform1i(uniforms.tex, 0);\n}", "function uploadModelViewMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadModelViewMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadModelViewMatrixToShader() {\n\tgl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function uploadModelViewMatrixToShader() {\n\tgl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);\n}", "function setLightPosition( u_position_loc, modelview, lightPosition ) {\n var transformedPosition = new Float32Array(4);\n vec4.transformMat4(transformedPosition, lightPosition, modelview);\n gl.uniform4fv(u_position_loc, transformedPosition);\n}", "_setPerspectiveMatrix() {\n // update our matrix uniform if we actually have updated its values\n if(this.camera._shouldUpdate) {\n this.renderer.useProgram(this._program);\n this.gl.uniformMatrix4fv(this._matrices.projection.location, false, this._matrices.projection.matrix.elements);\n }\n\n // reset camera shouldUpdate flag\n this.camera.cancelUpdate();\n }", "function setValue2fm( gl, v ) {\n\t\n\t\t\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\t\n\t\t}", "function uploadProjectionMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, \r\n false, pMatrix);\r\n}", "function uploadProjectionMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);\r\n}", "function setValue2fm( gl, v ) {\n\n\t \tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n\t }", "function uploadProjectionMatrixToShader() {\r\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,\r\n false, pMatrix);\r\n gl.uniformMatrix4fv(shaderProgram.inverseViewTransform, false, inverseViewTransform);\r\n}", "updateUniformValues() {\n this.scene.shaders[0].setUniformsValues({ uSampler: 0, uSampler2: 1 });\n this.scene.shaders[0].setUniformsValues({ normScale: this.heightScale });\n }", "function setValueM2a( gl, v ) {\n\n\t \tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n\t }", "function setValueM2a( gl, v ) {\n\t\n\t\t\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\t\n\t\t}", "function uploadProjectionMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, \n false, pMatrix);\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function setValueM2a( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );\n\n}", "function uploadProjectionMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform,\n false, pMatrix);\n}", "function uploadProjectionMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, \n false, pMatrix);\n}", "function uploadProjectionMatrixToShader() {\n gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, \n false, pMatrix);\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}", "function setValue2fm( gl, v ) {\n\n\tgl.uniformMatrix2fv( this.addr, false, v.elements || v );\n\n}" ]
[ "0.87147975", "0.8704717", "0.8704717", "0.8701584", "0.8658627", "0.8636551", "0.86213815", "0.8498286", "0.8396562", "0.8396562", "0.83267385", "0.83267385", "0.83267385", "0.83267385", "0.82997894", "0.82565206", "0.82565206", "0.82565206", "0.8233648", "0.8200989", "0.81977016", "0.8182373", "0.8169835", "0.8157804", "0.80558217", "0.7988078", "0.6815986", "0.6730454", "0.6656423", "0.664636", "0.662161", "0.66055524", "0.66055524", "0.66055524", "0.6590893", "0.6521173", "0.64120317", "0.63435525", "0.63265467", "0.63265467", "0.6310869", "0.62787914", "0.6278561", "0.6269391", "0.6253748", "0.623351", "0.61965626", "0.61866766", "0.6176792", "0.6176792", "0.6157485", "0.6118195", "0.61175823", "0.6106995", "0.61054695", "0.6076252", "0.6076252", "0.6064861", "0.6064861", "0.6058892", "0.6058892", "0.60508597", "0.60491246", "0.60487777", "0.6036537", "0.6036537", "0.60009146", "0.60009146", "0.59625924", "0.59110284", "0.59085995", "0.58902144", "0.5884247", "0.5881495", "0.58753324", "0.5852889", "0.58497685", "0.5830058", "0.5827638", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5823229", "0.5821099", "0.58196586", "0.58196586", "0.58140093", "0.58140093", "0.58140093", "0.58140093", "0.58140093", "0.58140093" ]
0.74250907
26
Adds multiple data sources and layers to the map
function loadMap() { //Change the cursor map.getCanvas().style.cursor = 'pointer'; //NOTE Draw order is important, largest layers (covers most area) are added first, followed by small layers //Add raster data and layers rasterLayerArray.forEach(function(layer) { map.addSource(layer[0], { "type": "raster", "tiles": layer[1] }); map.addLayer({ "id": layer[2], "type": "raster", "source": layer[0], 'layout': { 'visibility': 'none' } }); }); //Add polygon data and layers polyLayerArray.forEach(function(layer) { map.addSource(layer[0], { "type": "vector", "url": layer[1] }); map.addLayer({ "id": layer[2], "type": "fill", "source": layer[0], "source-layer": layer[3], "paint": layer[4], 'layout': { 'visibility': 'none' } }); }); map.setLayoutProperty('wildness', 'visibility', 'visible'); //Add wildness vector data source and layer for (i = 0; i < polyArray.length; i++) { map.addSource("vector-data"+i, { "type": "vector", "url": polyArray[i] }); //fill-color => stops sets a gradient map.addLayer({ "id": "vector" + i, "type": "fill", "source": "vector-data" + i, "source-layer": polySource[i], "minzoom": 6, "maxzoom": 22, "paint": wildPolyPaint }); } //Add polygon/line data and layers for (i=0; i<lineLayerArray.length; i++) { map.addSource(lineLayerArray[i][0], { "type": "vector", "url": lineLayerArray[i][1] }) map.addLayer({ "id": lineLayerArray[i][2], "type": "line", "source": lineLayerArray[i][0], "source-layer": lineLayerArray[i][4], "paint": { 'line-color': lineLayerArray[i][5], 'line-width': 2 } }); map.addLayer({ "id": lineLayerArray[i][3], "type": "fill", "source": lineLayerArray[i][0], "source-layer": lineLayerArray[i][4], "paint": { 'fill-color': lineLayerArray[i][5], 'fill-opacity': .3 } }); map.setLayoutProperty(lineLayerArray[i][2], 'visibility','none'); map.setLayoutProperty(lineLayerArray[i][3], 'visibility','none'); map.moveLayer(lineLayerArray[i][2]); map.moveLayer(lineLayerArray[i][3]); } //Add States data set map.addSource('states', { "type": "vector", "url": "mapbox://wildthingapp.2v1una7q" }); //Add States outline layer, omitting non-state territories map.addLayer({ "id": "states-layer", "type": "line", "source": "states", "source-layer": "US_State_Borders-4axtaj", "filter": ["!in","NAME","Puerto Rico", "Guam","American Samoa", "Commonwealth of the Northern Mariana Islands","United States Virgin Islands"] }); map.setLayerZoomRange('wildness', 0, 7); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function addMapSources() {\n\tmap.addSource('coastalCounties', {\n\t\t'type': 'geojson',\n\t\t'data': 'data/counties.geojson'\n\t});\n\t\n\tmap.addSource('single-point', {\n\t\t'type': 'geojson',\n\t\t'data': {\n\t\t\t'type': 'FeatureCollection',\n\t\t\t'features': []\n\t\t}\n\t});\n}", "addMapLayers() {\r\n // console.log('method: addMapLayers');\r\n let layers = this.map.getStyle().layers;\r\n // Find the index of the first symbol layer in the map style\r\n let firstSymbolId;\r\n for (let i = 0; i < layers.length; i++) {\r\n if (layers[i].type === 'symbol') {\r\n firstSymbolId = layers[i].id;\r\n break;\r\n }\r\n }\r\n this.options.mapConfig.layers.forEach((layer, index) => {\r\n\r\n // Add map source\r\n this.map.addSource(layer.source.id, {\r\n type: layer.source.type,\r\n data: layer.source.data\r\n });\r\n \r\n\r\n // Add layers to map\r\n this.map.addLayer({\r\n \"id\": layer.id,\r\n \"type\": \"fill\",\r\n \"source\": layer.source.id,\r\n \"paint\": {\r\n \"fill-color\": this.paintFill(layer.properties[0]),\r\n \"fill-opacity\": 0.8,\r\n \"fill-outline-color\": \"#000\"\r\n },\r\n 'layout': {\r\n 'visibility': 'none'\r\n }\r\n }, firstSymbolId);\r\n\r\n\r\n // check if touch device. if it's not a touch device, add mouse events\r\n if (!checkDevice.isTouch()) {\r\n this.initMouseEvents(layer);\r\n } // checkDevice.isTouch()\r\n\r\n\r\n // Store all the custom layers\r\n this.customLayers.push(layer.id);\r\n });\r\n }", "function LoadGEOJsonSources() {\n map.addSource('Scotland-Foto', {\n \"type\": \"geojson\",\n \"data\": \"https://daanvr.github.io/Schotland/geojson/Scotrip-FotoDataFile-RichOnly-Live.geojson\"\n });\n map.addSource('Scotland-Routes', {\n \"type\": \"geojson\",\n \"data\": \"https://daanvr.github.io/Schotland/geojson/Routes.geojson\"\n });\n\n var data = JSON.parse('{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[-5.096936,57.149319]},\"properties\":{\"FileName\":\"IMG_8571\",\"type\":\"Foto\",\"FileTypeExtension\":\"jpg\",\"SourceFile\":\"/Users/daan/Downloads/Schotlandexpiriment/IMG_8571.JPG\",\"CreateDate\":\"2018-04-13\",\"CreateTime\":\"15:15:34\",\"Make\":\"Apple\",\"Model\":\"iPhoneSE\",\"ImageSize\":\"16382x3914\",\"Duration\":\"\",\"Altitude\":\"276\",\"URL\":\"https://farm1.staticflickr.com/823/26804084787_f45be76bc3_o.jpg\",\"URLsmall\":\"https://farm1.staticflickr.com/823/26804084787_939dd60ebc.jpg\"}}]}');\n map.addSource('SelectedMapLocationSource', {\n type: \"geojson\",\n data: data,\n });\n\n AddMapIcon(); // add img to be used as icon for layer\n}", "function addMapLayer(geodata, layername) {\r\n map.addSource(layername, {\r\n 'type': 'geojson',\r\n 'data': geodata\r\n });\r\n map.addLayer({\r\n 'id': layername,\r\n 'type': 'line',\r\n 'source': layername,\r\n 'layout': {},\r\n 'paint': {\r\n 'line-width': 2,\r\n 'line-color': '#088',\r\n 'line-opacity': 0.8\r\n }\r\n });\r\n}", "function addSourceLineAndLayer(name) {\n map.addSource(name, {\n \"type\": \"geojson\",\n \"data\": {\n \"type\": \"Feature\",\n \"properties\": {},\n \"geometry\": {\n \"type\": \"Polygon\",\n \"coordinates\": [\n [\n []\n ]\n ]\n }\n }\n });\n map.addLayer({\n \"id\": name,\n \"source\": name,\n \"type\": \"fill\",\n \"layout\": {},\n \"paint\": {\n 'fill-color': '#088',\n 'fill-opacity': 0.7\n }\n });\n }", "function drawAllBuses(){\n map.on(\"load\", function(){\n console.log(\"adding buses\");\n\n console.log(cta);\n map.addSource(\"Bus Routes\", {\n \"type\":\"geojson\",\n \"data\":cta});\n\n console.log(\"layer\");\n\n map.addLayer({\n \"id\": \"Bus Routes\",\n \"type\": \"line\",\n \"source\": \"Bus Routes\",\n \"layout\": {\n \"line-join\": \"round\",\n \"line-cap\": \"butt\"\n },\n \"paint\": {\n \"line-color\": \"#31a354\",\n \"line-width\": 4,\n \"line-opacity\": 0.4\n }\n });\n });\n}", "function addSourcePointAndLayer(name) {\n map.addSource(name, {\n \"type\": \"geojson\",\n \"data\": {\n \"type\": \"Point\",\n \"coordinates\": []\n }\n });\n map.addLayer({\n \"id\": name,\n \"source\": name,\n \"type\": \"circle\",\n \"paint\": {\n \"circle-radius\": 5,\n \"circle-stroke-color\": \"#A93E71\",\n \"circle-stroke-width\": 1,\n \"circle-opacity\": 0\n }\n });\n }", "function addLayersOnMap(){\n\n var layers = map.getStyle().layers;\n // Find the index of the first symbol layer in the map style\n var firstSymbolId;\n for (var i = 0; i < layers.length; i++) {\n if (layers[i].type === 'symbol') {\n firstSymbolId = layers[i].id;\n console.log(firstSymbolId);\n break;\n }\n }\n\n // 3d extruded buildings\n // apartments from json\n map.addLayer({\n 'id': 'extrusion',\n 'type': 'fill-extrusion',\n \"source\": {\n \"type\": \"geojson\",\n \"data\": \"https://denyskononenko.github.io/maprebuild/buildigs_appartments.geojson\"\n },\n 'paint': {\n 'fill-extrusion-color': '#696969',\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 13,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 13,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': 1.0\n }\n }, firstSymbolId);\n\n // all buildings excepts hospitals and apartments\n map.addLayer({\n 'id': '3d-buildings',\n 'source': 'composite',\n 'source-layer': 'building',\n 'filter': ['all', ['==', 'extrude', 'true'], ['!=', 'type', 'hospital'], ['!=', 'type' ,'apartments']],\n 'type': 'fill-extrusion',\n 'minzoom': 15,\n 'paint': {\n 'fill-extrusion-color': '#dedede',\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': .4\n }\n }, firstSymbolId);\n\n // hospitals\n map.addLayer({\n 'id': '3d-buildings-hospitals',\n 'source': 'composite',\n 'source-layer': 'building',\n 'filter': ['all', ['==', 'extrude', 'true'], ['==', 'type', 'hospital']],\n 'type': 'fill-extrusion',\n 'minzoom': 15,\n 'paint': {\n 'fill-extrusion-color': '#A52A2A',\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': .2\n }\n }, firstSymbolId);\n\n // universities\n map.addLayer({\n 'id': '3d-buildings-university',\n 'source': 'composite',\n 'source-layer': 'building',\n 'filter': ['all', ['==', 'extrude', 'true'], ['==', 'type', 'university']],\n 'type': 'fill-extrusion',\n 'minzoom': 15,\n 'paint': {\n 'fill-extrusion-color': '#e6dabc',\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': .3\n }\n }, firstSymbolId);\n\n // schools\n map.addLayer({\n 'id': '3d-buildings-school',\n 'source': 'composite',\n 'source-layer': 'building',\n 'filter': ['all', ['==', 'extrude', 'true'], ['==', 'type', 'school']],\n 'type': 'fill-extrusion',\n 'minzoom': 15,\n 'paint': {\n 'fill-extrusion-color': '#e6dabc',\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': .3\n }\n }, firstSymbolId);\n\n // kindergarten\n map.addLayer({\n 'id': '3d-buildings-kindergarten',\n 'source': 'composite',\n 'source-layer': 'building',\n 'filter': ['all', ['==', 'extrude', 'true'], ['==', 'type', 'kindergarten']],\n 'type': 'fill-extrusion',\n 'minzoom': 15,\n 'paint': {\n 'fill-extrusion-color': '#e6dabc',\n // use an 'interpolate' expression to add a smooth transition effect to the\n // buildings as the user zooms in\n 'fill-extrusion-height': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"height\"]\n ],\n 'fill-extrusion-base': [\n \"interpolate\", [\"linear\"], [\"zoom\"],\n 15, 0,\n 15.05, [\"get\", \"min_height\"]\n ],\n 'fill-extrusion-opacity': .3\n }\n }, firstSymbolId);\n\n}", "function addSites() {\n require([\n\t\t\t\"esri/map\",\n\t\t\t\"esri/geometry/Point\",\n\t\t\t\"esri/symbols/SimpleMarkerSymbol\",\n\t\t\t\"esri/graphic\",\n\t\t\t\"esri/layers/GraphicsLayer\",\n\t\t\t\"esri/layers/ArcGISDynamicMapServiceLayer\",\n\t\t\t\"esri/layers/ImageParameters\",\n\t\t\t\"esri/layers/FeatureLayer\",\n\t\t\t\"dojo/domReady!\"\n ], function (Map, Point, SimpleMarkerSymbol, Graphic, GraphicsLayer, ArcGISDynamicMapServiceLayer, FeatureLayer, InfoTemplate) {\n if (map != null) {\n\t\t\t\tdropSitesLayer = new ArcGISDynamicMapServiceLayer(\"http://services4.geopowered.com/arcgis/rest/services/LATA/DropSites2015/MapServer\");\n //dropSitesLayer = new ArcGISDynamicMapServiceLayer(\"http://38.124.164.214:6080/arcgis/rest/services/DropZones/MapServer\");\n //dropSitesLayer = new ArcGISDynamicMapServiceLayer(\"http://38.124.164.214:6080/arcgis/rest/services/DropZones/FeatureServer\");\n /*\n\t\t\t\tvar infoTemplate = new InfoTemplate();\n\t\t\t\tinfoTemplate.setTitle(\"${Name}\");\n\t\t\t\tinfoTemplate.setContent(\"<b>Name: </b>${Name}\");\n\t\t\t\tdropSitesFeatureLayer = new esri.layers.FeatureLayer(\"http://38.124.164.214:6080/arcgis/rest/services/DropZones/FeatureServer/0\",{\n\t\t\t\t\tmode: esri.layers.FeatureLayer.MODE_ONDEMAND,\n\t\t\t\t\tinfoTemplate: infoTemplate,\n\t\t\t\t\toutFields: [\"*\"]\n\t\t\t\t});\n\t\t\t\t*/\n map.addLayer(dropSitesLayer);\n //map.addLayer(dropSitesFeatureLayer);\n }\n else {\n alert('no map');\n }\n });\n }", "function mapSource() {\n\t\n\tlet dataSelect = selectedSSP;\n\tconsole.log('New scenario: ' + selectedSSP.toLowerCase());\n\n\t// Fly to interesting location according to the selected model\n\tmap.flyTo({\n center: [85, 20],\n\t\tzoom: 4\n });\n\t\n\n\t// Add source\n\tmap.addSource(\"earthquakes\", {\n\t\ttype: \"geojson\",\n\t\tdata: \"data_\" + dataSelect.toLowerCase() + \".geojson\",\n\t\t//data: _data,\n\t\tcluster: false, // Set to true to sow clusters of points\n\t\tclusterMaxZoom: 6, // Max zoom to cluster points on\n\t\tclusterRadius: 10 // Radius of each cluster when clustering points (defaults to 50)\n\t});\n\n\tconsole.log('Data file ==> ' + \"data_\" + dataSelect.toLowerCase() + \".geojson\");\n}", "function addDataToMap(dataLayer, choice) {\n var url = 'https://eichnersara.cartodb.com/api/v2/sql?' + $.param({\n q: 'SELECT * FROM bk_oddlots ' + choice,\n format: 'GeoJSON'\n });\n $.getJSON(url)\n \n .done(function (data) {\n dataLayer.clearLayers();\n dataLayer.addData(data);\n console.log(data);\n });\n}", "function addLayer(layer) {\n map.add(layer);\n }", "add(map, {lng, lat}, layout = this.defaultLayout, paint = this.defaultPaint) {\n const srcId = 'mapbox-superset-src' + uniqId();\n\n map.addSource(srcId, {\n type: 'geojson',\n data: {\n type: 'FeatureCollection',\n features: [\n {\n type: 'Feature',\n geometry: {\n type: 'Point',\n coordinates: [lng, lat]\n },\n properties: {}\n }\n ]\n }\n });\n\n const layerId = 'mapbox-superset-layer' + uniqId();\n\n map.addLayer({\n id: layerId,\n type: 'symbol',\n source: srcId,\n layout: layout,\n paint: paint\n });\n\n return {\n layerId: layerId,\n srcId: srcId\n };\n }", "function addPointLayer() {\n var dummySource = map.getSource('taskai-src');\n if (typeof dummySource == 'undefined') {\n map.addSource('taskai-src', { 'type': 'geojson', 'data': urlTaskai });\n }\n map.addLayer({\n 'id': 'taskai',\n 'type': 'circle',\n 'source': 'taskai-src',\n 'paint': {\n 'circle-color': '#22dd22',\n 'circle-radius': {\n 'stops': [[11, 1], [16, 5]]\n },\n 'circle-stroke-color': '#222222',\n 'circle-stroke-width': {\n 'stops': [[11, 0], [16, 1]]\n }\n }\n });\n map.addLayer({\n 'id': 'taskai-label',\n 'type': 'symbol',\n 'source': 'taskai-src',\n 'layout': {\n 'text-field': '{pavadinimas}',\n 'text-font': ['Roboto Condensed Italic'],\n 'text-size': 12,\n 'text-variable-anchor': ['left','top','bottom','right'],\n 'text-radial-offset': 0.7,\n 'text-justify': 'auto',\n 'text-padding': 1\n },\n 'paint': {\n 'text-color': '#333333',\n 'text-halo-width': 1,\n 'text-halo-color': \"rgba(255, 255, 255, 0.9)\"\n }\n });\n if (!pointListeners) {\n map.on('click', 'taskai', paspaustasTaskas);\n map.on('mouseenter', 'taskai', mouseEnterPoints);\n map.on('mouseleave', 'taskai', mouseLeavePoints);\n pointListeners = true;\n }\n} // addPointLayer", "function bindDataLayerListeners(dataLayer) {\n dataLayer.addListener('addfeature', refreshGeoJsonFromData);\n dataLayer.addListener('removefeature', refreshGeoJsonFromData);\n dataLayer.addListener('setgeometry', refreshGeoJsonFromData);\n}", "function setup(map) {\n //$(\".feature-btn\").tooltip({ placement: 'right', title: 'Charts'});\n //map.addControl(new ChartControl());\n refresh();\n var layers = JSON.parse(localStorage.getItem(\"sk-load-charts\"));\n if (!layers) return;\n layers = jQuery.grep(layers, function(value) {\n addChartLayer(map, value.key, value.type, value.scale);\n });\n}", "addFromLayers(){\n let _from = this.props.fromVersion.key;\n //add the sources\n this.addSource({id: window.SRC_FROM_POLYGONS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _from + \"_polygons\" + window.TILES_SUFFIX]}});\n this.addSource({id: window.SRC_FROM_POINTS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _from + \"_points\" + window.TILES_SUFFIX]}});\n //add the layers\n this.addLayer({id: window.LYR_FROM_DELETED_POLYGON, sourceId: window.SRC_FROM_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(255,0,0, 0.2)\", \"fill-outline-color\": \"rgba(255,0,0,0.5)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_DELETED_POINT, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(255,0,0)\", \"circle-opacity\": 0.6}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_POLYGON});\n //geometry change in protected areas layers - from\n this.addLayer({id: window.LYR_FROM_GEOMETRY_POINT_TO_POLYGON, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(255,0,0)\", \"circle-opacity\": 0.5}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_GEOMETRY_POINT_COUNT_CHANGED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"line-color\": \"rgb(255,0,0)\", \"line-width\": 1, \"line-opacity\": 0.5, \"line-dasharray\": [3,3]}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n this.addLayer({id: window.LYR_FROM_GEOMETRY_SHIFTED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"line-color\": \"rgb(255,0,0)\", \"line-width\": 1, \"line-opacity\": 0.5, \"line-dasharray\": [3,3]}, filter:INITIAL_FILTER, beforeId: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON});\n //selection layers\n this.addLayer({id: window.LYR_FROM_SELECTED_POLYGON, sourceId: window.SRC_FROM_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POLYGON, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_FROM_SELECTED_LINE, sourceId: window.SRC_FROM_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _from + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_LINE, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_FROM_SELECTED_POINT, sourceId: window.SRC_FROM_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _from + \"_points\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POINT, filter:INITIAL_FILTER, beforeId: window.LYR_TO_SELECTED_POLYGON});\n }", "function startHere(){\n createStartMap();// step 1: Create a map on load with basemap and overlay map (with empty faultlinesLayer & EarhtquakesLayer ).\n addFaultlinesLayer();//step 2: Query data and add them to faultlinesLayer \n addEarthquakesLayer(); //step 3: Query data and add them to EarhtquakesLayer \n}", "function addLayers(){\n\n\t// Get renderer\n\tvar renderer = OpenLayers.Util.getParameters(window.location.href).renderer;\n\trenderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;\n\t// renderer = [\"Canvas\", \"SVG\", \"VML\"];\n\n\t// Create vector layer with a stylemap for vessels\n\tvesselLayer = new OpenLayers.Layer.Vector(\n\t\t\t\"Vessels\",\n\t\t\t{\n\t\t\t\tstyleMap: new OpenLayers.StyleMap({\n\t\t\t\t\t\"default\": {\n\t\t\t\t\t\texternalGraphic: \"${image}\",\n\t\t\t\t\t\tgraphicWidth: \"${imageWidth}\",\n\t\t\t\t\t\tgraphicHeight: \"${imageHeight}\",\n\t\t\t\t\t\tgraphicYOffset: \"${imageYOffset}\",\n\t\t\t\t\t\tgraphicXOffset: \"${imageXOffset}\",\n\t\t\t\t\t\trotation: \"${angle}\"\n\t\t\t\t\t},\n\t\t\t\t\t\"select\": {\n\t\t\t\t\t\tcursor: \"crosshair\",\n\t\t\t\t\t\texternalGraphic: \"${image}\"\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\trenderers: renderer\n\t\t\t}\n\t\t);\n\n\tmap.addLayer(vesselLayer);\n\t\n\t// Create vector layer with a stylemap for the selection image\n\tmarkerLayer = new OpenLayers.Layer.Vector(\n\t\t\t\"Markers\",\n\t\t\t{\n\t\t\t\tstyleMap: new OpenLayers.StyleMap({\n\t\t\t\t\t\"default\": {\n\t\t\t\t\t\texternalGraphic: \"${image}\",\n\t\t\t\t\t\tgraphicWidth: \"${imageWidth}\",\n\t\t\t\t\t\tgraphicHeight: \"${imageHeight}\",\n\t\t\t\t\t\tgraphicYOffset: \"${imageYOffset}\",\n\t\t\t\t\t\tgraphicXOffset: \"${imageXOffset}\",\n\t\t\t\t\t\trotation: \"${angle}\"\n\t\t\t\t\t},\n\t\t\t\t\t\"select\": {\n\t\t\t\t\t\tcursor: \"crosshair\",\n\t\t\t\t\t\texternalGraphic: \"${image}\"\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\trenderers: renderer\n\t\t\t}\n\t\t);\n\t\n\tmap.addLayer(markerLayer);\n\n\t// Create vector layer with a stylemap for the selection image\n\tselectionLayer = new OpenLayers.Layer.Vector(\n\t\t\t\"Selection\",\n\t\t\t{\n\t\t\t\tstyleMap: new OpenLayers.StyleMap({\n\t\t\t\t\t\"default\": {\n\t\t\t\t\t\texternalGraphic: \"${image}\",\n\t\t\t\t\t\tgraphicWidth: \"${imageWidth}\",\n\t\t\t\t\t\tgraphicHeight: \"${imageHeight}\",\n\t\t\t\t\t\tgraphicYOffset: \"${imageYOffset}\",\n\t\t\t\t\t\tgraphicXOffset: \"${imageXOffset}\",\n\t\t\t\t\t\trotation: \"${angle}\"\n\t\t\t\t\t},\n\t\t\t\t\t\"select\": {\n\t\t\t\t\t\tcursor: \"crosshair\",\n\t\t\t\t\t\texternalGraphic: \"${image}\"\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\trenderers: renderer\n\t\t\t}\n\t\t);\n\n\t// Create vector layer for past tracks\n\ttracksLayer = new OpenLayers.Layer.Vector(\"trackLayer\", {\n styleMap: new OpenLayers.StyleMap({'default':{\n strokeColor: pastTrackColor,\n strokeOpacity: pastTrackOpacity,\n strokeWidth: pastTrackWidth\n }})\n });\n\n\t// Create vector layer for time stamps\n\ttimeStampsLayer = new OpenLayers.Layer.Vector(\"timeStampsLayer\", {\n styleMap: new OpenLayers.StyleMap({'default':{\n label : \"${timeStamp}\",\n\t\t\tfontColor: timeStampColor,\n\t\t\tfontSize: timeStampFontSize,\n\t\t\tfontFamily: timeStampFontFamily,\n\t\t\tfontWeight: timeStampFontWeight,\n\t\t\tlabelAlign: \"${align}\",\n\t\t\tlabelXOffset: \"${xOffset}\",\n\t\t\tlabelYOffset: \"${yOffset}\",\n\t\t\tlabelOutlineColor: timeStamtOutlineColor,\n\t\t\tlabelOutlineWidth: 5,\n\t\t\tlabelOutline:1\n }})\n });\n\n\t// Create cluster layer\n\tclusterLayer = new OpenLayers.Layer.Vector( \"Clusters\", \n\t\t{\n\t\t styleMap: new OpenLayers.StyleMap({\n\t\t 'default':{\n\t\t fillColor: \"${fill}\",\n\t\t fillOpacity: clusterFillOpacity,\n\t\t strokeColor: clusterStrokeColor,\n\t\t strokeOpacity: clusterStrokeOpacity,\n\t\t strokeWidth: clusterStrokeWidth\n \t}\n })\n });\n\t\t\n\tmap.addLayer(clusterLayer);\n\n\t// Create cluster text layer\n\tclusterTextLayer = new OpenLayers.Layer.Vector(\"Cluster text\", \n\t\t{\n\t\t styleMap: new OpenLayers.StyleMap(\n\t\t {\n\t\t\t\t'default':\n\t\t\t\t{\n\t\t\t\t\t\tlabel : \"${count}\",\n\t\t\t\t\t\tfontColor: clusterFontColor,\n\t\t\t\t\t\tfontSize: \"${fontSize}\",\n\t\t\t\t\t\tfontWeight: clusterFontWeight,\n\t\t\t\t\t\tfontFamily: clusterFontFamily,\n\t\t\t\t\t\tlabelAlign: \"c\"\n\t\t\t\t}\n\t\t\t})\n \t});\n\n\tmap.addLayer(clusterTextLayer); \n\n\t// Create layer for individual vessels in cluster \n\tindieVesselLayer = new OpenLayers.Layer.Vector(\"Points\", \n\t\t{\n\t\t styleMap: new OpenLayers.StyleMap({\n\t\t \"default\": {\n pointRadius: indieVesselRadius,\n fillColor: indieVesselColor,\n strokeColor: indieVesselStrokeColor,\n strokeWidth: indieVesselStrokeWidth,\n graphicZIndex: 1\n \t},\n\t\t\t\"select\": {\n pointRadius: indieVesselRadius * 3,\n fillColor: indieVesselColor,\n strokeColor: indieVesselStrokeColor,\n strokeWidth: indieVesselStrokeWidth,\n graphicZIndex: 1\n \t}\n })\n });\n \n\t\n map.addLayer(indieVesselLayer); \n map.addLayer(selectionLayer);\n map.addLayer(tracksLayer); \n map.addControl(new OpenLayers.Control.DrawFeature(tracksLayer, OpenLayers.Handler.Path)); \n\tmap.addLayer(timeStampsLayer); \n\n\t// Add OpenStreetMap Layer\n\tvar osm = new OpenLayers.Layer.OSM(\n\t\t\"OSM\",\n\t\t\"//osm.e-navigation.net/${z}/${x}/${y}.png\",\n\t\t{\n\t\t\t'layers':'basic',\n\t\t\t'isBaseLayer': true\n\t\t} \n\t);\n\n\t// Add OpenStreetMap Layer\n\tmap.addLayer(osm);\n\t\n\t// Add KMS Layer\n\t//addKMSLayer();\n\n}", "function addMapLayers(layersArray) {\r\n var layers = {};\r\n $.each(layersArray, function(index, value) {\r\n if (value.wmsurl.indexOf(\"{x}\") != -1) {\r\n layers[value.name] = new L.TileLayer( value.wmsurl, value );\r\n }\r\n else {\r\n layers[value.name] = new L.TileLayer.WMS( value.wmsurl, value );\r\n }\r\n if ( value.isVisible ) map.addLayer(layers[value.name]);\r\n });\r\n return layers;\r\n}", "addToLayers(){\n try {\n let _to = this.props.toVersion.key;\n //add the sources\n let attribution = \"IUCN and UNEP-WCMC (\" + this.props.toVersion.year + \"), The World Database on Protected Areas (\" + this.props.toVersion.year + \") \" + this.props.toVersion.title + \", Cambridge, UK: UNEP-WCMC. Available at: <a href='http://www.protectedplanet.net'>www.protectedplanet.net</a>\";\n this.addSource({id: window.SRC_TO_POLYGONS, source: {type: \"vector\", attribution: attribution, tiles: [ window.TILES_PREFIX + \"wdpa_\" + _to + \"_polygons\" + window.TILES_SUFFIX]}});\n this.addSource({id: window.SRC_TO_POINTS, source: {type: \"vector\", tiles: [ window.TILES_PREFIX + \"wdpa_\" + _to + \"_points\" + window.TILES_SUFFIX]}});\n //no change protected areas layers\n this.addLayer({id: window.LYR_TO_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(99,148,69,0.2)\", \"fill-outline-color\": \"rgba(99,148,69,0.3)\"}, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(99,148,69)\", \"circle-opacity\": 0.6}, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //selection layers\n this.addLayer({id: window.LYR_TO_SELECTED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POLYGON, filter:INITIAL_FILTER});\n this.addLayer({id: window.LYR_TO_SELECTED_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_SELECTED_LINE, filter:INITIAL_FILTER});\n this.addLayer({id: window.LYR_TO_SELECTED_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: P_SELECTED_POINT, filter:INITIAL_FILTER});\n //add the change layers if needed\n if (this.props.fromVersion.id !== this.props.toVersion.id) this.addToChangeLayers();\n } catch (e) {\n console.log(e);\n }\n }", "function bindDataLayerListeners(dataLayer) {\n dataLayer.addListener('addfeature', refreshGeoJsonFromData);\n dataLayer.addListener('removefeature', refreshGeoJsonFromData);\n dataLayer.addListener('setgeometry', refreshGeoJsonFromData);\n dataLayer.addListener('click', selectFeature);\n}", "function loadMapShapes() {\n\n map.data.loadGeoJson('https://raw.githubusercontent.com/lotharJiang/Cluster-Sentiment-Analysis/master/Data%20Visualisation/newVicJson.json',{idPropertyName:'Suburb_Name'});\n\n google.maps.event.addListenerOnce(map.data,\"addfeature\",function(){\n google.maps.event.trigger(document.getElementById('Aurin-Variable'),'change');\n })\n\n map2.data.loadGeoJson('https://raw.githubusercontent.com/lotharJiang/Cluster-Sentiment-Analysis/master/Data%20Visualisation/newVicJson.json',{idPropertyName:'Suburb_Name'});\n\n google.maps.event.addListenerOnce(map2.data,\"addfeature\",function(){\n google.maps.event.trigger(document.getElementById('Aurin-Variable2'),'change');\n })\n}", "function createMapLayers(map) {\n \n var mapLayer1 = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.outdoors\",\n accessToken: apiKey\n });\n \n var mapLayer2 = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.light\",\n accessToken: apiKey\n });\n\n var mapLayer3 = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.dark\",\n accessToken: apiKey\n });\n\n var mapLayer4 = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.streets-satellite\",\n accessToken: apiKey\n });\n\n var mapLayer5 = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.streets\",\n accessToken: apiKey\n });\n\n return [mapLayer1, mapLayer2, mapLayer3, mapLayer4, mapLayer5];\n \n}", "function onLoad() {\n // Load map.\n OpenLayers.ProxyHost = '/proxy/';\n map = new OpenLayers.Map('map');\n map.addControl(new OpenLayers.Control.LayerSwitcher());\n\n var layer = new OpenLayers.Layer.WMS('OpenLayers WMS',\n 'http://labs.metacarta.com/wms/vmap0',\n {layers: 'basic'},\n {wrapDateLine: true});\n map.addLayer(layer);\n map.setCenter(new OpenLayers.LonLat(-145, 0), 3);\n\n // Add layer for the buoys.\n buoys = new OpenLayers.Layer.Markers('TAO array');\n map.addLayer(buoys);\n\n // Add buoys. Apparently, dapper always returns the data\n // in the order lon/lat/_id, independently of the projection.\n var url = baseUrl + \".dods?location.lon,location.lat,location._id\";\n jsdap.loadData(url, plotBuoys, '/proxy/');\n\n // Read variables in each location.\n jsdap.loadDataset(baseUrl, loadVariables, '/proxy/');\n}", "function initLayer() {\n addSourceLineAndLayer('line');\n addSourcePointAndLayer('tl_point');\n addSourcePointAndLayer('tr_point');\n addSourcePointAndLayer('bl_point');\n addSourcePointAndLayer('br_point');\n addSourcePointAndLayer('t_point');\n addSourcePointAndLayer('r_point');\n addSourcePointAndLayer('l_point');\n addSourcePointAndLayer('b_point');\n }", "function addPoints() {\n\t//for every station in the dataset, create a marker\n for(var i=0; i<dataTrento.length; i++) {\n var station=dataTrento[i];\n createMarker(station);\n }\n for(var i=0; i<dataPergine.length; i++) {\n var station=dataPergine[i];\n createMarker(station);\n }\n for(var i=0; i<dataRovereto.length; i++) {\n var station=dataRovereto[i];\n createMarker(station);\n }\n}", "function addTopoData(topoData) {\n topoLayer.addData(topoData);\n topoLayer.addTo(map0)\n topoLayer.eachLayer(handleLayer);\n }", "function handleNewData ( source, tileArrays, sourceKey ) {\n\t for ( var i = 0 ; i < tileArrays.length ; i++ ) {\n\t\tvar tileArray = tileArrays[ i ];\n\t\tvar tilePointer = loadBuffer( tileArray );\n\t\tvar start = source.getStart();\n\t\tvar end = source.getEnd();\n\t\tvar projection = source.getProjection();\n\t\tvar loadFunction = source.getLoadFunction();\n\t\tvar dataInfo = initSorceData( start, end, projection );\n\t\t\n\t\tloadGlBuffer( loadFunction, tilePointer, dataInfo, fBufferInfo );\n\n\t\tfSourceBuffers[ sourceKey ].push( dataInfo );\n\n\t\tif ( fMinY === undefined || fMinY > dataInfo.minY )\n\t\t fMinY = dataInfo.minY;\n\n\t\tif ( fMaxY === undefined || fMaxY < dataInfo.maxY )\n\t\t fMaxY = dataInfo.maxY;\n\t }\n\n\t fGl.bufferData(fGl.ARRAY_BUFFER, fBufferInfo.data, fGl.STATIC_DRAW);\n\n\t schudleDraw();\n\t}", "function makeSources(xyz) {\n // https://xyz.api.here.com/hub/spaces/{space}/tile/web/{z}_{x}_{y}\n return xyz.layers.reduce(function (tgSources, xyzLayer, index) {\n var spaceId = xyzLayer.geospace.id;\n var name = getXYZLayerName(xyzLayer, index);\n var access_token = xyz.rot;\n\n tgSources[name] = {\n type: 'GeoJSON',\n url: (\"https://xyz.api.here.com/hub/spaces/\" + spaceId + \"/tile/web/{z}_{x}_{y}\"),\n // url: `https://xyz.api.here.com/hub/spaces/${spaceId}/tile/quadkey/{q}`,\n url_params: {\n access_token: access_token,\n clip: true,\n clientId: 'viewer',\n },\n // max_zoom: 16, // using explicit zoom list below for now instead\n zooms: [0, 2, 4, 6, 8, 10, 12, 14, 16], // load every other zoom\n transform: 'global.add_feature_id' // TODO: remove this when Tangram 0.19 is released (temp solution for 0.18.x)\n };\n\n // add comma-delimited list of tags if available\n if (xyzLayer.meta && Array.isArray(xyzLayer.meta.spaceTags)) {\n tgSources[name].url_params.tags = xyzLayer.meta.spaceTags.join(',');\n }\n\n // add layer bounding box if available (sometimes `bbox` property is an empty array)\n // TODO: ignoring bounds for now, because bbox reported by Studio is sometimes incorrect\n // if (Array.isArray(xyzLayer.bbox) && xyzLayer.bbox.length === 4) {\n // tgSources[name].bounds = xyzLayer.bbox;\n // }\n\n return tgSources;\n }, {});\n }", "addLayer(details){\n //if the layer already exists then delete it\n if (this.map.getLayer(details.id)){\n this.map.removeLayer(details.id);\n } \n this.map.addLayer({\n 'id': details.id,\n 'type': details.type,\n 'source': details.sourceId,\n 'source-layer': details.sourceLayer,\n 'paint': details.paint\n }, (details.beforeId) ? details.beforeId : undefined);\n //set a filter if one is passed\n if (details.hasOwnProperty('filter')) this.map.setFilter(details.id, details.filter);\n if (this.props.view === 'country'){\n //set the visibility of the layer depending on the visible property of the status \n let status = this.props.statuses.filter(status => {\n return (status.layers.indexOf(details.id) !== -1);\n })[0];\n if (status) this.map.setLayoutProperty(details.id, \"visibility\", (status.visible) ? \"visible\" : \"none\" );\n }\n }", "function DisplayGEOJsonLayers(){\n map.addLayer({ \n //photos layer\n \"id\": \"photos\",\n \"type\": \"symbol\",\n \"source\": \"Scotland-Foto\",\n \"layout\": {\n \"icon-image\": \"CustomPhoto\",\n \"icon-size\": 1,\n \"icon-offset\": [0, -17],\n \"icon-padding\": 0,\n \"icon-allow-overlap\":true\n },\n \"paint\": {\n \"icon-opacity\": 1\n }\n }, 'country-label-lg'); // Place polygon under this labels.\n\n map.addLayer({ \n //selected rout section layer\n \"id\": \"routes-today\",\n \"type\": \"line\",\n \"source\": \"Scotland-Routes\",\n \"layout\": {\n },\n \"paint\": {\n \"line-color\": \"#4285F4\",\n \"line-width\": 6\n }\n }, 'housenum-label'); // Place polygon under this labels.\n\n map.addLayer({\n //rout layer\n \"id\": \"routes\",\n \"type\": \"line\",\n \"source\": \"Scotland-Routes\",\n \"layout\": {\n },\n \"paint\": {\n \"line-color\": \"rgba(120, 180, 244, 1)\",\n \"line-width\": 4\n }\n }, 'routes-today'); // Place polygon under this labels.\n\n map.addLayer({\n //layer used to create lins(borders) arround rout\n \"id\": \"routes-shadow\",\n \"type\": \"line\",\n \"source\": \"Scotland-Routes\",\n \"layout\": {\n },\n \"paint\": {\n \"line-color\": \"#4285F4\",\n \"line-width\": 6\n }\n }, 'routes'); // Place polygon under this labels.\n\n map.addLayer({\n //rout layer\n \"id\": \"walked\",\n \"type\": \"line\",\n \"source\": \"Scotland-Routes\",\n \"filter\": [\"==\", \"activities\", \"walking\"],\n \"layout\": {\n },\n \"paint\": {\n \"line-color\": \"rgba(80, 200, 50, 1)\",\n \"line-width\": 4\n }\n }, 'routes-today'); // Place polygon under this labels.\n\n map.addLayer({\n //layer used to create lins(borders) arround rout\n \"id\": \"walked-shadow\",\n \"type\": \"line\",\n \"source\": \"Scotland-Routes\",\n \"filter\": [\"==\", \"activities\", \"walking\"],\n \"layout\": {\n },\n \"paint\": {\n \"line-color\": \"#4285F4\",\n \"line-width\": 6\n }\n }, 'walked'); // Place polygon under this labels.\n\n map.addLayer({\n \"id\": \"SelectedMapLocationLayer\",\n \"type\": \"symbol\",\n \"source\": \"SelectedMapLocationSource\",\n \"layout\": {\n \"icon-image\": \"CustomPhotoSelected\",\n \"icon-size\": 1,\n \"icon-offset\": [0, -17],\n \"icon-padding\": 0,\n \"icon-allow-overlap\":true\n },\n \"paint\": {\n \"icon-opacity\": 1\n }\n }, 'country-label-lg');\n //ClickbleMapItemCursor(); //Now that the layers a loaded, have the mouse cursor change when hovering some of the layers\n NewSelectedMapLocation();\n\n}", "function addUSMap(usmap, args) {\n if (args == null) args = {};\n var numCanvas = \"county\" in usmap ? 2 : 1;\n if (\"pyramid\" in args && args.pyramid.length != numCanvas)\n throw new Error(\n \"Adding USMap: args.pyramid does not have matching number of canvases\"\n );\n\n // add to project\n this.usmaps.push(usmap);\n\n // rendering params\n var rpKey = \"usmap_\" + (this.usmaps.length - 1);\n var rpDict = {};\n rpDict[rpKey] = usmap.params;\n this.addRenderingParams(rpDict);\n\n // ================== state map canvas ===================\n var canvases = [];\n var stateMapCanvas;\n if (\"pyramid\" in args) stateMapCanvas = args.pyramid[0];\n else {\n stateMapCanvas = new Canvas(\n \"usmap\" + (this.usmaps.length - 1) + \"_\" + \"state\",\n usmap.stateMapWidth,\n usmap.stateMapHeight\n );\n this.addCanvas(stateMapCanvas);\n }\n if (\n stateMapCanvas.w != usmap.stateMapWidth ||\n stateMapCanvas.h != usmap.stateMapHeight\n )\n throw new Error(\"Adding USMap: state canvas sizes do not match\");\n\n // static legends layer\n var stateMapLegendLayer = new Layer(null, true);\n stateMapCanvas.addLayer(stateMapLegendLayer);\n stateMapLegendLayer.addRenderingFunc(\n usmap.getUSMapRenderer(\"stateMapLegendRendering\")\n );\n stateMapLegendLayer.setUSMapId(this.usmaps.length - 1 + \"_\" + 0);\n\n // state boundary layer\n var stateMapTransform = new Transform(\n `SELECT name, ${usmap.stateRateCol}, geomstr \n FROM ${usmap.stateTable}`,\n usmap.db,\n usmap.getUSMapTransformFunc(\"stateMapTransform\"),\n [\"bbox_x\", \"bbox_y\", \"name\", \"rate\", \"geomstr\"],\n true\n );\n var stateBoundaryLayer = new Layer(stateMapTransform, false);\n stateMapCanvas.addLayer(stateBoundaryLayer);\n stateBoundaryLayer.addPlacement({\n centroid_x: \"col:bbox_x\",\n centroid_y: \"col:bbox_y\",\n width: `con:${usmap.stateMapWidth / usmap.zoomFactor}`,\n height: `con:${usmap.stateMapWidth / usmap.zoomFactor}`\n });\n stateBoundaryLayer.addRenderingFunc(\n usmap.getUSMapRenderer(\"stateMapRendering\")\n );\n stateBoundaryLayer.addTooltip(\n [\"name\", \"rate\"],\n [\"State\", usmap.tooltipAlias]\n );\n stateBoundaryLayer.setUSMapId(this.usmaps.length - 1 + \"_\" + 0);\n\n // add to canvases (return)\n canvases.push(stateMapCanvas);\n\n // ========== Views ===============\n if (!(\"view\" in args)) {\n var view = new View(\n \"usmap\" + (this.usmaps.length - 1),\n usmap.stateMapWidth,\n usmap.stateMapHeight\n );\n this.addView(view);\n this.setInitialStates(view, stateMapCanvas, 0, 0);\n } else if (!(args.view instanceof View)) {\n throw new Error(\"Adding USMap: view must be a View object\");\n }\n\n // ================== county map canvas ===================\n if (\"countyTable\" in usmap) {\n var countyMapCanvas;\n if (\"pyramid\" in args) countyMapCanvas = args.pyramid[1];\n else {\n countyMapCanvas = new Canvas(\n \"usmap\" + (this.usmaps.length - 1) + \"_\" + \"county\",\n usmap.stateMapWidth * usmap.zoomFactor,\n usmap.stateMapHeight * usmap.zoomFactor\n );\n this.addCanvas(countyMapCanvas);\n }\n if (\n countyMapCanvas.w != usmap.stateMapWidth * usmap.zoomFactor ||\n countyMapCanvas.h != usmap.stateMapHeight * usmap.zoomFactor\n )\n throw new Error(\"Adding USMap: county canvas sizes do not match\");\n\n // static legends layer\n var countyMapLegendLayer = new Layer(null, true);\n countyMapCanvas.addLayer(countyMapLegendLayer);\n countyMapLegendLayer.addRenderingFunc(\n usmap.getUSMapRenderer(\"countyMapLegendRendering\")\n );\n countyMapLegendLayer.setUSMapId(this.usmaps.length - 1 + \"_\" + 1);\n\n // thick state boundary layer\n var countyMapStateBoundaryTransform = new Transform(\n `SELECT geomstr FROM ${usmap.stateTable}`,\n usmap.db,\n usmap.getUSMapTransformFunc(\"countyMapStateBoundaryTransform\"),\n [\"bbox_x\", \"bbox_y\", \"bbox_w\", \"bbox_h\", \"geomstr\"],\n true\n );\n var countyMapStateBoundaryLayer = new Layer(\n countyMapStateBoundaryTransform,\n false\n );\n countyMapCanvas.addLayer(countyMapStateBoundaryLayer);\n countyMapStateBoundaryLayer.addPlacement({\n centroid_x: \"col:bbox_x\",\n centroid_y: \"col:bbox_y\",\n width: \"col:bbox_w\",\n height: \"col:bbox_h\"\n });\n countyMapStateBoundaryLayer.addRenderingFunc(\n usmap.getUSMapRenderer(\"countyMapStateBoundaryRendering\")\n );\n countyMapStateBoundaryLayer.setUSMapId(\n this.usmaps.length - 1 + \"_\" + 1\n );\n\n // county boundary layer\n var countyMapTransform = new Transform(\n `SELECT name, ${usmap.countyRateCol}, geomstr\n FROM ${usmap.countyTable};`,\n usmap.db,\n usmap.getUSMapTransformFunc(\"countyMapTransform\"),\n [\"bbox_x\", \"bbox_y\", \"bbox_w\", \"bbox_h\", \"name\", \"rate\", \"geomstr\"],\n true\n );\n var countyBoundaryLayer = new Layer(countyMapTransform, false);\n countyMapCanvas.addLayer(countyBoundaryLayer);\n countyBoundaryLayer.addPlacement({\n centroid_x: \"col:bbox_x\",\n centroid_y: \"col:bbox_y\",\n width: \"col:bbox_w\",\n height: \"col:bbox_h\"\n });\n countyBoundaryLayer.addRenderingFunc(\n usmap.getUSMapRenderer(\"countyMapRendering\")\n );\n countyBoundaryLayer.addTooltip(\n [\"name\", \"rate\"],\n [\"County\", usmap.tooltipAlias]\n );\n countyBoundaryLayer.setUSMapId(this.usmaps.length - 1 + \"_\" + 1);\n\n // add to canvases (return)\n canvases.push(countyMapCanvas);\n\n // =============== jump ===============\n if (usmap.zoomType == \"literal\") {\n this.addJump(\n new Jump(stateMapCanvas, countyMapCanvas, \"literal_zoom_in\")\n );\n this.addJump(\n new Jump(countyMapCanvas, stateMapCanvas, \"literal_zoom_out\")\n );\n } else if (usmap.zoomType == \"jump\") {\n var selector = new Function(\n \"row\",\n \"args\",\n `return args.layerId = ${stateMapCanvas.layers.length - 1}`\n );\n var newPredicates = function() {\n return {};\n };\n var newViewportBody = function(row, args) {\n var zoomFactor = REPLACE_ME_zoomfactor;\n var vpW = args.viewportW;\n var vpH = args.viewportH;\n return {\n constant: [\n row.bbox_x * zoomFactor - vpW / 2,\n row.bbox_y * zoomFactor - vpH / 2\n ]\n };\n };\n var newViewport = new Function(\n \"row\",\n \"args\",\n getBodyStringOfFunction(newViewportBody).replace(\n /REPLACE_ME_zoomfactor/g,\n usmap.zoomFactor\n )\n );\n var jumpName = function(row) {\n return \"County map of \" + row.name;\n };\n this.addJump(\n new Jump(\n stateMapCanvas,\n countyMapCanvas,\n \"geometric_semantic_zoom\",\n {\n selector: selector,\n viewport: newViewport,\n predicates: newPredicates,\n name: jumpName\n }\n )\n );\n }\n }\n\n return {pyramid: canvases, view: args.view ? args.view : view};\n}", "function layersControl () {\r\n if (maptype == \"artmap\") { \r\n basemaps = {\r\n 'Mapquest Open <img src=\"./lib/images/external.png\" />' : mapquestopen\r\n };\r\n overlays = {\r\n 'WV Artikel <img src=\"./lib/images/wv-logo-12.png\" />' : wvarticles\r\n };\r\n }\r\n \r\n else if (maptype == \"geomap\") {\r\n basemaps = {\r\n 'Mapnik <img src=\"./lib/images/wmf-logo-12.png\" />': mapnik,\r\n 'Mapquest open <img src=\"./lib/images/external.png\" />': mapquestopen,\r\n 'Mapquest aerial <img src=\"./lib/images/external.png\" />': mapquest\r\n }; \r\n overlays = {\r\n 'Mapquest Beschriftungen <img src=\"./lib/images/external.png\" />': maplabels,\r\n 'Grenzen <img src=\"./lib/images/external.png\" />': boundaries,\r\n 'Radwege <img src=\"./lib/images/external.png\" />': cycling\r\n };\r\n }\r\n \r\n else if (maptype == \"gpxmap\") { \r\n basemaps = {\r\n 'Mapquest Open <img src=\"./lib/images/external.png\" />' : mapquestopen\r\n };\r\n overlays = {\r\n 'WV Artikel <img src=\"./lib/images/wv-logo-12.png\" />' : wvarticles\r\n };\r\n }\r\n \r\n else if (maptype == \"monmap\") {\r\n basemaps = {\r\n 'Mapquest Open <img src=\"./lib/images/external.png\" />' : mapquestopen,\r\n 'Mapnik <img src=\"./lib/images/wmf-logo-12.png\" />' : mapnik, \r\n 'Reliefkarte <img src=\"./lib/images/external.png\" />' : landscape\r\n };\r\n overlays = {\r\n 'Denkmäler <img src=\"./lib/images/wv-logo-12.png\" />' : monuments\r\n };\r\n }\r\n\r\n else if (maptype == \"poimap2\") {\r\n basemaps = {\r\n 'Mapnik <img src=\"./lib/images/wmf-logo-12.png\" />' : mapnik,\r\n 'Mapnik s/w <img src=\"./lib/images/wmf-logo-12.png\" />' : mapnikbw,\r\n 'Mapquest Open <img src=\"./lib/images/external.png\" />' : mapquestopen,\r\n 'Mapquest Aerial <img src=\"./lib/images/external.png\" />' : mapquest,\r\n 'Verkehrsliniennetz <img src=\"./lib/images/external.png\" />' : transport,\r\n 'Reliefkarte <img src=\"./lib/images/external.png\" />' : landscape\r\n };\r\n overlays = {\r\n 'Mapquest Beschriftungen <img src=\"./lib/images/external.png\" />' : maplabels,\r\n 'Grenzen <img src=\"./lib/images/external.png\" />' : boundaries,\r\n 'Schummerung <img src=\"./lib/images/wmf-logo-12.png\" />' : hill,\r\n 'Radwege <img src=\"./lib/images/external.png\" />' : cycling,\r\n 'Wanderwege <img src=\"./lib/images/external.png\" />' : hiking,\r\n 'Sehenswürdigkeiten <img src=\"./lib/images/wv-logo-12.png\" />' : markers,\r\n 'Reiseziele <img src=\"./lib/images/wv-logo-12.png\" />' : wvarticles,\r\n 'GPX Spuren / Kartenmaske <img src=\"./lib/images/wv-logo-12.png\" />' : tracks\r\n };\r\n }\r\n}", "set layers(layers) {\n this.cache.layers = [];\n layers.forEach(this.add, this);\n }", "function addDataToLayer(isySubLayer, data) {\n var layer = _getLayerFromPool(isySubLayer);\n if (isySubLayer.format === ISY.Domain.SubLayer.FORMATS.geoJson) {\n var geoJson = JSON.parse(data);\n var geoJsonParser = new ol.format.GeoJSON();\n var features = geoJsonParser.readFeatures(geoJson);\n\n //for (var i = 0; i < features.length; ++i) {\n // if (features[i].getProperties().Guid) {\n // features[i].setId(features[i].getProperties().Guid);\n // }\n //}\n if (isySubLayer.id && isySubLayer.name) {\n for (var i = 0; i < features.length; ++i) {\n if (features[i].getProperties().Guid === undefined) {\n features[i].setProperties({\n Guid: new ISY.Utils.Guid().NewGuid(),\n });\n }\n features[i].setId(\n isySubLayer.name + \".\" + features[i].getProperties().Guid\n );\n }\n }\n\n layer.getSource().addFeatures(features);\n }\n }", "function plotDataset(dataset) {\n SchoolDemographicsGeoJSON = L.geoJson(dataset, {\n\tstyle: schoolStyle,\n onEachFeature: schoolsOnEachFeature\n // school building data did not show up because I'd removed the .addTo(map) -- still have error showing up related to addTo on line 138:\n // addTo is undefined \"cannot read property 'addTo' of undefined\"\n }).addTo(map);\n\n // create layer controls\n createLayerControls(); \n}", "addSource(details){\n //if the source already exists then delete it\n if (this.map.getSource(details.id)) this.removeSource(details.id);\n this.map.addSource(details.id, details.source);\n }", "function createMarkers (urlArray) {\n let geoData\n // loop array with url's\n for (let i = 0; i < urlArray.length; i++) {\n let url = urlArray[i]\n // get data\n $.get(url, function (data) {\n // check if not empty\n if (data) {\n geoData = JSON.parse(data)\n }\n }).done(function () {\n let feature = new ol.Feature({\n service_url: geoData.http.service_url,\n geo: geoData.http.geo,\n ip4: geoData.http.ip4,\n country: geoData.http.geo.country_name,\n geometry: new ol.geom.Point(ol.proj.transform([geoData.http.geo.longitude, geoData.http.geo.latitude], 'EPSG:4326', 'EPSG:3857'))\n })\n // append Marker on map\n feature.setStyle(styleMk)\n sourceFeatures.addFeature(feature)\n })\n }\n // cleare Marker layers\n sourceFeatures.clear()\n startChain(2)\n }", "function add(options) {\n options.vectors.forEach(vector => {\n let format, url = vector.url;\n const readOptions = {\n featureProjection: map.get('view').getProjection()\n };\n const sourceOptions = {\n attributions: vector.attribution || ''\n };\n const name = url || vector.filename;\n if (name && !vector.format) {\n // define format from file extension\n const extensions = {geojson: 'GeoJSON', gpx: 'GPX', kml: 'KML'};\n const ext = name.substring(name.lastIndexOf('.') + 1);\n format = extensions[ext];\n }\n format = vector.format || format;\n if (format) {\n sourceOptions.format = getFormat(format);\n }\n if (vector.file) {\n sourceOptions.features = sourceOptions.format.readFeatures(vector.file,\n readOptions);\n } else if (url) {\n if (vector.strategy && vector.strategy == 'bbox') {\n // copied from loadingstrategy.bbox\n sourceOptions.strategy = (extent, resolution) => [extent];\n }\n sourceOptions.loader = (extent, resolution, projection) => {\n if (vector.strategy && vector.strategy == 'bbox') {\n const wgsExt = transformExtent(extent, projection, 'EPSG:4326');\n url = vector.url + [[wgsExt[0].toFixed(6), wgsExt[1].toFixed(6)],\n [wgsExt[2].toFixed(6), wgsExt[1].toFixed(6)],\n [wgsExt[2].toFixed(6), wgsExt[3].toFixed(6)],\n [wgsExt[0].toFixed(6), wgsExt[3].toFixed(6)],\n [wgsExt[0].toFixed(6), wgsExt[1].toFixed(6)]]\n .join('],[') + ']]]}}}}';\n }\n fetch(url)\n .then(response => {\n if (format == 'GeoJSON' || format == 'mongo') {\n return response.json();\n } else {\n return response.text();\n }\n })\n .then(result => {\n const features = sourceOptions.format.readFeatures(result, readOptions);\n const layers = getLayers().getArray().filter(function(l) {\n return l.getProperties().id == vector.id;\n });\n const source = layers[0].get('source');\n source.addFeatures(features);\n })\n .catch((err) => {\n console.log(err);\n alert('Unable to load vector file');\n });\n };\n }\n const source = new VectorSource(sourceOptions);\n // if this is an added layer and not bbox, zoom to data extent\n if (vector.add === true && (url && !(vector.strategy && vector.strategy == 'bbox'))) {\n source.once('change', (e) => {\n map.get('view').fit(e.target.getExtent());\n });\n }\n const vectOpts = {\n source: source,\n id: vector.id || url\n };\n // override default style if in options\n const custom = {};\n for (const att in defaultStyles.normal) {\n custom[att] = defaultStyles.normal[att];\n }\n if (vector.style) {\n for (const att in vector.style) {\n custom[att] = vector.style[att];\n }\n }\n defaultStyles[vectOpts.id] = custom;\n vectOpts.style = feature => getStyle(vectOpts.id, feature);\n const newLayer = new VectorLayer(vectOpts);\n if (vector.group) {\n newLayer.set('group', vector.group);\n }\n getLayers().push(newLayer);\n if (vector.add === true && vector.file) {\n map.get('view').fit(source.getExtent());\n }\n if (vector.noDisplay) {\n newLayer.set('visible', false);\n }\n\n // add to layerswitcher\n const rtns = switcher.addVectorDiv(vector);\n rtns[0].addEventListener('click', switcherHandler.bind(map));\n // if this is 1st vector layer, add vector component buttons and not already included\n if (rtns[1]) {\n const comps = options.components || [];\n if (comps.indexOf('popup') == -1) {\n $('#featuredisplayoption').style.display = 'block';\n }\n if (comps.indexOf('tooltip') == -1) {\n $('#tooltipoption').style.display = 'block';\n }\n }\n });\n}", "function addDataToMap(dataIndex) {\n\n // data container\n var plotData = {};\n\n // loop over the original dataset to fix the data format and find minMax\n $.each(internetData, function(_, entry) {\n\n // if first time using the data transform to 3 letter ISO country code\n if (entry.ISO.length < 3) {\n entry.ISO = countryConverter(entry.ISO);\n }\n });\n\n /* Remove the old legend. \n * While this is a bit of a 'hacky way to do it' it seems like datamaps \n * is actually working pretty smoothly when doing it this way.\n * More fancy 'd3-type' changes caused all kinds of complications, making\n * them not worth my time to fix.\n */\n $('.datamaps-legend').remove();\n // set the new map scale\n var scale = setMapScale(dataIndex);\n\n // remake the legend\n var mapLegend = {\n legendTitle: cleanText(dataIndex),\n defaultFillName: 'No data',\n labels: {}\n };\n\n // all data entries will be 9 categories, so again a bit of an 'ugly' fix\n for (var i = 0; i < 9; i++) {\n\n // this functions gives you the upper and lower bounds of a quantized scale\n var bounds = scale.invertExtent(i);\n mapLegend.labels[i] = String(parseInt(bounds[0])) + '-' + String(parseInt(bounds[1]));\n }\n\n // prepare the new data to be visualized\n $.each(internetData, function(_, entry) {\n plotData[entry.ISO] = {\n value: entry[dataIndex],\n fillKey: scale(entry[dataIndex])\n }\n });\n\n // update both map and legend\n map.updateChoropleth(plotData);\n map.legend(mapLegend);\n}", "function _map_addTrafficLayer(map,target){\r\n\t/* tbd */\r\n}", "function refreshAndInitMap() {\n // Remove all added layer:\n removeAllLayers();\n // Remove all source:\n removeAllSources();\n}", "function addAreas(){\n //draws the areas\n areaMap.forEach(function(item, key, mapObj){\n polyArea = drawArea(item);\n polyArea.addTo(areaLayer);\n })\n}", "function addPlaceMarks() {\n // first init layer\n if (gazetteerLayer == null) {\n gazetteerLayer = new WorldWind.RenderableLayer(\"GazetteerLayer\"); \n\n for (var i = 0; i < availableRegionsCSV.length; i++) { \n // create a marker for each point\n var name = availableRegionsCSV[i].name;\n var latitude = availableRegionsCSV[i].center_lat;\n var longitude = availableRegionsCSV[i].center_lon; \n var diameter = parseFloat(availableRegionsCSV[i].diameter);\n\n var labelAltitudeThreshold = 0; \n\n if (diameter >= 0 && diameter < 10) { \n labelAltitudeThreshold = 1.1e3;\n } else if (diameter > 10 && diameter < 20) {\n labelAltitudeThreshold = 1.7e3;\n } else if (diameter >= 20 && diameter < 40) {\n labelAltitudeThreshold = 1.2e4;\n } else if (diameter >= 40 && diameter < 60) {\n labelAltitudeThreshold = 1.7e4;\n } else if (diameter >= 60 && diameter < 80) {\n labelAltitudeThreshold = 1.2e5;\n } else if (diameter >= 80 && diameter < 100) {\n labelAltitudeThreshold = 1.7e5;\n } else if (diameter >= 100 && diameter < 200) {\n labelAltitudeThreshold = 1.2e6;\n } else if (diameter >= 200 && diameter < 400) {\n labelAltitudeThreshold = 1.7e6;\n } else if (diameter >= 400 && diameter < 600) {\n labelAltitudeThreshold = 1.2e7;\n } else if (diameter >= 600 && diameter < 1000) {\n labelAltitudeThreshold = 1.7e7;\n } else if (diameter >= 1000 && diameter < 1400) {\n labelAltitudeThreshold = 1.2e8;\n } else if (diameter >= 1400 && diameter < 2000) {\n labelAltitudeThreshold = 1.7e8;\n } else {\n labelAltitudeThreshold = 1.2e9;\n }\n\n\n var placemark = new WorldWind.Placemark(new WorldWind.Position(latitude, longitude, 10), true, null);\n placemark.label = name;\n placemark.altitudeMode = WorldWind.RELATIVE_TO_GROUND; \n\n placemark.eyeDistanceScalingThreshold = labelAltitudeThreshold - 1e5;\n placemark.eyeDistanceScalingLabelThreshold = labelAltitudeThreshold;\n\n var placemarkAttributes = new WorldWind.PlacemarkAttributes(); \n placemarkAttributes.labelAttributes.color = new WorldWind.Color(0.43, 0.93, 0.97, 1);\n placemarkAttributes.labelAttributes.depthTest = false;\n placemarkAttributes.labelAttributes.scale = 1.2;\n placemarkAttributes.imageScale = 0.8;\n placemarkAttributes.imageSource = \"html/images/close.png\"; \n\n placemark.attributes = placemarkAttributes;\n\n\n // as they are small and slow\n if (diameter < MIN_DEFAULT_LOAD) {\n placemark.enabled = false;\n }\n\n var obj = {\"diameter\": diameter};\n placemark.userProperties = obj;\n\n\n // add place mark to layer\n gazetteerLayer.addRenderable(placemark); \n } \n\n // Marker layer\n wwd.insertLayer(10, gazetteerLayer);\n\n } else { \n if (isShowGazetteer === false) {\n gazetteerLayer.enabled = false; \n } else { \n gazetteerLayer.enabled = true;\n }\n } \n }", "function buildLayerMap(){\n // OpenStreetMap\n let osm = L.tileLayer(\"http://{s}.tile.osm.org/{z}/{x}/{y}.png\", {\n attribution:\n '&copy; <a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors'\n });\n\n // Sentinel Hub WMS service\n // tiles generated using EPSG:3857 projection - Leaflet takes care of that\n let baseUrl =\n \"https://services.sentinel-hub.com/ogc/wms/ca37eeb6-0a1f-4d1b-8751-4f382f63a325\";\n let sentinelHub = L.tileLayer.wms(baseUrl, {\n tileSize: 512,\n attribution:\n '&copy; <a href=\"http://www.sentinel-hub.com/\" target=\"_blank\">Sentinel Hub</a>',\n urlProcessingApi:\n \"https://services.sentinel-hub.com/ogc/wms/aeafc74a-c894-440b-a85b-964c7b26e471\",\n maxcc: 0,\n minZoom: 6,\n maxZoom: 16,\n preset: \"CUSTOM\",\n evalscript: \"cmV0dXJuIFtCMDEqMi41LEIwMSoyLjUsQjA0KjIuNV0=\",\n evalsource: \"S2\",\n PREVIEW: 3,\n layers: \"NDVI\",\n time: \"2020-05-01/2020-11-07\"\n });\n let agriHub = L.tileLayer.wms(baseUrl, {\n tileSize: 512,\n attribution: '&copy; <a href=\"http://www.sentinel-hub.com/\" target=\"_blank\">Sentinel Hub</a>',\n urlProcessingApi:\"https://services.sentinel-hub.com/ogc/wms/aeafc74a-c894-440b-a85b-964c7b26e471\", \n maxcc:20, \n minZoom:6, \n maxZoom:16, \n preset:\"AGRICULTURE\", \n layers:\"AGRICULTURE\", \n time:\"2020-05-01/2020-11-07\", \n \n });\n\n layerMap.default = osm;\n layerMap.one = sentinelHub;\n layerMap.two = agriHub;\n}", "function addHexLayer(recordsJson) {\n\n // Get coordinate pairs for each record\n var coords = [];\n jQuery.each(recordsJson, function (i, val) {\n coords.push([val[\"longitude\"], val[\"latitude\"]]);\n });\n\n // Update the layer data\n hexLayer.data(coords);\n\n // Add to the overlay group\n hexLayer.addTo(overlays);\n}", "function setMapAndLayers() {\n if (_options.mapDivId) {\n var map = _config.getMap();\n if (map) {\n // Render map to its position.\n map.render(_options.mapDivId);\n var layers = _config.getLayers();\n if (layers) {\n setAnimationLegendEventListener(layers);\n setLayers(map, layers);\n }\n // Zoom the map after layers have been inserted.\n map.setCenter(map.getCenter(), _config.getDefaultZoomLevel());\n setupSwitcher(map, _options.layerSwitcherDivId, _options.maximizeSwitcher);\n }\n }\n }", "swapBasemap(toAdd) {\n this.currentSources = []\n this.currentLayers = []\n\n // First record which layers are currently on the map\n Object.keys(mapStyle.sources).forEach(source => {\n let isPresent = this.map.getSource(source)\n if (isPresent) {\n this.currentSources.push({\n id: source,\n config: mapStyle.sources[source],\n data: isPresent._data || null\n })\n }\n })\n\n mapStyle.layers.forEach(layer => {\n let isPresent = this.map.getLayer(layer.id)\n if (isPresent) {\n this.currentLayers.push({\n layer: layer,\n filters: this.map.getFilter(layer.id)\n })\n }\n })\n\n // Set the style. `style.load` will be fired after to readd other layers\n this.map.setStyle(toAdd)\n }", "function addFeaturesListener() {\n const vectorLayers = getLayers().getArray();\n // copied from extent.createEmpty()\n const vectorsExtent = [Infinity, Infinity, -Infinity, -Infinity];\n let sourcesRead = 0;\n // callback\n const callback = e => {\n // copied from extent.extend\n const extend = (extent1, extent2) => {\n if (extent2[0] < extent1[0]) {\n extent1[0] = extent2[0];\n }\n if (extent2[2] > extent1[2]) {\n extent1[2] = extent2[2];\n }\n if (extent2[1] < extent1[1]) {\n extent1[1] = extent2[1];\n }\n if (extent2[3] > extent1[3]) {\n extent1[3] = extent2[3];\n }\n return extent1;\n };\n extend(vectorsExtent, e.target.getExtent());\n sourcesRead++;\n if (sourcesRead == vectorLayers.length) {\n // we've loaded all the sources\n // so zoom to data extent and make 1st raster layer visible\n map.get('view').fit(vectorsExtent);\n rasters.makeActiveLayerVisible();\n $('#status').style.display = 'none';\n }\n };\n vectorLayers.forEach(l => {\n l.get('source').once('change', callback);\n });\n}", "function addBaseLayer(map, pBaseLayer) {\n\n // var streetsB = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n // attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n // maxZoom: 18,\n // id: \"mapbox.streets\",\n // accessToken: apiKey\n // });\n\n pBaseLayer.addTo(map);\n\n}", "function buildMaps(countrys_info) {\n\n d3.json(\"/static/data/countries.geo.json\", function (countryMapData) {\n updataJsonData(countryMapData, countrys_info);\n createFeatures(countryMapData);\n });\n }", "function eqfeed_callback(data) {\n map.data.addGeoJson(data);\n }", "addSource(source) {\n this._data.source = source;\n }", "function loadMap(stores) {\n map1.on('load', function () {\n map1.addLayer({\n id: 'points',\n type: 'symbol',\n source: {\n type: 'geojson',\n data: {\n type: 'FeatureCollection',\n features: stores\n }\n },\n layout: {\n 'icon-image': '{icon}-15',\n 'icon-size': 1.5,\n 'text-field': '{placeId}',\n 'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],\n 'text-offset': [0, 0.9],\n 'text-anchor': 'top'\n }\n\n });\n\n // When a click event occurs on a feature in the places layer, open a popup at the\n // location of the feature, with description HTML from its properties.\n map1.on('click', 'points', function (e) {\n var coordinates = e.features[0].geometry.coordinates.slice();\n var place = e.features[0].properties.place;\n var about = e.features[0].properties.description;\n\n // Ensure that if the map is zoomed out such that multiple\n // copies of the feature are visible, the popup appears\n // over the copy being pointed to.\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n new mapboxgl.Popup()\n .setLngLat(coordinates)\n .setHTML('<h3>' + place + '</h3>' + '<p>' + about + '</p>')\n .addTo(map1);\n });\n\n // Change the cursor to a pointer when the mouse is over the places layer.\n map1.on('mouseenter', 'points', function () {\n map1.getCanvas().style.cursor = 'pointer';\n });\n\n // Change it back to a pointer when it leaves.\n map1.on('mouseleave', 'points', function () {\n map1.getCanvas().style.cursor = '';\n });\n\n });\n }", "function loadMapServiceLayers(inMapServiceArray, inMap){\n\t \n\t var currentMapService = null;\n\t var mapControl = inMap;\n\t \n\t try {\n\t \n\t //iterate all base map services in json config and add to map control\n\t \tfor (var i = 0, il = inMapServiceArray.length; i < il; i++) {\n\t\t\t\n\t \t\tif (inMapServiceArray[i].mapServiceType == \"fusedCache\") {\n\n\t \t\t\tcurrentMapService = new esri.layers.ArcGISTiledMapServiceLayer(inMapServiceArray[i].restUrl, {\n\t \t\t\t\tid: inMapServiceArray[i].mapServiceId,\n\t \t\t\t\topacity: inMapServiceArray[i].opacity,\n\t \t\t\t\tvisible: inMapServiceArray[i].isVisible\n\t \t\t\t});\n\t \t\t}\t\n\t \t\telse if (inMapServiceArray[i].mapServiceType == \"dynamic\") {\n\t \t\t\t\n\t \t\t\tcurrentMapService = new esri.layers.ArcGISDynamicMapServiceLayer(inMapServiceArray[i].restUrl, {\n\t \t\t\t\tid: inMapServiceArray[i].mapServiceId,\n\t \t\t\t\topacity: inMapServiceArray[i].opacity,\n\t \t\t\t\tvisible: inMapServiceArray[i].isVisible\n\t \t\t\t});\n\t \t\t}\t\t\t\t\n\t\t\t\n\t\t\tmapControl.addLayer(currentMapService);\t\n\t }\n\t}\n\tcatch(err){\n\t\t\n\t\tconsole.error(\"Error at loadMapServiceLayers() method.\" + \"\\nError Description:\" + err.description);\n\t}\n}", "function createMap(){\n\n var black = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png', {maxZoom: 19}),\n satelite = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {\n attribution: 'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'\n });\n\n var leafletMap = L.map('map',{\n center: [6.45, -9.5],\n zoom: 8,\n layers: [black,satelite]\n});\n\n var baseMaps = {\n \"Satelite\": satelite,\n \"Black\": black\n};\n \n\n L.control.layers(baseMaps).addTo(leafletMap);\n\n\n ////////////////////////////////////////////////////// Counties JSON\n\n // waCountiesJSON = L.geoJson(waCounties, {\n // style: lowStyle,\n // onEachFeature: onEachLowFeature\n // }).addTo(leafletMap); \n\n // slCountiesJSON = L.geoJson(slCounties, {\n // style: style,\n // onEachFeature: onEachFeature\n // }).addTo(leafletMap); \n\n // ginCountiesJSON = L.geoJson(ginCounties, {\n // style: style,\n // onEachFeature: onEachFeature\n // }).addTo(leafletMap); \n\n libCountiesJSON = L.geoJson(libCounties, {\n style: style,\n onEachFeature: onEachFeature\n }).addTo(leafletMap); \n\n ////////////////////////////////////////////////////////// Country JSON\n\n libOutline = L.geoJson(libCountry, {\n style: countryStyle,\n }).addTo(leafletMap); \n\n\n\n//////////////////////////////////////////////////////////// Roads\n\n libRoadJSON = L.geoJson(libROADS, {\n style: roadStyle,\n \n }).addTo(leafletMap); \n\n//////////////////////////////////////////////////// ETU JSON Files\n \n libJSON = L.geoJson(libETUData, {\n style: ETUstyle,\n pointToLayer : pointToLayer,\n onEachFeature: onEachETU\n}).addTo(leafletMap); \n\n// slJSON = L.geoJson(slETUData, {\n// style: ETUstyle,\n// pointToLayer : pointToLayer,\n// onEachFeature: onEachETU\n// }).addTo(leafletMap); \n\n// ginJSON = L.geoJson(ginETUData, {\n// style: ETUstyle,\n// pointToLayer : pointToLayer,\n// onEachFeature: onEachETU \n// }).addTo(leafletMap); \n\n CCCJSON = L.geoJson(CCCData, {\n style: ETUstyle,\n pointToLayer : pointToLayer,\n onEachFeature: onEachETU \n}).addTo(leafletMap); \n\n\n//////////////////////////////////////////////////////////// health centers \n\n// ginHealthJSON = L.geoJson(ginHealth, {\n// style: ETUstyle,\n// pointToLayer : HpointToLayer,\n// onEachFeature: onEachETU\n// }).addTo(leafletMap); \n\n libHealthJSON = L.geoJson(libHealth, {\n style: healthStyle,\n pointToLayer : HpointToLayer,\n onEachFeature: onEachHealth\n}).addTo(leafletMap); \n\n// slHealthJSON = L.geoJson(slHealth, {\n// style: ETUstyle,\n// pointToLayer : HpointToLayer,\n// onEachFeature: onEachETU \n// }).addTo(leafletMap); \n}", "function getDataSets (mapSource, dataSource) {\n queue()\n .defer(d3.json, mapSource)\n .defer(d3.csv, dataSource)\n .await(ready);\n }", "function addDistricts(map)\n { \n var districtLayer = new L.TopoJSON();\n $.getJSON('js/districts.topo.json').done(addDistrictData);\n \n function addDistrictData(topoData) \n {\n districtLayer.addData(topoData);\n districtLayer.addTo(map);\n districtLayer.eachLayer(handleLayer);\n }\n\n function handleLayer(layer) \n { \n layer.setStyle({\n fillColor : '#ccc',\n weight: 2,\n opacity: 1,\n color: 'white',\n fillOpacity: 1,\n });\n \n layer.on({\n mouseover : enterLayer,\n mouseout: leaveLayer,\n });\n }\n \n function enterLayer() \n { //show tooltip with district name\n var district = this.feature.properties.name;\n showTip = true;\n $('#map-tooltip').html(distTooltipHtml(district));\n $('#map-tooltip').addClass('active');\n $('#map-nepal').mousemove(function(e) {\n if (showTip) {\n $('#map-tooltip').css({'top': e.pageY, 'left': e.pageX + 15, 'position': 'absolute'}).show();\n }\n });\n }\n \n var distTooltipHtml = function(districtName) \n {\n return \"<div class='html-wrapper'><div>\" + districtName + \"</div></div>\";\n }\n \n function leaveLayer() \n {\n showTip = false;\n $('#map-tooltip').hide();\n }\n\n }", "function addWMSLayer(name, geoserver_name) {\n wms_layer = new OpenLayers.Layer.WMS(name, geoserver_url, {\n layers: \"cite:\" + geoserver_name,\n format: \"image/png8\",\n tiled: true,\n singleTile: false,\n transparent: true,\n styles: \"cite:Hazard Map\",\n tilesorigin: map.maxExtent.left + \",\" + map.maxExtent.bottom,\n }, {\n displayInLayerSwitcher: !1\n }, {\n isBaseLayer: false\n });\n registerEvents(wms_layer);\n toggleWMSLayer(name);\n}", "function addDatasets(dataSets) {\r\n chartDataSets = dataSets;\r\n return this;\r\n }", "addToChangeLayers(){\n let _to = this.props.toVersion.key;\n //attribute change in protected areas layers\n this.addLayer({id: window.LYR_TO_CHANGED_ATTRIBUTE, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(99,148,69,0.4)\", \"fill-outline-color\": \"rgba(99,148,69,0.8)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //geometry change in protected areas layers - to\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_TO_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_COUNT_CHANGED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_POINT_COUNT_CHANGED_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_SHIFTED_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_GEOMETRY_SHIFTED_POLYGON_LINE, sourceId: window.SRC_TO_POLYGONS, type: \"line\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: P_TO_CHANGED_GEOMETRY_LINE, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n //added protected areas layers\n this.addLayer({id: window.LYR_TO_NEW_POLYGON, sourceId: window.SRC_TO_POLYGONS, type: \"fill\", sourceLayer: \"wdpa_\" + _to + \"_polygons\", layout: {visibility: \"visible\"}, paint: { \"fill-color\": \"rgba(63,127,191,0.2)\", \"fill-outline-color\": \"rgba(63,127,191,0.6)\"}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n this.addLayer({id: window.LYR_TO_NEW_POINT, sourceId: window.SRC_TO_POINTS, type: \"circle\", sourceLayer: \"wdpa_\" + _to + \"_points\", layout: {visibility: \"visible\"}, paint: {\"circle-radius\": CIRCLE_RADIUS_STOPS, \"circle-color\": \"rgb(63,127,191)\", \"circle-opacity\": 0.6}, filter:INITIAL_FILTER, beforeID: window.LYR_TO_SELECTED_POLYGON});\n \n }", "function addSourceToMap(information, getBound, uploadAction) {\n if (convex_hull.isVisible()) {\n mamufasPolygon();\n }\n\n var point_changes = []\n\n\t\t\t\t/* Recursive service for adding markers. */\n function asynAddMarker(i,total,_bounds, uploadAction, observations) {\n if (i < total){\n var info_data = new Object();\n $.extend(info_data, observations[i]);\n \n if (info_data.catalogue_id && occurrences[info_data.catalogue_id]==undefined) {\n\t\t\t\t\t\t\t// If the point doesnt have info about _active and _removed\n\t\t\t\t\t\t\tif (info_data.geocat_active==undefined || info_data.geocat_active==null) info_data.geocat_active = true;\n\t\t\t\t\t\t\tif (info_data.geocat_removed==undefined || info_data.geocat_removed==null) info_data.geocat_removed = false;\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tvar geocat_query = (info_data.geocat_query!=undefined)?info_data.geocat_query.toLowerCase():'';\n\t\t\t\t\t\t\tvar geocat_kind = (info_data.geocat_kind!=undefined)?info_data.geocat_kind.toLowerCase():'user';\n\t\t\t\t\t\t\tvar latlng = new google.maps.LatLng(parseFloat(info_data.latitude),parseFloat(info_data.longitude));\n\t\t\t\t\t\t\t\n (info_data.geocat_removed)?null:points.add(geocat_query,geocat_kind);\n bounds.extend(latlng);\n\t\n var marker = new GeoCATMarker(latlng, geocat_kind, true, true, info_data, (info_data.geocat_removed)?null:map);\n\n occurrences[marker.data.catalogue_id] = marker;\n occurrences[marker.data.catalogue_id].data.geocat_query = geocat_query;\n occurrences[marker.data.catalogue_id].data.geocat_kind = geocat_kind;\n\n if (!info_data.geocat_active) {\n var marker_id = marker.data.catalogue_id;\n occurrences[marker_id].setActive(false);\n }\n } else {\n\t\t\t\t\t\t\tif (info_data.geocat_kind==undefined) {\n\t\t\t\t\t\t\t\tif (info_data.geocat_active==undefined || info_data.geocat_active==null) info_data.geocat_active = true;\n\t\t\t\t\t\t\t\tif (info_data.geocat_removed==undefined || info_data.geocat_removed==null) info_data.geocat_removed = false;\n\n\t\t\t\t\t\t\t\tvar geocat_query = (info_data.geocat_query!=undefined)?info_data.geocat_query.toLowerCase():'';\n\t\t\t\t\t\t\t\tvar geocat_kind = (info_data.geocat_kind!=undefined)?info_data.geocat_kind.toLowerCase():'user';\n\t\t\t\t\t\t\t\tvar latlng = new google.maps.LatLng(parseFloat(info_data.latitude),parseFloat(info_data.longitude));\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tpoints.add(geocat_query,geocat_kind);\n\t\t\t\t\t\t\t\tbounds.extend(latlng);\n\t\t\t\t\t\t\t\tglobal_id++;\n\t\t\t\t\t\t\t\tinfo_data.catalogue_id = 'user_' + global_id;\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tvar marker = new GeoCATMarker(latlng, geocat_kind, true, true, info_data, (info_data.geocat_removed)?null:map);\n\n\t occurrences[marker.data.catalogue_id] = marker;\n\t occurrences[marker.data.catalogue_id].data.geocat_query = geocat_query;\n\t occurrences[marker.data.catalogue_id].data.geocat_kind = geocat_kind;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\n\t\t\t\t\t\tif (!occurrences[marker.data.catalogue_id].data.geocat_removed)\n\t\t\t\t\t\t\tpoint_changes.push(occurrences[marker.data.catalogue_id].data);\n\n i++;\n setTimeout(function(){asynAddMarker(i,total,_bounds,uploadAction,observations);},0);\n } else {\n if (uploadAction) {\n $('body').trigger('hideMamufas');\n } else {\n hideMamufasMap(true);\n }\n \n if (_bounds) {\n map.fitBounds(bounds);\n }\n \n if (convex_hull.isVisible()) {\n $(document).trigger('occs_updated');\n }\n\n // Do add\n actions.Do('add',null,point_changes);\n }\n }\n \n if (information.points.length>20) {\n showMamufasMap();\n }\n\n asynAddMarker(0,information.points.length,getBound,uploadAction,information.points);\n\t\t\t}", "function createLayers(map){\n let torqueLayer = createTorqueLayer(map)\n let polygonLayer = createPolygonLayer(map)\n\n let loadedTorqueLayer;\n let loadedPolyLayer;\n\n polygonLayer.addTo(map)\n .on('done', function(layer) {\n loadedPolyLayer = layer;\n if (loadedTorqueLayer) {\n onPolygonLoad(map, loadedTorqueLayer, loadedPolyLayer)\n }\n })\n .on('error', logError);\n\n torqueLayer.addTo(map)\n .on('done', function(layer) {\n onTorqueLoad(map, layer)\n loadedTorqueLayer = layer\n if (loadedPolyLayer) {\n onPolygonLoad(map, loadedTorqueLayer, loadedPolyLayer)\n }\n })\n .on('error', logError);\n }", "function eqfeed_callback(data) {\n map.data.addGeoJson(data);\n }", "function createOpenLayersMaps() {\n var canadaMapOptions = {\n center: new OpenLayers.LonLat(-73.55, 45.51)\n };\n var canadaMap = new OpenLayers.Map('map_canada', canadaMapOptions);\n var wholeEarth = new OpenLayers.Layer.WMS(\"OpenLayers WMS\",\n \"http://vmap0.tiles.osgeo.org/wms/vmap0\",\n { layers: 'basic' });\n var canada = new OpenLayers.Layer.WMS(\"Canada\",\n \"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap\",\n {\n layers: \"road,popplace\",\n transparent: \"true\",\n format: \"image/png\"\n },\n {\n isBaseLayer: false,\n visibility: false\n });\n canadaMap.addLayers([wholeEarth, canada]);\n canadaMap.addControl(new OpenLayers.Control.LayerSwitcher());\n canadaMap.zoomTo(4);\n }", "function addCoordsToMap(jobs, sideBar, regions, layers) {\n var controlRegion = layers[0];\n if (regions)\n { layers.forEach(function(layer){\n layer.clearLayers();\n });\n regions.forEach(function(region){\n L.geoJson(region, {\n pointToLayer: function (feature, latlng) {\n return L.marker(latlng)\n }\n }).addTo(controlRegion);\n })\n }\n jobs.forEach(function (job) {\n L.geoJson(job, {\n pointToLayer: function (feature, latlng) {\n return L.marker(latlng, {icon: eval(job.properties.jobType), alt: job.properties.id})\n }\n }).addTo(eval(\"control\" + job.properties.jobType.capitalize())).on('click', function(){\n getJobProperties(job.properties.id, sideBar)\n })\n });\n\n}", "function initLayerAllFeatures(points, mainMap) {\n var context = function(feature) {return feature;} // a magic line from somewhere..\n var myStyle = new OpenLayers.Style( {\n graphicName: \"circle\", fillOpacity: \"1\", fillColor: \"#378fe0\", strokeColor: \"blue\", pointRadius: 5,\n graphicTitle: \"${label}\", labelYOffset: \"7px\", externalGraphic: \"${iconUrl}\", graphicWidth: \"${size}\",\n fontSize: \"10px\", fontFamily: \"Verdana, Arial\", fontColor: \"#ffffff\"}); //, cursor: \"pointer\"} );\n var textStyle = new OpenLayers.Style( {\n graphicName: \"circle\", fillOpacity: \"1\", fillColor: \"#378fe0\", strokeColor: \"#378fe0\", pointRadius: 8,\n fontSize: \"11px\", fontWeight: \"bold\", labelXOffset: \"-2px\", fontFamily: \"Verdana, Arial\",\n fontColor: \"#ffffff\", label: \"${text}\"} );\n var symbolizer = OpenLayers.Util.applyDefaults( myStyle, OpenLayers.Feature.Vector.style[\"default\"]);\n var myStyleMap = new OpenLayers.StyleMap({\n \"default\": symbolizer, \"enumeration\": textStyle, // cursor: \"pointer\",\n \"select\": {strokeColor:\"red\", fillOpacity: \"1\", fillColor:\"white\", strokeWidth: 2 , graphicWidth: 23},\n \"temporary\": {strokeColor:\"white\", fillOpacity: \"1\", fillColor: \"blue\", strokeWidth: 2, graphicWidth: 25}\n });\n //\"hotspot\": {pointRadius: 8}});\n var lookup = {\n \"normal\": {pointRadius: 5}, // normal\n \"hotspot\": {pointRadius: 7} // hotspot / cluster\n };\n myStyleMap.addUniqueValueRules(\"default\", \"marker\", lookup);\n // myStyleMap.addUniqueValueRules(\"temporary\", \"label\", labelook);\n myNewLayer = new OpenLayers.Layer.Vector('Kiezatlas Marker', {\n styleMap: myStyleMap, displayInLayerSwitcher: false\n // strategies: [ new OpenLayers.Strategy.Cluster() ]\n });\n // ### redundant^^\n kiezatlas.setLayer(myNewLayer);\n //\n var selectFeatureHandler = new OpenLayers.Control.SelectFeature(kiezatlas.layer, {\n multiple: false, clickout: false, toggle: false,\n hover: false, highlightOnly: false, renderIntent: \"select\",\n onSelect: function() {\n // jQuery(\"#memu\").css(\"visibility\", \"hidden\");\n }\n });\n mainMap.addControl(selectFeatureHandler);\n selectFeatureHandler.activate();\n //\n var featureHandler = new OpenLayers.Handler.Feature(selectFeatureHandler, myNewLayer, {\n //stopClick: true,\n stopUp: true, stopDown: true,\n click: function(feat) {\n for ( i = 0; i < kiezatlas.layer.selectedFeatures.length; i++) {\n selectFeatureHandler.unselect(kiezatlas.layer.selectedFeatures[i]);\n }\n showInfoWindowForMarker(feat.data);\n selectFeatureHandler.select(feat);\n }, // clickFunction\n clickout: function (feat) {\n selectFeatureHandler.unselect(feat);\n hideAllInfoWindows();\n }\n }); // end FeatureHandlerInit\n /* commented out the mouseover cluster menu */\n var highlightCtrl = new OpenLayers.Control.SelectFeature(kiezatlas.layer, {\n hover: true, highlightOnly: true,\n renderIntent: \"temporary\",\n eventListeners: { // makes use of the global propertyMap for eventListeners\n beforefeaturehighlighted: function(e) {\n e.feature.attributes.label = e.feature.data.topicName;\n // no menu just label\n var marker = e.feature.attributes.marker;\n if (marker == \"hotspot\") {\n e.feature.attributes.label = \"mehrere Einsatzm\\u00F6glichkeiten\";\n }\n },\n // ### ToDo: mostly unused and to be removed\n /* featurehighlighted: function(e) {\n var marker = e.feature.attributes.marker;\n if (marker == \"hotspot\") {\n //log(\"hotSpotFeature highlght, to show contextMenu at l:\" + e.feature.geometry.bounds.getCenterPixel()); // + \"b:\"+ e.feature.geometry.bounds.bottom);\n var centerPoint = myNewLayer.getViewPortPxFromLonLat(e.feature.geometry.bounds.getCenterLonLat());\n var htmlString = \"\";\n if ( e.feature.data.cluster != null && e.feature.data.cluster != undefined ) {\n /* for ( i = 0; i < e.feature.data.cluster.length; i++) {\n // htmlString += '<a href=javascript:showInfoWindowForTopicId(\"'\n // + e.feature.data.cluster[i].topicId+'\");>'+e.feature.data.cluster[i].topicName+'</a><br/>';\n }\n // jQuery(\"#memu\").html(htmlString);\n // jQuery(\"#memu\").css(\"visibility\", \"visible\");\n // jQuery(\"#memu\").css(\"left\", centerPoint.x);\n // jQuery(\"#memu\").css(\"top\", centerPoint.y + headerGap + 27); // ### headergap seems unneccessary\n }\n } else {\n // log(\"normalFeature just highlight\");\n // e.feature.attributes.label = \"\";\n }\n }, */\n featureunhighlighted: function(e) {\n // TODO: is wrong one, if one is already selected and the user wants to deal with a cluster\n // log(\"feature\" + e.feature.data.topicId + \" unhighlighted\");\n var marker = e.feature.attributes.marker;\n if (marker == \"hotspot\") {\n jQuery(\"#memu\").css(\"visibility\", \"hidden\");\n // var testXY = e.feature.geometry.clone().transform(map.projection, map.displayProjection);\n // log(\"hotSpotFeature highlght, to hide contextMenu at l:\" + myNewLayer.getViewPortPxFromLonLat(testXY));\n // + \"t:\"+ e.feature.geometry.bounds.top);\n } else {\n // e.feature.attributes.label = \" \";\n }\n }\n } // eventListeners end\n });\n mainMap.addControl(highlightCtrl);\n highlightCtrl.activate();\n featureHandler.activate();\n allFeatures = [points.length];\n for ( var i = 0; i < points.length; i++ ) {\n allFeatures[i] = new OpenLayers.Feature.Vector (\n new OpenLayers.Geometry.Point(points[i].lonlat.lon, points[i].lonlat.lat), {\"marker\": \"normal\", \"label\": \"\"}\n );\n allFeatures[i].data = {\n topicName: points[i].topicName, topicId: points[i].topicId, defaultIcon: points[i].defaultIcon,\n lon:points[i].lonlat.lon, lat:points[i].lonlat.lat, originId: points[i].originId\n };\n allFeatures[i].cluster = null;\n allFeatures[i].attributes.iconUrl = \"\"; // not to show feature after initializing\n // allFeatures[i].attributes.renderer = \"circle\"; // = \"blackdot.gif\"; // not to show feature after initializing\n allFeatures[i].attributes.size = \"15\"; // item-style when geoobject is directly called from outside www\n allFeatures[i].attributes.label = points[i].topicName;\n allFeatures[i].renderIntent = \"default\"; // not to show feature after initializing\n // add new feature\n kiezatlas.layer.addFeatures(allFeatures[i]);\n }\n map.addLayer(kiezatlas.layer);\n }", "function dataMaps(){\n\td3.queue()\n\t.defer(d3.json, \"QoLI.json\")\n\t.awaitAll(makeMap)\n}", "function getData(map) {\n\n // load the states\n $.ajax(\"data/state_4326_map.json\", {\n dataType: \"json\",\n success: function(data) {\n // remove current layer if exists\n if (curStateLayer) {\n map.removeLayer(curStateLayer);\n };\n\n // Define the geojson layer and add it to the map\n curStateLayer = L.geoJson(data, {\n style: stateStyle,\n // filter by location\n /*filter: function(feature, layer){\n return filterStateByName(feature, layer);\n },*/\n // on each feature of states\n onEachFeature: stateOnEachFeature\n });\n map.addLayer(curStateLayer);\n\n }\n });\n\n // load the urban\n $.ajax(\"data/urban_4326_map.json\", {\n dataType: \"json\",\n success: function(data) {\n // remove current layer if exists\n if (curUrbanLayer) {\n map.removeLayer(curUrbanLayer);\n };\n\n // Define the geojson layer and add it to the map\n curUrbanLayer = L.geoJson(data, {\n style: urbanStyle,\n // filter by location\n /*filter: function(feature, layer){\n return filterUrbanByName(feature, layer);\n },*/\n // on each feature of states\n onEachFeature: urbanOnEachFeature\n });\n map.addLayer(curUrbanLayer);\n }\n });\n\n}", "addLayer(layer) {\n const { feature } = layer\n const { color } = feature.properties\n\n if (color && layer.setStyle) {\n layer.setStyle({ color })\n }\n\n GeoJson.prototype.addLayer.call(this, layer)\n }", "function initBasemapLayerTiles() {\n // overlayDescription = my.InitOverlay(my.descriptionContainer);\n\n // Init osmTileLayer base map\n osmTileLayer = new TileLayer({\n name: 'osmTileLayer',\n crossOriginKeyword: 'anonymous',\n source: new OSM(),\n });\n osmTileLayerMini = new TileLayer({\n name: 'osmTileLayerMini',\n crossOriginKeyword: 'anonymous',\n source: new OSM(),\n });\n\n // Init esriWSPTileLayer base map\n esriWSPTileLayer = new TileLayer({\n name: 'esriWSPTileLayer',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/0\">ArcGIS World Street Map</a>'],\n // // rendermode: 'image',\n url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',\n }),\n });\n esriWSPTileLayerMini = new TileLayer({\n name: 'esriWSPTileLayerMini',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/0\">ArcGIS World Street Map</a>'],\n // // rendermode: 'image',\n url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',\n }),\n });\n\n // Init esriWITileLayer base map (Satelite Images)\n esriWITileLayer = new TileLayer({\n name: 'esriWITileLayer',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/0\">ArcGIS World Imagery Map</a>'],\n // rendermode: 'image',\n url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n }),\n });\n esriWITileLayerMini = new TileLayer({\n name: 'esriWITileLayerMini',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/0\">ArcGIS World Imagery Map</a>'],\n // rendermode: 'image',\n url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',\n }),\n });\n\n blackTileLayer = new TileLayer({\n name: 'blackTileLayer',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> &copy; <a href=\"http://cartodb.com/attributions\">CartoDB</a>'],\n // rendermode: 'image',\n url: 'http://{a-c}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',\n }),\n });\n blackTileLayerMini = new TileLayer({\n name: 'blackTileLayerMini',\n crossOriginKeyword: 'anonymous',\n source: new XYZ({\n attributions: ['&copy; <a href=\"http://www.openstreetmap.org/copyright\">OpenStreetMap</a> &copy; <a href=\"http://cartodb.com/attributions\">CartoDB</a>'],\n // rendermode: 'image',\n url: 'http://{a-c}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',\n }),\n });\n }", "addParcelsLayer(layerURL) {\n var featureLayer = new FeatureLayer(layerURL, {\n model: /*FeatureLayer.MODE_ONDEMAND,//*/FeatureLayer.MODE_SELECTION,\n outFields: ['PARCEL_ID']\n });\n\n this.get('layersMap').set('parcelsLayer', featureLayer);\n this.get('map').addLayer(featureLayer);\n }", "function addJobTypesToMap(jobTypes, layers, overlaysMaps) {\n var controlRegion = new L.LayerGroup();\n layers.push(controlRegion);\n jobTypes.forEach(function (jobType) {\n switch (jobType.var_name) {\n case \"arch\":\n arch = L.icon({\n iconUrl: jobType.iconUrl,\n shadowUrl: jobType.shadowUrl,\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n });\n controlArch = new L.LayerGroup();\n layers.push(controlArch);\n var htmlImageArch = \"<img src='{0}' class='icon_legend'/> <span class='my-layer-item'>{1}</span>\".format(jobType.iconUrl, jobType.name);\n overlaysMaps[htmlImageArch] = controlArch;\n\n break;\n case \"gis\":\n gis = L.icon({\n iconUrl: jobType.iconUrl,\n shadowUrl: jobType.shadowUrl,\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n });\n controlGis = new L.LayerGroup();\n layers.push(controlGis);\n var htmlImageGis = \"<img src='{0}' class='icon_legend'/> <span class='my-layer-item'>{1}</span>\".format(jobType.iconUrl, jobType.name);\n overlaysMaps[htmlImageGis] = controlGis;\n break;\n case \"civil\":\n civil = L.icon({\n iconUrl: jobType.iconUrl,\n shadowUrl: jobType.shadowUrl,\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n });\n controlCivil = new L.LayerGroup();\n layers.push(controlCivil);\n var htmlImageCivil = \"<img src='{0}' class='icon_legend'/> <span class='my-layer-item'>{1}</span>\".format(jobType.iconUrl, jobType.name);\n overlaysMaps[htmlImageCivil] = controlCivil;\n break;\n case \"geodesy\":\n geodesy = L.icon({\n iconUrl: jobType.iconUrl,\n shadowUrl: jobType.shadowUrl,\n iconSize: [25, 41],\n iconAnchor: [12, 41],\n popupAnchor: [1, -34],\n shadowSize: [41, 41]\n });\n controlGeodesy = new L.LayerGroup();\n layers.push(controlGeodesy);\n var htmlImageGeodesy = \"<img src='{0}' class='icon_legend'/> <span class='my-layer-item'>{1}</span>\".format(jobType.iconUrl, jobType.name);\n overlaysMaps[htmlImageGeodesy] = controlGeodesy;\n break;\n default:\n return\n }\n\n\n });\n}", "async loadDataLayer(layer) {\n // Our data layers put a URL in the .source.data field. We'll fetch that\n // and then inline the resulting GeoJSON as a new source.\n //\n const sourceUrl = layer.getIn([\"source\", \"data\"]);\n const sourceId = `${layer.get(\"id\")}-source`;\n\n const response = await fetch(sourceUrl);\n const geojson = await response.json();\n\n // Convert layer w/ source url to a source + layer style spec\n //\n const newStyle = immutable({\n sources: {\n [sourceId]: layer.get(\"source\").set(\"data\", geojson)\n },\n layers: [\n layer.set(\"source\", sourceId)\n ]\n });\n\n // Add new source + layer style to the map\n //\n this.newState(state =>\n state.update(\"mapStyle\", mapStyle =>\n mergeMapStyle(mapStyle, newStyle)));\n }", "_populateLayer(layer, props) {\n\t\tlayer.addData(props.data);\n\t\tthis._addIcons(layer);\n\t\treturn layer;\n\t}", "initMap(entries){\n //Destroy the old map so we can reload a new map\n var map = this.get('map');\n\n var tpkLayer = new TPKLayer();\n\n tpkLayer.on(\"progress\", function (evt) {\n console.log(\"TPK loading...\" + evt);\n });\n tpkLayer.extend(entries);\n\n tpkLayer.map = map;\n map.addLayer(tpkLayer, 0);\n }", "function locations(collections) {\n\tcollections.forEach(function(datass) {\n\t\taddMarkerPoints(datass.x,datass.y);\n\t});\n}", "function addMapFeatures(map, popup) {\n map.dragRotate.disable(); // Disable map rotation using right click + drag.\n map.touchZoomRotate.disableRotation(); // Disable map rotation using touch rotation gesture.\n\n map.addControl(\n new maplibregl.NavigationControl({\n showCompass: false,\n })\n );\n\n map.on(\"load\", async function () {\n let partnerHubs = await fetchData(\"assets/data_source/partner_hubs.json\");\n let sponsors = await fetchData(\"assets/data_source/sponsors.json\");\n //let stakeholders = await fetchData(\"assets/data_source/stakeholders.json\");\n let corePartners = await fetchData(\"assets/data_source/core_partners.json\");\n let countiesCentre = await fetchData(\n \"assets/data_source/counties_centre.json\"\n );\n\n let startupsSupported = await fetchData(\n \"assets/data_source/startups_supported_counties.json\"\n );\n let hubMembers = await fetchData(\n \"assets/data_source/members_counties.json\"\n );\n let networkConnections = await fetchData(\n \"assets/data_source/network_connections_counties.json\"\n );\n\n let startupsSupportedCount = countUniqueCounties(\n startupsSupported,\n \"Startups\"\n );\n\n let startups_supported_cluster_data = convertToClusterPoints(\n startupsSupportedCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"startups-supported\",\n \"startups_supported_cluster\",\n startups_supported_cluster_data,\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"#7CB9E8\", // Aero\n \"#7CB9E8\", // Aero\n \"#C0E8D5\", // Aero Blue\n \"#EFDECD\", // Almond\n \"#F19CBB\", // Amaranth Pink\n \"#3DDC84\", // Android Green\n \"#FBCEB1\", // Apricot\n \"#7FFFD4\" // Aquamarine\n );\n\n let hubMembersCount = countUniqueCounties(hubMembers, \"Members\");\n\n let hub_members_cluster_data = convertToClusterPoints(\n hubMembersCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"hub_members\",\n \"hub_members_cluster\",\n hub_members_cluster_data,\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"#E4D00A\", // Citrine\n \"#E4D00A\", // Citrine\n \"#E9D66B\", // Arylide yellow\n \"#FF9966\", // Atomic tangerine\n \"#A1CAF1\", // Baby blue eyes\n \"#FF91AF\", // Baker-Miller pink\n \"#FAE7B5\", // Banana Mania\n \"#F5F5DC\" // Beige\n );\n\n let networkConnectionsCount = countUniqueCounties(\n networkConnections,\n \"Connections\"\n );\n\n let network_connections_cluster_data = convertToClusterPoints(\n networkConnectionsCount,\n countiesCentre\n );\n\n addCluster(\n map,\n \"network_connections\",\n \"network_connections_cluster\",\n network_connections_cluster_data,\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"#FFE4C4\", // Bisque\n \"#FFE4C4\", // Bisque\n \"#FE6F5E\", // Bittersweet\n \"#BFAFB2\", // Black shadows\n \"#DE5D83\", // Blush\n \"#D891EF\", // Bright lilac\n \"#5F9EA0\", // Cadet Blue\n \"#ACE1AF\" // Celadon\n );\n\n createHubMarkers(partnerHubs, map, \"partner-hub-markers\");\n\n createMarkers(\n sponsors,\n map,\n \"sponsor-markers\",\n \"sponsor-markers\",\n \"assets/images/sponsors_marker.svg\"\n );\n\n createCoreMarkers(corePartners, map, \"core-partner-markers\");\n\n hideAllLayers(map, [\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"partner-hub-markers\",\n \"sponsor-markers\",\n \"core-partner-markers\",\n ]);\n });\n\n toggleInput(\"partner-hub-markers\", map);\n toggleInput(\"sponsor-markers\", map);\n toggleInput(\"core-partner-markers\", map);\n\n toggleLayers(\n map,\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"startups-supported\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n toggleLayers(\n map,\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"hub-members\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n toggleLayers(\n map,\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\",\n \"network-connections\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\"\n );\n\n hideLayer(\n map,\n \"show_basemap\",\n \"startups_supported_cluster\",\n \"startups_supported_cluster_count\",\n \"startups_supported_unclustered_point\",\n \"hub_members_cluster\",\n \"hub_members_cluster_count\",\n \"hub_members_unclustered_point\",\n \"network_connections_cluster\",\n \"network_connections_cluster_count\",\n \"network_connections_unclustered_point\"\n );\n\n addPopup(map, \"partner-hub-markers\", popup);\n addPopup(map, \"sponsor-markers\", popup);\n addPopup(map, \"core-partner-markers\", popup);\n}", "function addDealAreasToLayerControl(map, dbDealAreas) {\n // iterate over dictionary\n var layerDictionary = [];\n var areaLayers = [];\n $.each(dbDealAreas, function (key, polygon) { // method doku: http://api.jquery.com/jquery.each/\n var coords = polygon.coordinates;\n var coordsTransformed;\n if (polygon.type === 'Polygon') {\n coordsTransformed = coords.map(function(c) {\n return L.GeoJSON.coordsToLatLngs(c);\n });\n } else if (polygon.type === 'MultiPolygon') {\n coordsTransformed = coords.map(function(c2) {\n return c2.map(function(c1) {\n return L.GeoJSON.coordsToLatLngs(c1);\n })\n });\n }\n var polygonL = L.polygon(\n coordsTransformed,\n {\n color: getPolygonColorByLabel(key)\n });\n areaLayers.push(polygonL);\n\n map.addLayer(polygonL); // polygons are initially added to the map\n layerDictionary[key] = polygonL;\n });\n\n // add Layers to layer control\n // try: https://gis.stackexchange.com/questions/178945/leaflet-customizing-the-layerswitcher\n // http://embed.plnkr.co/Je7c0m/\n if (!jQuery.isEmptyObject(layerDictionary)) { // only add layer control if layers aren't empty\n L.control.layers([], layerDictionary).addTo(map);\n }\n return areaLayers;\n}", "function addQueryLayerToMap(jsonurl, layername, values){\n\t//colours = addLyrCols(values);\n\tvar fSource = new ol.source.Vector({\n\t\turl: jsonurl,\n\t\tformat: new ol.format.GeoJSON({\n\t\t\tdefaultDataProjection: 'EPSG:27700'\n\t\t})\n\t});\n\t\n\tvar fLayer = new ol.layer.Vector({\n\t\ttitle: layername,\n\t\tsource: fSource,\n\t\tstyle: styleFunction\n\t});\n\tmap.addLayer(fLayer);\n\n\t\n}", "function loadMap(stores) {\n map.on('load', function () {\n map.addLayer({\n id: 'points',\n type: 'symbol',\n source: {\n type: 'geojson',\n data: {\n type: 'FeatureCollection',\n features: stores\n }\n },\n layout: {\n 'icon-image': '{icon}-15',\n 'icon-size': 1.5,\n 'text-field': '{placeId}',\n 'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],\n 'text-offset': [0, 0.9],\n 'text-anchor': 'top'\n },\n\n });\n\n // When a click event occurs on a feature in the places layer, open a popup at the\n // location of the feature, with description HTML from its properties.\n map.on('click', 'points', function (e) {\n var coordinates = e.features[0].geometry.coordinates.slice();\n var place = e.features[0].properties.place;\n var about = e.features[0].properties.description;\n\n\n // Ensure that if the map is zoomed out such that multiple\n // copies of the feature are visible, the popup appears\n // over the copy being pointed to.\n while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {\n coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;\n }\n\n new mapboxgl.Popup()\n .setLngLat(coordinates)\n .setHTML('<h3>' + place + '</h3>' + '<p>' + about + '</p>')\n .addTo(map);\n });\n\n // Change the cursor to a pointer when the mouse is over the places layer.\n map.on('mouseenter', 'points', function () {\n map.getCanvas().style.cursor = 'pointer';\n });\n\n // Change it back to a pointer when it leaves.\n map.on('mouseleave', 'points', function () {\n map.getCanvas().style.cursor = '';\n });\n\n });\n }", "function addElementsToMap(map, overlaysMaps) {\n L.control.coordinates({\n position: \"topright\",\n decimals: 4,\n decimalSeperator: \".\",\n labelTemplateLat: \"Latitude: {y}\",\n labelTemplateLng: \"Longitude: {x} | WGS84\",\n enableUserInput: true,\n useDMS: false,\n useLatLngOrder: true\n }).addTo(map);\n\n L.control.layers(null, overlaysMaps, {\n collapsed: false,\n position: 'bottomright',\n autoZIndex: true\n }).addTo(map);\n\n L.control.scale().addTo(map);\n\n}", "function setMapOnAll(map, layer) {\r\n for (var i = 0; i < layer.length; i++) {\r\n layer[i].setMap(map);\r\n }\r\n}", "function addSatImages(data) {\n\tvar googleMapsApiKey = 'AIzaSyBLtOssY47tO3dbrV6liAY5X7LhVjTaNw8'\n\tvar zoomLevel = '17';\n\tvar googleMapsRootURL = 'https://maps.googleapis.com/maps/api/staticmap?';\n\tvar size = '220x220';\n\tvar mapType = 'satellite';\n\tfor (var i = data.length - 1; i > -1; i--) {\n\t\tvar strikeLat = data[i]['lat'];\n\t\tvar strikeLon = data[i]['lon'];\n\t\tvar region = data[i]['location'];\n\t\tvar country = data[i]['country'];\n\t\tvar date = getLocalDate(data[i]['date']);\n\t\tvar narrative = data[i]['narrative'];\n\t\tvar deaths = data[i]['deaths'];\n\t\tvar injuries = data[i]['injuries'];\n\n\t\tif (strikeLat != \"\" && strikeLon != \"\") {\n\t\t\tvar mapURL = googleMapsRootURL + 'center=' + strikeLat + ',' + strikeLon\n\t\t\t\t\t\t\t+ '&zoom=' + zoomLevel + '&size=' + size + '&maptype='\n\t\t\t\t\t\t\t+ mapType + '&key=' + googleMapsApiKey;\n\t\t\t$('#sat-image-grid').append(\n\t\t\t\t'<div class=\"sat-image-container\">' +\n\t\t\t\t\t'<div class=\"sat-image-overlay\">' +\n\t\t\t\t\t\t'<div class=\"sat-image-overlay-text\">' +\n\t\t\t\t\t\t\t\"<b>Location: </b>\" + region + \", \" + country\n\t\t\t\t\t\t\t+ \"<br>\"\n\t\t\t\t\t\t\t+ \"<br><b>Date: </b>\" + date\n\t\t\t\t\t\t\t+ \"<br>\" + \"<b>Narrative: </b>\" + narrative\n\t\t\t\t\t\t\t+ \"<br><br>\"\n\t\t\t\t\t\t\t+ \"<b>Deaths: </b>\" + deaths\n\t\t\t\t\t\t\t+ \"&nbsp;&nbsp;|&nbsp;&nbsp;\"\n\t\t\t\t\t\t\t+ \"<b>Injuries: </b>\" + injuries +\n\t\t\t\t\t\t'</div>' +\n\t\t\t\t\t'</div>' +\n\t\t\t\t\t'<img class=\"sat-image\" src=' + mapURL + '>' +\n\t\t\t\t'<div>'\n\t\t\t);\n\t\t}\n\t}\n}", "function addTopoData(topoData) {\r\n // Add data to the layer\r\n topoLayer.addData(topoData);\r\n // Add layer to the map\r\n topoLayer.addTo(map);\r\n\r\n // Color each layer according to attribute value\r\n // And add some event listeners to each layer\r\n topoLayer.eachLayer(handleLayer);\r\n\r\n createLegend();\r\n // Create a legend for the map if the screen size is large enough\r\n if ($(window).width() < 768) {\r\n $('.legend-control-container').hide();\r\n }\r\n // Create window event listener to switch legend on/off depending on window width\r\n window.addEventListener(\"resize\", (function() {\r\n if ($(window).width() < 768) {\r\n $('.legend-control-container').hide();\r\n } else if ($(window).width() >= 768) {\r\n $('.legend-control-container').show();\r\n }\r\n }))\r\n\r\n }", "addGEEImage(sceneId) {\n map.addSource('gee-source', {\n 'type': 'raster',\n 'tiles': [\n 'https://geeimageserver.appspot.com/ogc?service=WMS&request=GetMap&version=1.1.1&styles=&format=image%2Fpng&transparent=false&layers=[' + sceneId + ']&srs=EPSG%3A3857&bbox={bbox-epsg-3857}'\n ],\n 'tileSize': 256\n });\n map.addLayer({\n 'id': 'gee-layer',\n 'type': 'raster',\n 'source': 'gee-source',\n 'paint': {}\n },\n \"gl-draw-polygon-fill-inactive.cold\");\n }", "function buildMap(data, data2) {\n $(\"#mapcontainer\").empty();\n $(\"#mapcontainer\").append(`<div id=\"map\"></div>`);\n // Step 0: Create the Tile Layers\n // Add a tile layer\n var dark_mode = L.tileLayer(\"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>\",\n tileSize: 512,\n maxZoom: 18,\n zoomOffset: -1,\n id: \"mapbox/dark-v10\",\n accessToken: API_KEY\n });\n\n var light_mode = L.tileLayer(\"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>\",\n tileSize: 512,\n maxZoom: 18,\n zoomOffset: -1,\n id: \"mapbox/light-v10\",\n accessToken: API_KEY\n });\n\n var satellite_mode = L.tileLayer(\"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>\",\n tileSize: 512,\n maxZoom: 18,\n zoomOffset: -1,\n id: \"mapbox/satellite-v9\",\n accessToken: API_KEY\n });\n\n // STEP 1: INIT MAP\n // Create a map object\n myMap = L.map(\"map\", {\n center: [31.5, -100],\n zoom: 6,\n layers: dark_mode\n });\n\n // Step 2: Build Data\n var county_list = [];\n data.features.forEach(function(county) {\n var polygon = L.geoJSON(county, {\n style: (feature) => getStyle(feature, data2),\n onEachFeature: (feature, layer) => onEachFeature(feature, layer, data2)\n });\n county_list.push(polygon);\n });\n\n var county_group = L.layerGroup(county_list);\n county_group.addTo(myMap);\n var column = $(\"#column\").val();\n var minimum = data2.map(x => parseFloat(x[column].replace(/,/g, '')));\n minimum = minimum.filter(x => x);\n minimum = Math.min(...minimum);\n // Create Layer Legend\n var baseMaps = {\n \"Light Mode\": light_mode,\n \"Dark Mode\": dark_mode,\n \"Satellite\": satellite_mode\n };\n\n var overlayMaps = {\n \"County\": county_group,\n };\n // Slap Layer Legend onto the map\n L.control.layers(baseMaps, overlayMaps).addTo(myMap);\n\n // Set up the legend\n var legend = L.control({ position: \"bottomright\" });\n legend.onAdd = function() {\n var div = L.DomUtil.create(\"div\", \"info legend\");\n\n // create legend as raw html\n var legendInfo = `<h2 style = \"margin-bottom:5px\"> ${column} </h2>\n <div>\n <div style = \"background:yellow;height:10px;width:10px;display:inline-block\"> </div> \n <div style = \"display:inline-block\"> Less than 1,000 doses</div>\n </div> \n <div>\n <div style = \"background:orange;height:10px;width:10px;display:inline-block\"> </div> \n <div style = \"display:inline-block\">1,000 - 10,000 doses</div>\n </div> \n <div>\n <div style = \"background:red;height:10px;width:10px;display:inline-block\"></div> \n <div style = \"display:inline-block\">10,000 - 100,000 doses</div>\n </div>\n <div>\n <div style = \"background:darkred;height:10px;width:10px;display:inline-block\"></div>\n <div style = \"display:inline-block\">More than 100,000 doses</div>\n </div>`;\n div.innerHTML = legendInfo;\n return (div)\n }\n\n // Adding legend to the map\n legend.addTo(myMap);\n\n}", "function addTo(map, layerStyle) {\n if (map && properties.layer && !status.layerAdded) {\n layerStyle = {\"color\":\"rgb(200,200,200)\", \"fill\": false, \"weight\": 2 } || layerStyle;\n status.layerAdded = true;\n properties.layer.addTo(map);\n properties.layer.setStyle(layerStyle);\n }\n }", "function addGeoJsonToMap(v){\n\t\t\t$('#' + spinnerID).hide();\n\t\t\t$('#' + visibleLabelID).show();\n\n\t\t\tif(layer.currentGEERunID === geeRunID){\n if(v === undefined){loadFailure()}\n\t\t\t\tlayer.layer = new google.maps.Data();\n // layer.viz.icon = {\n // path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,\n // scale: 5,\n // strokeWeight:2,\n // strokeColor:\"#B40404\"\n // }\n\t\t layer.layer.setStyle(layer.viz);\n\t\t \n\t\t \tlayer.layer.addGeoJson(v);\n if(layer.viz.clickQuery){\n map.addListener('click',function(){\n infowindow.setMap(null);\n })\n layer.layer.addListener('click', function(event) {\n console.log(event);\n infowindow.setPosition(event.latLng);\n var infoContent = `<table class=\"table table-hover bg-white\">\n <tbody>`\n var info = event.feature.h;\n Object.keys(info).map(function(name){\n var value = info[name];\n infoContent +=`<tr><th>${name}</th><td>${value}</td></tr>`;\n });\n infoContent +=`</tbody></table>`;\n infowindow.setContent(infoContent);\n infowindow.open(map);\n }) \n }\n\t\t \tfeatureObj[layer.name] = layer.layer\n\t\t \t// console.log(this.viz);\n\t\t \n\t\t \tif(layer.visible){\n\t\t \tlayer.layer.setMap(layer.map);\n\t\t \tlayer.rangeOpacity = layer.viz.strokeOpacity;\n\t\t \tlayer.percent = 100;\n\t\t \tupdateProgress();\n\t\t \t$('#'+layer.legendDivID).show();\n\t\t \t}else{\n\t\t \tlayer.rangeOpacity = 0;\n\t\t \tlayer.percent = 0;\n\t\t \t$('#'+layer.legendDivID).hide();\n\t\t \t\t}\n\t\t \tsetRangeSliderThumbOpacity();\n\t\t \t}\n \t\t}", "function getData() {\n // Get ESRI WFS as GeoJSON and Add to Map\n\n /////*** BOUNDARY LAYERS ****\\\\\\\\\n var hawkcreekbndry = L.esri.featureLayer({\n url: a_hwkCreekBndry,\n style: function () {\n return {\n color: \"#70ca49\",\n weight: 2\n };\n }\n }).addTo(map);\n\n var cnty = L.esri.featureLayer({\n url: a_cnty,\n style: function () {\n return {\n color: \"#7256E8\",\n weight: 2\n };\n }\n }).addTo(map);\n\n var huc2 = L.esri.featureLayer({\n url: a_huc2,\n });\n\n var huc4 = L.esri.featureLayer({\n url: a_huc4,\n });\n var huc6 = L.esri.featureLayer({\n url: a_huc6,\n });\n var huc8 = L.esri.featureLayer({\n url: a_huc8,\n });\n var huc10 = L.esri.featureLayer({\n url: a_huc10,\n });\n var huc12 = L.esri.featureLayer({\n url: a_huc12,\n });\n var huc14 = L.esri.featureLayer({\n url: a_huc14,\n });\n var huc16 = L.esri.featureLayer({\n url: a_huc16,\n });\n\n\n\n ////// *** hydrography layers *** /////\n\n var fEMAflood = L.esri.featureLayer({\n url: a_fEMAflood,\n });\n\n var imptStrm = L.esri.featureLayer({\n url: a_imptStrm,\n });\n var impLks = L.esri.featureLayer({\n url: a_impLks,\n });\n var altwtr = L.esri.featureLayer({\n url: a_altwtr,\n });\n var phos = L.esri.featureLayer({\n url: a_phos,\n });\n var trout = L.esri.featureLayer({\n url: a_trout,\n });\n var wellhead = L.esri.featureLayer({\n url: a_wellhead,\n });\n var wtrVul = L.esri.featureLayer({\n url: a_wtrVul,\n });\n\n ////// *** landstatus layers *** /////\n\n var gAP_DNR = L.esri.featureLayer({\n url: a_gAP_DNR,\n });\n var gAP_State = L.esri.featureLayer({\n url: a_gAP_State,\n });\n var gAP_Cnty = L.esri.featureLayer({\n url: a_gAP_Cnty,\n });\n var gAP_Fed = L.esri.featureLayer({\n url: a_gAP_Fed,\n });\n var natPra = L.esri.featureLayer({\n url: a_natPra,\n });\n\n\n ////// *** index layers *** /////\n\n var bioIndex = L.esri.featureLayer({\n url: a_bioIndex,\n });\n var hydIndex = L.esri.featureLayer({\n url: a_hydIndex,\n });\n var geoIndex = L.esri.featureLayer({\n url: a_geoIndex,\n });\n var conIndex = L.esri.featureLayer({\n url: a_conIndex,\n });\n var wQIndex = L.esri.featureLayer({\n url: a_wQIndex,\n });\n var combIndex = L.esri.featureLayer({\n url: a_combIndex,\n });\n\n\n\n /////*** Misc. layers ***/////\n\n var natPlnt = L.esri.featureLayer({\n url: a_natPlnt,\n });\n var mBSbio = L.esri.featureLayer({\n url: a_mBSbio,\n });\n var cONUS = L.esri.featureLayer({\n url: a_cONUS,\n });\n var dNRCatch = L.esri.featureLayer({\n url: a_dNRCatch,\n });\n var bedrockPoll = L.esri.featureLayer({\n url: a_bedrockPoll,\n });\n var nitrCnty = L.esri.featureLayer({\n url: a_nitrCnty,\n });\n var nitrTwn = L.esri.featureLayer({\n url: a_nitrTwn,\n });\n\n\n var overlays = {\n \"Watershed Boundary\": hawkcreekbndry,\n \"Counties\": cnty,\n \"HUC 2\": huc2,\n \"HUC 4\": huc4,\n \"HUC 6\": huc6,\n \"HUC 8\": huc8,\n \"HUC 10\": huc10,\n \"HUC 12\": huc12,\n \"HUC 14\": huc14,\n \"HUC 16\": huc16,\n \"100 YR Floodplain\": fEMAflood,\n \"Impaired Streams\": imptStrm,\n \"Impaired Lakes\": impLks,\n \"Altered Watercourses\": altwtr,\n \"Lake Phosophorus Sensitivity Significance\": phos,\n \"Trout Streams\": trout,\n \"Wellhead Protection Areas\": wellhead,\n \"Drinking Water Supply Vulnerability\": wtrVul,\n\n\n \"GAP DNR Land\": gAP_DNR,\n \"GAP State Land\": gAP_State,\n \"GAP County Land\": gAP_Cnty,\n \"GAP Federal Land\": gAP_Fed,\n \"Natice Prairies\": natPra,\n\n // index layers //\n \"Bio Index Mean\": bioIndex,\n \"Hyd Index Mean\": hydIndex,\n \"Geo Index Mean\": geoIndex,\n \"Con Index Mean\": conIndex,\n \"WQ Index Mean\": wQIndex,\n \"Combined Index Mean\": combIndex,\n\n // Misc. layers\n\n \"Native Plants\": natPlnt,\n \"MBS Biodiversity\": mBSbio,\n \"NWI\": cONUS,\n \"Catchments\": dNRCatch,\n \"Bedrock Pollution Sensitivity\": bedrockPoll,\n \"Nitrate per County\": nitrCnty,\n \"Nitrate per Township\": nitrTwn\n\n }\n L.control.layers(null, overlays).addTo(map);\n}", "function addWMSLayer()\n{\n\t//Get Selected Layer\n\tvar selLayer = '';\n\tvar elements = document.getElementsByName('rbGroup');\n\tfor(elemIndex = 0 ; elemIndex < elements.length; elemIndex++)\n\t{\n\t\tvar element = elements[elemIndex];\n\t\tif(element.checked)\n\t\t{\n\t\t\tselLayer = element.value;\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t//INitialize the WMS Layer with the default dimension values\n\twmsLayer.initializeDimensionParams(selLayer);\n\tmap.addLayer(wmsLayer);\n\t\n \n //Get Dimension Values from WMS Layer\n var dimensions = wmsLayer.getDimensions();\n \n if(dimensions.length > 2)\n \talert(\"More than two dimensions represented within WMS Service. Only the \\\"time\\\" and one other dimension can be represented\");\n \n timeDim = '';\n nDim = '';\n for(index = 0; index < dimensions.length; index++)\n {\n \tvar dim = dimensions[index];\n \tif(dim.indexOf(\"time\") != -1 || dim.indexOf(\"date\") != -1 )\n \t\ttimeDim = dim;\n \telse\n \t\tnDim = dim;\n }\n \n require([\"dojo/dom-style\"], function(domStyle){\n //Only show the Time/Event Slider when there is a time dimension\n if(timeDim != '')\n {\n \tif(eventSliderOb == null)\n \t{\n \t\teventSliderOb = new EventSlider();\n \t\tdocument.addEventListener(\"EventSliderDateChanged\",updateMapTime,false);\n \t}\n \n \tvar timeValues = wmsLayer.getDimensionValues(timeDim);\n \teventSliderOb.setTimeField(timeDim);\n \teventSliderOb.setTimeSlices(timeValues);\n \teventSliderOb.generateChart();\n \t\n \t//Show the Event Slider.\n \tvar footerElem = document.getElementById('footer');\n \tfooterElem.style.visibility = 'visible';\n }\n \n //Only show the n Dim Slider when there is a dimension other than time\n if(nDim != '')\n {\n \tif(dimSliderOb == null)\n \t{\n \t\tdimSliderOb = new nDimSlider();\n \t\tdocument.addEventListener(\"DimSliderDateChanged\",updateDimension,false);\n \t}\n \tvar dimValues = wmsLayer.getDimensionValues(nDim);\n \t\n \tvar dimParams = wmsLayer.getDimensionProperties(nDim);\n \tdimSliderOb.setDimensionField(nDim);\n \tdimSliderOb.setDimensionUnits(dimParams.units);\n \tdimSliderOb.setDefaultValue(dimParams.defaultValue);\n \t\n \t//We want to check if it's a depth value, because then the dim slider inverses the values'\n \tvar isDepthValue = false;\n \tif(nDim.toLowerCase().indexOf('depth') != -1)\n \t\tisDepthValue = true;\n \t\t\n \tdimSliderOb.setSlices(dimValues,isDepthValue);\n \tdimSliderOb.createDimensionSlider();\n \t\n \t//Show the Dimension Slider.\n \tvar leftChartElem = document.getElementById('leftChart');\n \t\tleftChartElem.style.visibility = 'visible';\n }\n\t\n\t\t//We want to make sure that the current time is shown\n\t updateMapTime();\n \n \t//Now that the application is fully loaded, we can hide the load form.\n \tvar spashConElem = document.getElementById('splashCon');\n \t\tdomStyle.set(spashConElem, 'display', 'none');\n\t});\n}", "constructor(map, uniqueId, mapBoxSourceId, addBeforeLayer) {\n this.map = map.map || map;\n this.uniqueId = uniqueId;\n this.mapBoxSourceId = mapBoxSourceId;\n\n // Add the colored fill area\n map.addLayer(\n {\n id: this.uniqueId+'fillpoly',\n type: 'fill',\n source: this.mapBoxSourceId,\n paint: {\n 'fill-antialias': true,\n 'fill-outline-color': [\n 'case',\n ['boolean', ['feature-state', 'hover'], false],\n 'rgba(0, 0, 0, 0.9)',\n 'rgba(100, 100, 100, 0.4)'\n ],\n 'fill-opacity': [\n 'case',\n ['boolean', ['feature-state', 'hover'], false],\n 0.6,\n FILL_OPACITY\n ]\n }\n },\n addBeforeLayer\n );\n }", "function addToView(layer) {\n view.map.add(layer);\n}", "function activateAddLayerUrl(options) {\n mapImplementation.ActivateAddLayerUrl(options);\n }", "function updateLayer(){\n // Get dem name from selector\n var dem_name = c.selectDEM.selector.getValue();\n // Filter ImageCollection to current dem\n var dem = m.dem_col.filterMetadata('DEM_Type', 'equals', dem_name).first();\n // Get value from layer selector\n var layer_option = c.selectLayer.selector.getValue();\n // Get date from date selector\n var current_date = ee.Date(c.selectDate.aDate.getValue());\n // Execute solar functions\n var solar_postion = Imported.solar_fun(current_date);\n var solar_surface = Imported2.solar_surface_fun(current_date, null, dem);\n // Extract relevant variables\n var time_zone = solar_postion.select('time_zone');\n var ele = solar_postion.select('ele');\n var zenith = solar_postion.select('zenith');\n var azimuth = solar_postion.select('azimuth');\n var surface_ele = solar_surface.select('surface_ele');\n var surface_zenith = solar_surface.select('surface_zenith');\n var surface_azimuth = solar_surface.select('surface_azimuth');\n // Execute terrain functions\n var hill = ee.Terrain.hillshade(dem);\n var slo = ee.Terrain.slope(dem);\n var asp = ee.Terrain.aspect(dem);\n // Add layer to map\n if (layer_option == 'Time Zone'){\n // Define visualization\n var layer3 = ui.Map.Layer({\n eeObject: time_zone,\n visParams: {min: -12, max: 12},\n name: 'Time Zone'\n });\n // Add layer to map\n c.map.layers().set(1, layer3); // Define nth layer\n } else if (layer_option == 'Solar Elevation') {\n // Define visualization\n var layer4 = ui.Map.Layer({\n eeObject: ele,\n visParams: {min: 0, max: 90},\n name: 'Solar Elevation'\n });\n // Add layer to map\n c.map.layers().set(1, layer4); // Define nth layer\n } else if (layer_option == 'Solar Zenith') {\n // Define visualization\n var layer5 = ui.Map.Layer({\n eeObject: zenith,\n visParams: {min: 0, max: 90},\n name: 'Solar Zenith'\n });\n // Add layer to map\n c.map.layers().set(1, layer5); // Define nth layer\n } else if (layer_option == 'Solar Azimuth') {\n // Define visualization\n var layer6 = ui.Map.Layer({\n eeObject: azimuth,\n visParams: {min: 90, max: 270},\n name: 'Solar Azimuth'\n });\n // Add layer to map\n c.map.layers().set(1, layer6); // Define nth layer\n } else if (layer_option == 'Solar-Surface Elevation') {\n // Define visualization\n var layer7 = ui.Map.Layer({\n eeObject: surface_ele,\n visParams: {min: 0, max: 90},\n name: 'Solar-Surface Elevation'\n });\n // Add layer to map\n c.map.layers().set(1, layer7); // Define nth layer\n } else if (layer_option == 'Solar-Surface Zenith') {\n // Define visualization\n var layer8 = ui.Map.Layer({\n eeObject: surface_zenith,\n visParams: {min: 0, max: 90},\n name: 'Solar-Surface Zenith'\n });\n // Add layer to map\n c.map.layers().set(1, layer8); // Define nth layer\n } else if (layer_option == 'Solar-Surface Azimuth') {\n // Define visualization\n var layer9 = ui.Map.Layer({\n eeObject: surface_azimuth,\n visParams: {min: 0, max: 360},\n name: 'Solar-Surface Azimuth'\n });\n // Add layer to map\n c.map.layers().set(1, layer9); // Define nth layer\n } else if (layer_option == 'Slope') {\n // Define visualization\n var layer10 = ui.Map.Layer({\n eeObject: slo,\n visParams: {min: 0, max: 90},\n name: 'Slope'\n });\n // Add layer to map\n c.map.layers().set(1, layer10); // Define nth layer\n } else if (layer_option == 'Aspect') {\n // Define visualization\n var layer11 = ui.Map.Layer({\n eeObject: asp,\n visParams: {palette: ['green', 'yellow', 'yellow', 'orange', 'orange', 'blue', 'blue', 'green'], min: 0, max: 360},\n name: 'Aspect'\n });\n // Add layer to map\n c.map.layers().set(1, layer11); // Define nth layer\n } else {\n // Define visualization\n var layer12 = ui.Map.Layer({\n eeObject: hill,\n visParams: {min: 0, max: 255},\n opacity: 0.3,\n name: 'Hillshade'\n });\n // Add layer to map\n c.map.layers().set(1, layer12); // Define nth layer\n }\n}", "function attachMaps() {\n\t\tif ($('.local-map').length < 1 || mapData[1] == '') {\n\t\t\treturn false;\n\t\t}\n\n\t\tvar latlng = new google.maps.LatLng(mapData[1], mapData[2]);\n\n\t\tvar zoomLevel = mapData[0];\n\n\t\tvar myOptions = {\n\t\t\tzoom: parseInt(zoomLevel),\n\t\t\tminZoom: 1,\n\t\t\tcenter: latlng,\n\t\t\tmapTypeId: google.maps.MapTypeId.ROADMAP,\n\t\t\tpanControl: false,\n\t\t\tzoomControl: true,\n\t\t\tmapTypeControl: false,\n\t\t\tscaleControl: true,\n\t\t\tstreetViewControl: true\n\t\t};\n\n\t\tvar map = new google.maps.Map(\n\t\t\tdocument.getElementById(\"map\"),\n\t\t\tmyOptions\n\t\t);\n\n\t\tonlyAddMarker(map, agencyLocation);\n\n\t\t$(window).resize(function() {\n\t\t\tmap.panTo(latlng);\n\t\t});\n\t}", "function updateDEM(){\n // Get dem name from selector\n var dem_name = c.selectDEM.selector.getValue();\n // Filter ImageCollection to current dem\n var dem = m.dem_col.filterMetadata('DEM_Type', 'equals', dem_name).first();\n // Define current min and max value\n var min = ee.Number.parse(c.selectMinMax.Min.getValue());\n var max = ee.Number.parse(c.selectMinMax.Max.getValue());\n // Define layer to map\n var layer = ui.Map.Layer({\n eeObject: dem,\n visParams: {palette: ['grey', 'lightgreen', 'khaki', 'brown', 'white'], min: min.getInfo(), max: max.getInfo()},\n name: dem_name\n });\n // Add layer to map\n c.map.layers().set(0, layer); // Define nth layer\n}", "function initMapParts(layers) { \n \n //The Search Filter class handles the user defined filters\n searchFilters = new SearchFilters();\n searchFilters.basicSearchChanged = updateFilteredSearch; //One of the filter parameters has changed\n searchFilters.advanceSearchChanged = updateAdanvceSearch;\n \n\n //The Provider List class builds the provider list on the left of the map\n providerList = new ProviderList();\n providerList.listItemSelected = openFeaturePopup //An Event that fires off when a user selects a provider item\n \n //A helper for working with the provider feature layer\n providerFeatureLayer = new ProviderFeatureLayer();\n \n //The Provider Feature Layer in the map.\n providerFS = layers[0].layer;\n \n //The event that is fired off when a feature is selected\n //In this case we want to select the provider list item when a feature is selected on the map\n providerFS.on(\"selection-complete\", featureServiceClicked); \n \n //We need the FeatureLayer for performing Searches, such as a drop down that populates with\n //results from a query\n searchFilters.setFeatureLayer(providerFS);\n\n //Add Geolocate Button\n geoLocate = new LocateButton({\n map: map\n }, dom.byId(\"LocateButton\"));\n geoLocate.startup();\n \n //Use Geolocation if available on the browser to find the current location\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition(showPosition);\n } \n }", "function createFeatures(earthquakeData) {\n \n function onEachFeature(feature, layer) {\n layer.bindPopup(\"<h3>\" + feature.properties.place +\n \"</h3><hr><p>\" + new Date(feature.properties.time) + \"</p>\");\n }\n\n // Read GeoJSON data, create circle markers, and add to earthquake layer group\n L.geoJSON(earthquakeData, {\n pointToLayer: function (feature, latlng) {\n return L.circleMarker(latlng, {\n radius: feature.properties.mag * 5,\n fillColor: chooseColour(feature.properties.mag),\n color: \"black\",\n weight: 0.5,\n opacity: 0.5,\n fillOpacity: 0.8\n });\n },\n onEachFeature: onEachFeature\n }).addTo(earthquakes);\n\n // Define street map layer\n var streetmap = L.tileLayer(\"https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors, <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox/streets-v11\",\n accessToken: API_KEY\n });\n\n // Define satellite map layer\n var satellitemap = L.tileLayer(\"https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors,\\\n <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.satellite\",\n accessToken: API_KEY\n });\n\n // Define outdoors map layer\n var outdoorsmap = L.tileLayer(\"https://api.mapbox.com/styles/v1/mapbox/outdoors-v9/tiles/256/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors,\\\n <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox/outdoors\",\n accessToken: API_KEY\n });\n\n // define greyscale map layer\n var lightmap = L.tileLayer(\"https://api.mapbox.com/styles/v1/mapbox/light-v9/tiles/256/{z}/{x}/{y}?access_token={accessToken}\", {\n attribution: \"Map data &copy; <a href=\\\"https://www.openstreetmap.org/\\\">OpenStreetMap</a> contributors,\\\n <a href=\\\"https://creativecommons.org/licenses/by-sa/2.0/\\\">CC-BY-SA</a>, Imagery © <a href=\\\"https://www.mapbox.com/\\\">Mapbox</a>\",\n maxZoom: 18,\n id: \"mapbox.light\",\n accessToken: API_KEY\n });\n\n // Define the baseMaps for the map types we created above\n var baseMaps = {\n \"Street Map\": streetmap,\n \"Satellite Map\": satellitemap,\n \"Outdoors Map\": outdoorsmap,\n \"Greyscale Map\": lightmap\n };\n\n // Read the tectonic Plate GeoJSON from the source URL, and add to faultLines layer group\n d3.json(\"https://raw.githubusercontent.com/fraxen/tectonicplates/master/GeoJSON/PB2002_boundaries.json\",\n function(platedata) {\n L.geoJson(platedata, {\n color: \"orange\",\n weight: 2\n }).addTo(faultLines);\n });\n\n // Create a new map\n var myMap = L.map(\"map\", {\n center: [\n 48.10, -100.10\n ],\n zoom: 3,\n layers: [streetmap, earthquakes, faultLines]\n });\n\n // create overlay map with the 2 data layers\n var overlayMaps = {\n \"Earthquakes\": earthquakes,\n \"Fault Lines\": faultLines,\n };\n\n // Add a layer control to the map\n L.control.layers(baseMaps, overlayMaps, {\n collapsed: false\n }).addTo(myMap);\n\n // function to set the earthquake circle size based on value of mag (magnitude)\n function chooseColour(mag) {\n if (mag > 5) {\n return \"red\";\n }\n else if (mag > 4){\n return \"orangered\";\n }\n else if (mag > 3){\n return \"orange\";\n }\n else if (mag > 2){\n return \"gold\";\n }\n else if (mag > 1){\n return \"yellow\"\n }\n else {\n return \"greenyellow\";\n }\n }\n\n // Create the legend control and set its position\n var legend = L.control({\n position: \"bottomright\"\n });\n\n // function to assign values to the legend, as well as color boxes (see style.css file)\n legend.onAdd = function (myMap) {\n\n var div = L.DomUtil.create('div', 'info legend'),\n grades = [0, 1, 2, 3, 4, 5],\n labels = [];\n\n // loop through our density intervals and generate a label with a colored square for each interval\n for (var i = 0; i < grades.length; i++) {\n div.innerHTML +=\n '<i style=\"background:' + chooseColour(grades[i] + 1) + '\"></i> ' +\n grades[i] + (grades[i + 1] ? '&ndash;' + grades[i + 1] + '<br>' : '+');\n }\n return div;\n };\n // add the legend to the map\n legend.addTo(myMap);\n\n}" ]
[ "0.7754036", "0.6964218", "0.6789085", "0.6779885", "0.6777212", "0.6599146", "0.64894867", "0.64444286", "0.6417326", "0.63529414", "0.630586", "0.62828875", "0.6275323", "0.6274869", "0.6261586", "0.62507325", "0.624012", "0.6146554", "0.61339027", "0.6123894", "0.6107965", "0.6092572", "0.60276467", "0.5967014", "0.59367335", "0.59315115", "0.5879489", "0.5860418", "0.5855296", "0.5841949", "0.583859", "0.58383346", "0.58229357", "0.58025026", "0.579336", "0.57777333", "0.5777427", "0.5762899", "0.5754024", "0.5750013", "0.57440114", "0.5740203", "0.57333636", "0.5729201", "0.57267714", "0.572039", "0.5714761", "0.571441", "0.571251", "0.57027215", "0.5698752", "0.5688688", "0.56838816", "0.568126", "0.5676277", "0.5668871", "0.5666533", "0.5665477", "0.5662744", "0.5636826", "0.5636288", "0.5630952", "0.562384", "0.56136316", "0.560778", "0.56067663", "0.56047857", "0.56022644", "0.5599497", "0.5589079", "0.55890083", "0.55890083", "0.5581676", "0.5572934", "0.55687475", "0.55661935", "0.55639976", "0.556254", "0.55561125", "0.5556046", "0.5552853", "0.5548644", "0.5546425", "0.5522026", "0.552", "0.5512", "0.55097765", "0.550417", "0.5503164", "0.5492996", "0.54829174", "0.54723215", "0.5470513", "0.54682755", "0.5467713", "0.54624665", "0.5460405", "0.5460168", "0.5456829", "0.54520106" ]
0.6617926
5
Sets event listeners for filtergroup
function setEventListeners() { var checkboxSmallLayers = [[$("[name='FWS']"), 'fws'], [$("[name='NPS']"), 'nps'], [$("[name='FS']"), 'fs'], [$("[name='BLM']"), 'blm'], [$("[name='wilderness-checkbox']"), 'wilderness']]; var checkboxLargeLayers = [[$("[name='climate-checkbox']"), 'climate'], [$("[name='wildness-checkbox']"), 'wildness'], [$("[name='amphib-checkbox'"), 'amphibian-layer'], [$("[name='fish-checkbox']"), 'fish-layer'], [$("[name='priority-checkbox']"), 'priority_index'], [$("[name='bird-checkbox']"),'bird-layer']]; var sliderArray = [[$('#wildnessSlider'), 'wildness', 'raster-opacity', 'wildnessSlider'], [$('#amphibSlider'), 'amphibian-layer', 'fill-opacity', 'amphibSlider'], [$('#fishSlider'), 'fish-layer', 'fill-opacity', 'fishSlider'], [$('#climateSlider'), 'climate', 'raster-opacity', 'climateSlider'], [$('#prioritySlider'), 'priority_index', 'fill-opacity', 'prioritySlider'], [$('#birdSlider'), 'bird-layer', 'fill-opacity', 'birdSlider']]; //This variable ensures that the small layers will always be above the large layers in draw order var smallLayerPartition = lineLayerArray[lineLayerArray.length-1][3]; checkboxSmallLayers.forEach(function(layer) { layer[0].on('switchChange.bootstrapSwitch', function() { if (layer[0].bootstrapSwitch('state')) { map.setLayoutProperty(layer[1]+'-layer', 'visibility', 'visible'); map.setLayoutProperty(layer[1]+'-line', 'visibility','visible'); map.moveLayer(layer[1]+'-layer'); map.moveLayer(layer[1]+'-line'); } else { map.setLayoutProperty(layer[1]+'-layer', 'visibility', 'none'); map.setLayoutProperty(layer[1]+'-line', 'visibility','none'); } }); }); checkboxLargeLayers.forEach(function(layer) { if (layer[1] == 'wildness') { layer[0].on('switchChange.bootstrapSwitch', function() { if ( layer[0].bootstrapSwitch('state')) { map.setLayoutProperty(layer[1], 'visibility', 'visible'); for (i=0;i<polyArray.length;i++) { map.setLayoutProperty('vector'+i, 'visibility', 'visible'); map.moveLayer('vector'+i); } map.moveLayer(layer[1], smallLayerPartition); lineLayerArray.forEach(function(layer) { if (map.getLayoutProperty(layer[2], 'visibility') == 'visible') { map.moveLayer(layer[2],smallLayerPartition); map.moveLayer(layer[3],smallLayerPartition); } }); } else { map.setLayoutProperty(layer[1], 'visibility', 'none'); for (i=0;i<polyArray.length;i++) { map.setLayoutProperty('vector'+i, 'visibility', 'none'); } } }); } else { layer[0].on('switchChange.bootstrapSwitch', function() { if (layer[0].bootstrapSwitch('state')) { map.setLayoutProperty(layer[1], 'visibility', 'visible'); map.moveLayer(layer[1], smallLayerPartition); lineLayerArray.forEach(function(layer) { if (map.getLayoutProperty(layer[2], 'visibility') == 'visible') { map.moveLayer(layer[2],smallLayerPartition); map.moveLayer(layer[3],smallLayerPartition); } }); } else { map.setLayoutProperty(layer[1], 'visibility', 'none'); } }); } }); //Add wilderness info popup map.on('click', 'wilderness-layer', function(e) { new mapboxgl.Popup() .setLngLat(e.lngLat) .setHTML('<h5> <a href=' + e.features[0].properties.URL + '>' + e.features[0].properties.NAME + '</a> </h5>' + '<p class=popup>' + e.features[0].properties.Descriptio + '</p>') .addTo(map); }); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "addFilterEventHandlers() {\n \n //it's three filters 'broadband, tv, mobile'\n if (this.productFilters.length) {\n this.productFilters.forEach(element => {\n element.addEventListener(\"change\", this.onProductFilterChange);\n });\n }\n\n //remaining filters underneath\n if (this.providerFilters.length) {\n this.providerFilters.forEach(element => {\n element.addEventListener(\"change\", this.onProviderFilterChange);\n });\n }\n }", "setupFilterListener() {\n // show hide filter sections\n $('.filter-section').on('click', '.filter-title', (event) => {\n const $section = $(event.delegateTarget);\n const filter = $section.data('section');\n $section.children('.filter-body__list').toggleClass('filter-body__list--hidden');\n $(event.target.parentElement).find('.filter-title__action').toggleClass('filter-title__action--expanded');\n\n event.stopPropagation();\n this.expandedFilterEvent.notify({ filter });\n });\n\n // on filter selection\n $('.filter-section').on('click', '.filter-item__checkbox', (event) => {\n const $currentSelection = $(event.target);\n const isChecked = $currentSelection.prop('checked')\n const filter = $currentSelection.data('filter');\n const section = $(event.delegateTarget).data('section');\n\n this.checkedFilterEvent.notify({\n filter,\n isChecked,\n section\n });\n });\n\n // clear\n $('#clear-button').click(() => {\n this.clearEvent.notify();\n });\n }", "createListeners() {\n\n this.listenDeleteAllFiltersOptions();\n\n this.listenMainInputOnType();\n\n this.listenClickFilterOption();\n\n this.listenDeleteFilter();\n\n this.listenMainInputOnFocus();\n\n this.listenMainInputOnBlur();\n\n this.listenClickModalFilter();\n\n this.listenModalFilterOnBlur();\n\n this.listenModalFilterOnType();\n\n }", "function setGridEvents() {\n\t\t\t$scope.externalFilterChanged = function() {\n\t\t\t\t$scope.gridOptionsFacturas.api\n\t\t\t\t\t\t.onFilterChanged();\n\t\t\t};\n\t\t}", "function addDayFilterListeners() {\n days.forEach(function(day) {\n $(`#day-${day}-filter`).click(\"click\", function() {\n dayFilter(day);\n $('#day-filter-btn').html(`${day}`)\n });\n });\n }", "function addFilterEventListeners(){\n const onlyCatsButton = document.querySelector(`[data-filter=\"cat\"]`)\n onlyCatsButton.addEventListener(\"click\", changeFiltering.bind(null, \"type\", \"cat\"))\n\n const onlyDogsButton = document.querySelector(`[data-filter=\"dog\"]`)\n onlyDogsButton.addEventListener(\"click\", changeFiltering.bind(null, \"type\", \"dog\"))\n\n const allButton = document.querySelector(`[data-filter=\"*\"]`)\n allButton.addEventListener(\"click\", changeFiltering.bind(null, \"\", \"\"))\n}", "function filterListener(){\n $(\"#colorFilter\").change(function(){\n populateBikeList();\n });\n $(\"#statusFilter\").change(function(){\n populateBikeList();\n });\n }", "handleEventFiltering() {\n this.events = this.filterByType(this.replicaSetEvents.events, this.eventType);\n this.events = this.filterBySource(this.events, this.eventSource);\n }", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters(){}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}", "function setFilters() {}" ]
[ "0.7554857", "0.7273307", "0.725229", "0.68904346", "0.6885258", "0.6880303", "0.6837646", "0.6710117", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6611541", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425", "0.6517425" ]
0.0
-1
component first gets rendered
componentDidMount() { const { id } = this.props.match.params; this.props.fetchPost(id); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_firstRendered() { }", "render() {\n\t\tif (!this.component_.element) {\n\t\t\tthis.component_.element = document.createElement('div');\n\t\t}\n\t\tthis.emit('rendered', !this.isRendered_);\n\t}", "render() {\n if (!this.initialized) this.init();\n }", "render() {\n if (!this.initialized) {\n this.init();\n }\n }", "function render() {\n\t\t\t}", "function render() {\n\n\t\t\t}", "render() {\n // always reinit on render\n this.init();\n }", "render() {\n // always reinit on render\n this.init();\n }", "onRender () {\n console.log(this.component);\n if(undefined !== this.component) {\n this.el.querySelector(`[data-id=\"${this.component}\"]`).classList.add(\"active\");\n }\n\n var Navigation = new NavigationView();\n App.getNavigationContainer().show(Navigation);\n Navigation.setItemAsActive(\"components\");\n this.showComponent(this.component);\n\n }", "function init() { render(this); }", "onAfterRendering() {}", "onBeforeRendering() {}", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting Vendor</Loader>;\n }", "render() {\n return (this.props.ready && this.props.ready2) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "render() {\n this.notify('initial-load', {});\n /**\n * Used to load context menu\n */\n this.trigger('load');\n this.notify('initial-end', {});\n this.renderElements();\n this.renderComplete();\n }", "static rendered () {}", "static rendered () {}", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "onRender () {\n\n }", "render() {\n // Called every time the component gets new props\n this.update();\n // Render the empty table text if there is no data\n if (!this.state.data[0]) return <TableEmpty message={this.props.emptyMessage} />;\n return <Component {...this.props} {...this.state} headerClick={this.headerClick} />;\n }", "onRender () {\n\t\tthis.registerComponent(App.Compontents, \"app-controls\", TopBarControls, this.$el.find(\"#topbar-container\"), { title: \"Home\" });\n }", "onRender()/*: void*/ {\n this.render();\n }", "function init(){\n buildComponent();\n attachHandlers();\n addComponents();\n doSomethingAfterRendering(); // 렌더 이후 처리함수 (예 - 서버접속)\n }", "afterRender() { }", "afterRender() { }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return this.props.ready ? (\n this.renderPage()\n ) : (\n <Loader active>Getting data</Loader>\n );\n }", "render() {\n this.configPage();\n history.pushState({ href: '/first-entrance' }, null, '/first-entrance');\n this.wrapper.append(this.main);\n\n this.main.innerHTML = firstTemplate();\n\n document.querySelector('.icon-list').classList.add('active');\n\n this.attachListeners(this.main);\n }", "render() {\n\n return (this.props.ready) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render(){\r\n\r\n\t}", "beforerender (el) {\n console.log('Component is about to be rendered for the first time')\n\n // this is where you can register other lifecycle events:\n // on.resize()\n // on.ready()\n // on.intersect()\n // on.idle()\n }", "onBeforeRender () {\n\n }", "init() {\n this.render();\n }", "init() {\n this.render();\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader active>Fetching Data</Loader>;\n }", "render() {\n return (this.props.ready1 && this.props.ready2) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "render() {\n return (this.props.ready) ? this.renderPage() : <Loader>Getting data</Loader>;\n }", "postRender()\n {\n super.postRender();\n }", "render() {\n this.update();\n }", "render() {\n return (this.props.tickets) ? this.renderPage() : <Loader active>Getting data</Loader>;\n }", "render() {\n if (!this.state.loaded1 || !this.state.loaded2) {\n return (\n <div className=\"center-align\">\n <div className=\"progress\">\n <div className=\"indeterminate\"></div>\n </div>\n </div>\n );\n }\n\n return (\n <div>\n <Navbar/>\n <div className=\"calender\">\n <ScheduleComponent\n height=\"650px\"\n readonly={true}\n currentView=\"Month\"\n eventSettings={{ dataSource: this.state.localData }}\n >\n <Inject services={[Day, Week, WorkWeek, Month, Agenda]} />\n </ScheduleComponent>\n </div>\n </div>\n \n );\n }", "connectedCallback() {\r\n this.addComponentContent()\r\n }", "render() {\n\n return (\n <div>\n {this.renderContent()}\n </div>\n );\n \n }", "render() {\n\n\t}", "render() {\n\n\t}", "function render() {\n\t}", "componentWillLoad() {\n this.base = new baseComponent_esm.BaseComponent(this, core.dxp);\n if (this.textList.length > 0) {\n this.assignPlaceholderText();\n }\n }", "render() {\n return ((this.props.ready && this.props.ready2 && this.props.ready3)) ? this.renderPage() :\n <Loader active>Getting data</Loader>;\n }", "function render() {\n\t\t\n\t}", "render(){}", "render(){}", "render() {\n /* renderComponent() -> this will call renderComponent() and be applied for all conditions in it.\n */\n return <div style={{ border: \"red\" }}>{this.renderComponent()}</div>;\n }", "function renderComponentNow(component) {\n if (componentsToRender.indexOf(component) === -1) componentsToRender.push(component);\n}", "_didRender(_props, _changedProps, _prevProps) { }", "render() {\r\n document.body.insertBefore(this.element, document.querySelector('script'));\r\n\r\n this.append(this.PageContent.element, [this.NewsList, this.Footer]);\r\n this.append(this.Sidebar.element, [this.SidebarTitle, this.SourcesList]);\r\n this.append(this.element, [this.Spinner, this.PageContent, this.Sidebar, this.ToggleBtn]);\r\n }", "connectedCallback() {\n self.addComponentContent()\n }", "function render(selectedHeaderItem, component, props, ready) {\n ReactDOM.render(\n <div>\n <Crystal.React.Header selectedItem={selectedHeaderItem} />\n { ready === false ? \n <Crystal.React.Loading /> : \n React.createElement(component, props)\n }\n <footer></footer>\n <Crystal.React.ScrollToTop />\n </div>,\n document.getElementById('react-root'));\n}", "render() {\n\n if (this.type === \"Terrains\") {\n return (\n <RechercheTerrainJouer\n gotoItemOnPress={true}\n latitude={this.selfLat}\n longitude={this.selfLong}\n />\n )\n }\n else {\n return (\n <ComposantRechercheAutour\n type={this.type}\n renderItem={this.renderItem}\n />\n )\n }\n }", "didRender() {\n console.log('didRender ejecutado!');\n }", "_renderScreen() {\n\t\tif (this._el && this._component) {\n\t\t\tthis._component.render(this._el);\n\t\t}\n\t}", "constructor() {\n super();\n this.render();\n }", "render() {\n this.el.innerHTML = this.template();\n\n setTimeout(() => {\n this.bindUIElements();\n }, 0);\n }", "render() {\r\n return;\r\n }", "_renderNewRootComponent(/* instance, ... */) { }" ]
[ "0.7185477", "0.6914897", "0.6682586", "0.66601306", "0.6643164", "0.6597932", "0.65428543", "0.65428543", "0.65246207", "0.65000814", "0.6499305", "0.6460951", "0.6459545", "0.64594257", "0.6452687", "0.6452687", "0.6452687", "0.64507055", "0.64507055", "0.64243776", "0.64152783", "0.63922405", "0.6390121", "0.63634616", "0.6349621", "0.63494223", "0.63494223", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.6345695", "0.63445747", "0.63364965", "0.6329642", "0.6302268", "0.62978494", "0.6276941", "0.627343", "0.627343", "0.62556124", "0.6252268", "0.6243818", "0.6243818", "0.6243818", "0.6243818", "0.62337446", "0.62281734", "0.62256867", "0.6222171", "0.6217997", "0.621368", "0.62114793", "0.62114793", "0.6192378", "0.61823374", "0.61807954", "0.6177392", "0.6167651", "0.6167651", "0.6161131", "0.61561555", "0.6151617", "0.615024", "0.61297673", "0.6128557", "0.6126784", "0.612099", "0.61156535", "0.6111374", "0.6073648", "0.607052", "0.6063199" ]
0.0
-1
This function gets cookie with a given name
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function getCookie(name) {\n // from tornado docs: http://www.tornadoweb.org/en/stable/guide/security.html\n var r = document.cookie.match('\\\\b' + name + '=([^;]*)\\\\b');\n return r ? r[1] : void 0;\n }", "function GetCookie (name) {\r\n var arg=name+\"=\";\r\n var alen=arg.length;\r\n var clen=document.cookie.length;\r\n var i=0;\r\n while (i<clen) {\r\n var j=i+alen;\r\n if (document.cookie.substring(i, j)==arg)\r\n return getCookieVal (j);\r\n i=document.cookie.indexOf(\" \",i)+1;\r\n if (i==0) break;}\r\n return null;\r\n}", "function getCookie(name) {\n var arg = name + \"=\";\n var alen = arg.length;\n var clen = document.cookie.length;\n var i = 0;\n while (i < clen) {\n var j = i + alen;\n if (document.cookie.substring(i, j) == arg) {\n return getCookieVal(j);\n }\n i = document.cookie.indexOf(\" \", i) + 1;\n if (i == 0) break;\n }\n return;\n }", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2)\n return parts.pop().split(\";\").shift();\n }", "function getCookie(name) {\n\t return _cookiesMin2.default.get(name);\n\t}", "function getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') { c = c.substring(1) };\n if (c.indexOf(nameEQ) != -1) { return c.substring(nameEQ.length,c.length) };\n }\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n }", "function getCookie(name) {\n\n var matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ))\n return matches ? decodeURIComponent(matches[1]) : undefined\n }", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n }", "function GetCookie(name) {\r\n\tvar i,x,y,ARRcookies=document.cookie.split(\";\");\r\n\tfor (i=0;i<ARRcookies.length;i++){\r\n\t\tx=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));\r\n\t\ty=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);\r\n\t\tx=x.replace(/^\\s+|\\s+$/g,\"\");\r\n\t\tif (x==name){\r\n\t\t\treturn decodeURIComponent(y);\r\n\t\t}\r\n\t}\r\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\n var c = document.cookie.match(\"\\\\b\" + name + \"=([^;]*)\\\\b\");\n return c ? c[1] : undefined;\n}", "function getCookie(name) {\n var value = \"; \" + document.cookie;\n var parts = value.split(\"; \" + name + \"=\");\n if (parts.length == 2) {\n return parts.pop().split(\";\").shift();\n }\n}", "function getCookie(name)\r\n{\r\n var prefix = name + '='\r\n var cookieStartIndex = document.cookie.indexOf(prefix)\r\n if (cookieStartIndex == -1)\r\n return null\r\n var cookieEndIndex = document.cookie.indexOf(';', cookieStartIndex + prefix.length)\r\n if (cookieEndIndex == -1)\r\n cookieEndIndex = document.cookie.length\r\n return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))\r\n}", "function bzw_getCookie(name) {\n var arg = name + \"=\";\n var alen = arg.length;\n var clen = document.cookie.length;\n var i = 0;\n while (i < clen) {\n var j = i + alen;\n if (document.cookie.substring(i, j) == arg) {\n return bzw_getCookieVal(j);\n }\n i = document.cookie.indexOf(\" \", i) + 1;\n if (i == 0) break; \n }\n return \"\";\n}", "function getCookie(name) {\r\n\t\t\tvar arg = name + \"=\";\r\n\t\t\tvar alen = arg.length;\r\n\t\t\tvar clen = document.cookie.length;\r\n\t\t\tvar i = 0;\r\n\t\t\twhile (i < clen) {\r\n\t\t\t\tvar j = i + alen;\r\n\t\t\t\tif (document.cookie.substring(i, j) == arg) { \r\n\t\t\t\t\treturn getCookieVal(j);\r\n\t\t\t\t}\r\n\t\t\t\ti = document.cookie.indexOf(\" \", i) + 1;\r\n\t\t\t\tif (i == 0) break; \r\n\t\t\t}\r\n\t\t\treturn \"\";\r\n}", "function getCookie(name) {\n let matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n }", "function getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n }", "function getCookie(name) {\n\tvar str = document.cookie;\n\tvar arr = str.split('; ');\n\tfor (var i = 0;i < arr.length;i++) {\n\t\tvar arr2 = arr[i].split('=');\n\t\t// arr2[0] = username arr2[1] = zs\n\t\t// arr2[0] = bbb arr2[1] = 18\n\t\tif (name == arr2[0]) {\n\t\t\treturn arr2[1];\n\t\t}\n\t}\n\treturn null;\n}", "function readCookie(name){\n var search = name + \"=\";\n if (document.cookie.length > 0){ \n offset = document.cookie.indexOf(search)\n if (offset != -1) // if cookie exists\n { \n offset += search.length\n end = document.cookie.indexOf(\";\", offset) // set index of beginning of value\n if (end == -1) end = document.cookie.length // set index of end of cookie value\n return unescape(document.cookie.substring(offset, end));\n }\n }\n if (name == 'v4iilex'){ return readCookie('v4iil'); }\n return \"\";\n}", "function getCookie(name) {\n let matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n }", "function getCookie(name) {\n\tvar cookies = document.cookie.split(\"; \");\n\n\tfor (var i = 0; i < cookies.length; i++) {\n\t\tvar strings = cookies[i].split(\"=\");\n\t\tif (strings[0] == name) return strings[1];\n\t}\n \n return undefined;\n}", "function getCookie(name) {\n\tvar value = \"; \" + document.cookie;\n\tvar parts = value.split(\"; \" + name + \"=\");\n\tif (parts.length == 2) return parts.pop().split(\";\").shift();\n}", "function getCookie(name) {\r\n\tvar prefix = name + \"=\" \r\n\tvar start = document.cookie.indexOf(prefix) \r\n\r\n\tif (start==-1) {\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tvar end = document.cookie.indexOf(\";\", start+prefix.length) \r\n\tif (end==-1) {\r\n\t\tend=document.cookie.length;\r\n\t}\r\n\r\n\tvar value=document.cookie.substring(start+prefix.length, end) \r\n\treturn unescape(value);\r\n}", "function getCookie(name) {\r\n\tvar prefix = name + \"=\" \r\n\tvar start = document.cookie.indexOf(prefix) \r\n\r\n\tif (start==-1) {\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tvar end = document.cookie.indexOf(\";\", start+prefix.length) \r\n\tif (end==-1) {\r\n\t\tend=document.cookie.length;\r\n\t}\r\n\r\n\tvar value=document.cookie.substring(start+prefix.length, end) \r\n\treturn unescape(value);\r\n}", "function GetCookie(name)\r\n{\r\n\tvar nameEQ = name + \"=\";\r\n\tvar ca = document.cookie.split(';');\r\n\tfor(var i=0;i < ca.length;i++)\r\n\t{\r\n\t\tvar c = ca[i];\r\n\t\twhile (c.charAt(0)==' ') c = c.substring(1,c.length);\r\n\t\tif (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\r\n\t}\r\n\treturn null;\r\n}", "function getCookie(name) {\n var c, RE = new RegExp('(^|;)\\\\s*' + name + '\\\\s*=\\\\s*([^\\\\s;]+)', 'g');\n return (c = RE.exec(document.cookie)) ? c[2] : null;\n}", "function getCookie(name) {\r\n var nameEQ = name + \"=\";\r\n var ca = document.cookie.split(\";\");\r\n for (var i = 0; i < ca.length; i++) {\r\n var c = ca[i];\r\n while (c.charAt(0) == \" \") c = c.substring(1, c.length);\r\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);\r\n }\r\n return null;\r\n}", "function getCookie(name) {\n let matches = document.cookie.match(\n new RegExp(\n \"(?:^|; )\" +\n name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, \"\\\\$1\") +\n \"=([^;]*)\"\n )\n );\n return matches ? decodeURIComponent(matches[1]) : undefined;\n }", "function getCookie(name) {\n var matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ))\n return matches ? decodeURIComponent(matches[1]) : undefined\n}", "function getCookie(name) {\n var prefix = name + \"=\" \n var start = document.cookie.indexOf(prefix) \n\n if (start==-1) {\n return null;\n }\n \n var end = document.cookie.indexOf(\";\", start+prefix.length) \n if (end==-1) {\n end=document.cookie.length;\n }\n\n var value=document.cookie.substring(start+prefix.length, end) \n return unescape(value);\n}", "function getCookie(name){\n //Split cookie string and get all indiviudal name=value pairs in an array\n var cookieArr = document.cookie.split(\";\");\n\n //Loop through the array elements\n for(var i=0; i< cookieArr.length; i++){\n var cookiePair = cookieArr[i].split(\"=\");\n\n /* Removing whitespace at the begining of the cookije name\n and compare it with the given string */\n if(name == cookiePair[0].trim()){\n //Decode the cookie value and return\n return decodeURIComponent(cookiePair[1]);\n } \n }\n // Return null if not found\n return null;\n }", "function ht_getcookie(name) {\n\tvar cookie_start = document.cookie.indexOf(name);\n\tvar cookie_end = document.cookie.indexOf(\";\", cookie_start);\n\treturn cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));\n}", "function GetCookie(name) {\r\n\t\r\nif (checkCookie())\r\n\t{\r\n var arg = name + \"=\";\r\n var alen = arg.length;\r\n var clen = document.cookie.length;\r\n var i = 0;\r\n while (i < clen) {\r\n var j = i + alen;\r\n if (document.cookie.substring(i, j) == arg)\r\n return getCookieVal (j);\r\n i = document.cookie.indexOf(\" \", i) + 1;\r\n if (i == 0) break;\r\n }\r\n return null;\r\n\t}\r\n else\r\n return unescape(document.cookie.substring(offset, endstr));\r\n}", "function GetCookie(name) {\r\n\t\r\nif (checkCookie())\r\n\t{\r\n var arg = name + \"=\";\r\n var alen = arg.length;\r\n var clen = document.cookie.length;\r\n var i = 0;\r\n while (i < clen) {\r\n var j = i + alen;\r\n if (document.cookie.substring(i, j) == arg)\r\n return getCookieVal (j);\r\n i = document.cookie.indexOf(\" \", i) + 1;\r\n if (i == 0) break;\r\n }\r\n return null;\r\n\t}\r\n else\r\n return unescape(document.cookie.substring(offset, endstr));\r\n}", "function GetCookie(name) {\r\n\t\r\nif (checkCookie())\r\n\t{\r\n var arg = name + \"=\";\r\n var alen = arg.length;\r\n var clen = document.cookie.length;\r\n var i = 0;\r\n while (i < clen) {\r\n var j = i + alen;\r\n if (document.cookie.substring(i, j) == arg)\r\n return getCookieVal (j);\r\n i = document.cookie.indexOf(\" \", i) + 1;\r\n if (i == 0) break;\r\n }\r\n return null;\r\n\t}\r\n else\r\n return unescape(document.cookie.substring(offset, endstr));\r\n}", "function GetCookie(name) {\n\n var arg = name + \"=\";\n\n var alen = arg.length;\n\n var clen = document.cookie.length;\n\n var i = 0;\n\n while (i < clen) {\n\n var j = i + alen;\n\n if (document.cookie.substring(i, j) == arg)\n\n return getCookieVal(j);\n\n i = document.cookie.indexOf(\" \", i) + 1;\n\n if (i == 0) break;\n\n }\n\n return null;\n\n}", "function getCookie(name) {\n\t\tvar arg = name + \"=\";\n\t\tvar alen = arg.length;\n\t\tvar clen = document.cookie.length;\n\t\tvar i = 0;\n\t\twhile (i < clen) {\n\t\t\tvar j = i + alen;\n\t\t\tif (document.cookie.substring(i, j) == arg) {\n\t\t\t\treturn getCookieVal(j);\n\t\t\t}\n\t\t\ti = document.cookie.indexOf(\" \", i) + 1;\n\t\t\tif (i == 0) break;\n\t\t}\n\t\treturn null;\n\t}", "get(name, options = {}) {\n const cookies = cookie.parse(document.cookie)\n return readCookie(cookies[name], options)\n }", "function getCookie(name) {\n const value = `; ${document.cookie}`;\n const parts = value.split(`; ${name}=`);\n if (parts.length === 2) return parts.pop().split(';').shift();\n }", "function getCookie(name) {\n var matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n}", "function getCookie(name)\r\n{\r\n\tvar re = new RegExp(name + \"=([^;]+)\");\r\n\tvar value = re.exec(document.cookie);\r\n\treturn (value != null) ? unescape(value[1]) : null;\r\n}", "function getCookie(name)\n{\n\tvar arg = name + \"=\";\n\tvar alen = arg.length;\n\tvar clen = document.cookie.length;\n\tvar i = 0;\n\twhile(i < clen)\n\t{\n\t\tvar j = i + alen;\n\t\tif (document.cookie.substring(i, j) == arg)\n\t\t{\n\t\t\treturn getCookieVal(j);\n\t\t}\n\t\ti = document.cookie.indexOf(\" \", i) + 1;\n\t\tif(i == 0) break;\n\t}\n\treturn;\n}", "function getcookie(name) {\n var cookies = document.cookie.split(';'), i = 0, l = cookies.length,\n current;\n for (; i < l; i++) {\n current = cookies[i].split('=');\n // current[0] = current[0].replace(/\\s+/,\"\");\n if (current[0] === name) {return current[1];}\n }\n return undefined;\n}", "function getCookie(name) {\n var matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n}", "function getCookie(name) {\n var nameEq = name + \"=\", i, c, ca = document.cookie.split(';');\n\n for (i = 0; i < ca.length; i += 1) {\n c = ca[i];\n while (c.charAt(0) === ' ') {\n c = c.substring(1, c.length);\n }\n if (c.indexOf(nameEq) === 0) {\n return c.substring(nameEq.length, c.length);\n }\n }\n return null;\n }", "function get_cookie(name) {\n\tname = name += \"=\";\n\tvar cookie_start = document.cookie.indexOf(name);\n\tif(cookie_start > -1) {\n\t\tcookie_start = cookie_start+name.length;\n\t\tcookie_end = document.cookie.indexOf(';', cookie_start);\n\t\tif(cookie_end == -1) {\n\t\t\tcookie_end = document.cookie.length;\n\t\t}\n\t\treturn unescape(document.cookie.substring(cookie_start, cookie_end));\n\t}\n}", "function getCookie(name)\r\n{\r\n var dc = document.cookie;\r\n var prefix = name + \"=\";\r\n var begin = dc.indexOf(\"; \" + prefix);\r\n if (begin == -1)\r\n {\r\n begin = dc.indexOf(prefix);\r\n if (begin != 0) return null;\r\n }\r\n else\r\n {\r\n begin += 2;\r\n }\r\n var end = document.cookie.indexOf(\";\", begin);\r\n if (end == -1)\r\n {\r\n end = dc.length;\r\n }\r\n return unescape(dc.substring(begin + prefix.length, end));\r\n}", "function getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for (var i = 0; i < ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) == ' ') c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n}", "function getCookie(name) {\n\n\tlet cookies = document.cookie.split(';');\n\tfor (let i=0; i < cookies.length; i++) {\n\t\tlet biscuit = cookies[i].split('=');\n\t\tif (biscuit[0].trim() == name) {\n\t\t\treturn biscuit[1];\n\t\t}\n\n\t}\n\n\treturn null;\n\n}", "function getCookie(name) {\n let nameEq = name + \"=\";\n let ca = document.cookie.split(';');\n for(let i=0;i < ca.length;i++) {\n let c = ca[i];\n while (c.charAt(0)===' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEq) === 0) return c.substring(nameEq.length,c.length);\n }\n return null;\n}", "function xl_GetCookie (name) \n{\n\tvar arg = name + \"=\";\n\tvar alen = arg.length;\n\tvar clen = document.cookie.length;\n\tvar i = 0;\n\twhile (i < clen) \n\t{\n\t\tvar j = i + alen;\n\t\tif (document.cookie.substring(i, j) == arg)\n\t\t\treturn xl_GetCookieVal (j);\n\t\ti = document.cookie.indexOf(\" \", i) + 1;\n\t\tif (i == 0) break; \n\t}\n\t\n\treturn null;\n}", "function getCookie(name) {\n var dc = document.cookie,\n prefix = name + \"=\",\n begin = dc.indexOf(\"; \" + prefix);\n if (begin == -1) {\n begin = dc.indexOf(prefix);\n if (begin != 0) return null;\n }\n else {\n begin += 2;\n var end = document.cookie.indexOf(\";\", begin);\n if (end == -1) {\n end = dc.length;\n }\n }\n return decodeURI(dc.substring(begin + prefix.length, end));\n}", "function getCookie(name)\n{\n var re = new RegExp(name + \"=([^;]+)\");\n var value = re.exec(document.cookie);\n return (value != null) ? unescape(value[1]) : null;\n}", "function getCookie(name) {\r\n var dc = document.cookie;\r\n var prefix = name + \"=\";\r\n var begin = dc.indexOf(\"; \" + prefix);\r\n if (begin == -1) {\r\n begin = dc.indexOf(prefix);\r\n if (begin != 0) return null;\r\n } else\r\n begin += 2;\r\n var end = document.cookie.indexOf(\";\", begin);\r\n if (end == -1)\r\n end = dc.length;\r\n return unescape(dc.substring(begin + prefix.length, end));\r\n}", "function getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i < ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));\n }\n return null;\n }", "function xGetCookie(name)\r\n{\r\n var value=null, search=name+\"=\";\r\n if (document.cookie.length > 0) {\r\n var offset = document.cookie.indexOf(search);\r\n if (offset != -1) {\r\n offset += search.length;\r\n var end = document.cookie.indexOf(\";\", offset);\r\n if (end == -1) end = document.cookie.length;\r\n value = unescape(document.cookie.substring(offset, end));\r\n }\r\n }\r\n return value;\r\n}", "function getCookie(name) {\r\n var nameEQ = name + \"=\";\r\n var ca = document.cookie.split(';');\r\n for (var i = 0; i < ca.length; i++) {\r\n var c = ca[i];\r\n while (c.charAt(0) == ' ') c = c.substring(1, c.length);\r\n if (c.indexOf(nameEQ) == 0)\r\n return decodeURIComponent(c.substring(nameEQ.length, c.length));\r\n }\r\n return null;\r\n}", "function getCookie(name) {\r\n var dc = document.cookie;\r\n var prefix = name + \"=\";\r\n var begin = dc.indexOf(\"; \" + prefix);\r\n if (begin == -1) {\r\n begin = dc.indexOf(prefix);\r\n if (begin != 0) return null;\r\n }\r\n else {\r\n begin += 2;\r\n }\r\n var end = document.cookie.indexOf(\";\", begin);\r\n if (end == -1) {\r\n end = dc.length;\r\n }\r\n return unescape(dc.substring(begin + prefix.length, end));\r\n}", "function getCookie(name) {\r\n let cookie = decodeURIComponent(document.cookie);\r\n let cArray = cookie.split(';');\r\n let obj = {\r\n exist: false,\r\n value: null\r\n }\r\n for (let i = 0; i <cArray.length; i++) {\r\n let c = cArray[i];\r\n while (c.charAt(0) == ' ') {\r\n c = c.substring(1);\r\n }\r\n if (c.indexOf(name) == 0) {\r\n obj.exist = true;\r\n obj.value = c.substring(name.length+1, c.length);\r\n }\r\n }\r\n return obj;\r\n}", "function get_cookie(name) {\r\n\tvar searchstr = name + \"=\";\r\n\tvar returnvalue = \"\";\r\n\tif (document.cookie.length > 0) {\r\n\t\tvar offset = document.cookie.indexOf(searchstr);\r\n\t\t// if cookie exists\r\n\t\tif (offset != -1) {\r\n\t\t\toffset += searchstr.length;\r\n\t\t\t// set index of beginning of value\r\n\t\t\tvar end = document.cookie.indexOf(\";\", offset);\r\n\t\t\t\t// set index of end of cookie value\r\n\t\t\tif (end == -1) \r\n\t\t\t\t\tend = document.cookie.length;\r\n\t\t\treturnvalue=unescape(document.cookie.substring(offset, end));\r\n\t\t}\r\n \t}\r\n \treturn returnvalue;\r\n}", "function getCookie(name) {\n var dc = document.cookie;\n var prefix = name + \"=\";\n var begin = dc.indexOf(\"; \" + prefix);\n if (begin == -1) {\n begin = dc.indexOf(prefix);\n if (begin != 0) return null;\n } else\n begin += 2;\n var end = document.cookie.indexOf(\";\", begin);\n if (end == -1)\n end = dc.length;\n return unescape(dc.substring(begin + prefix.length, end));\n}", "function __cookieGet($name) {\r\n var arg = $name + \"=\";\r\n var alen = arg.length;\r\n var clen = document.cookie.length;\r\n var i = 0;\r\n while (i < clen) {\r\n var j = i + alen;\r\n if (document.cookie.substring(i, j) == arg)\r\n return getVal (j);\r\n i = document.cookie.indexOf(\" \", i) + 1;\r\n if (i == 0)\r\n break;\r\n }\r\n return null;\r\n\r\n function getVal(offset) {\r\n var endstr = document.cookie.indexOf (\";\", offset);\r\n if (endstr == -1)\r\n endstr = document.cookie.length;\r\n return unescape(document.cookie.substring(offset, endstr));\r\n }\r\n}", "function getCookie(name){\n\n let cookieVal = null;\n\n if(document.cookie && document.cookie != ''){\n const cookies = document.cookie.split(';');\n\n for(let i=0; i < cookies.length; i++){\n const currCookie = cookies[i].trim();\n if(currCookie.substring(0, name.length + 1) === (name + '=') ){\n cookieVal = decodeURIComponent(currCookie.substring(name.length+1));\n break;\n }\n }\n }\n\n return cookieVal;\n}", "function getCookie(name) {\n var v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');\n return v ? v[2] : null;\n}", "function getCookie(name) {\r\n var prefix = name + \"=\";\r\n var start = document.cookie.indexOf(prefix);\r\n\r\n if (start == -1) {\r\n return null;\r\n }\r\n\r\n var end = document.cookie.indexOf(\";\", start + prefix.length);\r\n if (end == -1) {\r\n end = document.cookie.length;\r\n }\r\n\r\n var value = document.cookie.substring(start + prefix.length, end);\r\n return unescape(value);\r\n}", "function getCookie(name)\n{\n var dc = document.cookie;\n var prefix = name + \"=\";\n var begin = dc.indexOf(\"; \" + prefix);\n if (begin == -1)\n {\n begin = dc.indexOf(prefix);\n if (begin !== 0)\n {\n return null;\n }\n }\n else\n {\n begin += 2;\n }\n var end = document.cookie.indexOf(\";\", begin);\n if (end == -1)\n {\n end = dc.length;\n }\n return unescape(dc.substring(begin + prefix.length, end));\n}", "function getCookie(name) {\n var name = name + \"=\";\n var cookieArray = document.cookie.split(';');\n for (var i = 0; i < cookieArray.length; i++) {\n var cookie = cookieArray[i];\n while (cookie.charAt(0) == ' ') cookie = cookie.substring(1);\n if (cookie.indexOf(name) == 0) {\n return cookie.substring(name.length, cookie.length);\n }\n }\n return \"\";\n }", "function getCookie(name) {\n var arr, reg = new RegExp(\"(^| )\" + name + \"=([^;]*)(;|$)\");\n if (arr = document.cookie.match(reg)) {\n return unescape(arr[2]);\n } else {\n return null;\n }\n }", "function getCookie(name) {\n const re = new RegExp(`${name}=([^;]+)`);\n const value = re.exec(document.cookie);\n return (value != null) ? unescape(value[1]) : null;\n }", "function my_getcookie( name )\n{\n\tcname = var_cookieid + name + '=';\n\tcpos = document.cookie.indexOf( cname );\n\t\n\tif ( cpos != -1 )\n\t{\n\t\tcstart = cpos + cname.length;\n\t\tcend = document.cookie.indexOf(\";\", cstart);\n\t\t\n\t\tif (cend == -1)\n\t\t\tcend = document.cookie.length;\n\t\n\t\treturn unescape( document.cookie.substring(cstart, cend) );\n\t}\n\t\n\treturn null;\n}", "function getCookie(name) {\r\n var cname = name + \"=\";\r\n var dc = document.cookie;\r\n if (dc.length > 0) {\r\n begin = dc.indexOf(cname);\r\n if (begin != -1) {\r\n begin += cname.length;\r\n end = dc.indexOf(\";\", begin);\r\n if (end == -1) end = dc.length;\r\n return unescape(dc.substring(begin, end));\r\n }\r\n }\r\n return null;\r\n}", "function GetCookie(name) {\n var cookies = (document.cookie || \"\").split(\";\");\n var i = 0, l = cookies.length, c;\n for ( i; i < l; i++ ) {\n c = cookies[i].replace(/^\\s+|\\s|\\s$/g, \"\").split(\"=\");\n if ( (c.shift()) == name ) {\n return c.join(\" \");\n }\n }\n\n return null;\n}", "function getCookie(c_name) {\n var i, x, y, ARRcookies = document.cookie.split(';');\n for (i = 0; i < ARRcookies.length; i++) {\n x = ARRcookies[i].substr(0, ARRcookies[i].indexOf('='));\n y = ARRcookies[i].substr(ARRcookies[i].indexOf('=') + 1);\n x = x.replace(/^\\s+|\\s+$/g, '');\n if (x === c_name) {\n return decodeURIComponent(y);\n }\n }\n }", "function getCookie(c_name) { \n\tvar c_value = document.cookie;\n\tvar c_start = c_value.indexOf(\" \" + c_name + \"=\");\n\tif (c_start == -1)\n\t {\n\t c_start = c_value.indexOf(c_name + \"=\");\n\t }\n\tif (c_start == -1)\n\t {\n\t c_value = null;\n\t }\n\telse\n\t {\n\t c_start = c_value.indexOf(\"=\", c_start) + 1;\n\t var c_end = c_value.indexOf(\";\", c_start);\n\t if (c_end == -1)\n\t {\n\tc_end = c_value.length;\n\t}\n\tc_value = unescape(c_value.substring(c_start,c_end));\n\t}\n\treturn c_value;\n}", "function Get_Cookie(name) { \n var start = document.cookie.indexOf(name+\"=\"); \n var len = start+name.length+1; \n if ((!start) && (name != document.cookie.substring(0,name.length))) return null; \n if (start == -1) return null; \n var end = document.cookie.indexOf(\";\",len); \n if (end == -1) end = document.cookie.length; \n return unescape(document.cookie.substring(len,end)); \n}", "function getCookie(name) {\r\n if (name === undefined) {\r\n return null;\r\n }\r\n name += '=';\r\n\r\n var i, c, ca = document.cookie.split(';'), len = ca.length;\r\n\r\n for (i = 0; i < len; ++i) {\r\n c = ca[i];\r\n while (c.charAt(0) === ' ') {\r\n c = c.substring(1, c.length);\r\n }\r\n if (c.indexOf(name) === 0) {\r\n return decodeURIComponent(c.substring(name.length, c.length));\r\n }\r\n }\r\n return null;\r\n }", "function GetCookie(name)\r\n{\r\n\tif(document.cookie.length > 0) {\r\n\t\tc_start = document.cookie.indexOf(name + \"=\");\r\n\t\tif(c_start != -1) {\r\n\t\t\tc_start = c_start + name.length + 1;\r\n\t\t\tc_end = document.cookie.indexOf(\";\", c_start);\r\n\t\t\tif(c_end == -1)\r\n\t\t\t\tc_end = document.cookie.length;\r\n\t\t\treturn unescape(document.cookie.substring(c_start, c_end));\r\n\t\t}\r\n\t}\r\n\r\n\treturn \"\";\r\n}", "static get(name) \r\n\t{\r\n\t if (document.cookie.length > 0) {\r\n\t let c_start = document.cookie.indexOf(name + \"=\");\r\n\t \r\n\t if (c_start != -1) {\r\n\t c_start = c_start + name.length + 1;\r\n\t let c_end = document.cookie.indexOf(\";\", c_start);\r\n\t \r\n\t if (c_end == -1) {\r\n\t c_end = document.cookie.length;\r\n\t }\r\n\r\n\t return JSON.parse(unescape(document.cookie.substring(c_start, c_end)));\r\n\t }\r\n\t }\r\n\r\n\t return {};\r\n\t}", "function getCookie(name) {\n var start = document.cookie.indexOf(name+\"=\");\n var len = start+name.length+1;\n if ((!start) && (name != document.cookie.substring(0,name.length))) return null;\n if (start == -1) return null;\n var end = document.cookie.indexOf(\";\",len);\n if (end == -1) end = document.cookie.length;\n return unescape(document.cookie.substring(len,end));\n}", "function getCookie(c_name){\n var i,x,y,ARRcookies=document.cookie.split(\";\");\n for (i=0;i<ARRcookies.length;i++){\n x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));\n y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);\n x=x.replace(/^\\s+|\\s+$/g,\"\");\n if (x==c_name){\n return unescape(y);\n }\n }\n}", "function getCookie(name) {\r\n var start = document.cookie.indexOf(name + \"=\");\r\n var len = start + name.length + 1;\r\n if ((!start) && (name != document.cookie.substring(0, name.length))) return null;\r\n if (start == -1) return null;\r\n var end = document.cookie.indexOf(\";\", len);\r\n if (end == -1) end = document.cookie.length;\r\n return unescape(document.cookie.substring(len, end));\r\n}", "function getCookie(c_name)\r\n{\r\n var i,x,y,ARRcookies=document.cookie.split(\";\");\r\n for (i=0;i<ARRcookies.length;i++)\r\n {\r\n x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));\r\n y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);\r\n x=x.replace(/^\\s+|\\s+$/g,\"\");\r\n if (x==c_name)\r\n {\r\n return unescape(y);\r\n }\r\n }\r\n \r\n return null;\r\n}", "function getCookie(name)\n{\n var name = name + \"=\";\n\n // Get cookie string and split it up by cookie\n var decodedCookie = decodeURIComponent(document.cookie);\n var ca = decodedCookie.split(';');\n\n // Loop through all cookies\n for(var i = 0; i < ca.length; i++)\n {\n var cookie = ca[i];\n while(cookie.charAt(0) == ' ')\n {\n cookie = cookie.substring(1);\n }\n\n // IF we find a match, return the value of that cookie\n if(cookie.indexOf(name) == 0)\n {\n return cookie.substring(name.length, cookie.length);\n }\n }\n return \"\";\n}", "function getCook(name) {\n let matches = document.cookie.match(new RegExp(\n \"(?:^|; )\" + name.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1') + \"=([^;]*)\"\n ));\n return matches ? decodeURIComponent(matches[1]) : undefined;\n }", "function getCookie(c_name)\n{\nvar i,x,y,ARRcookies=document.cookie.split(\";\");\nfor (i=0;i<ARRcookies.length;i++)\n {\n x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));\n y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);\n x=x.replace(/^\\s+|\\s+$/g,\"\");\n if (x==c_name)\n {\n return unescape(y);\n }\n }\n}", "function get_cookie(c_name) {\n var c_value = document.cookie;\n var c_start = c_value.indexOf(\" \" + c_name + \"=\");\n if (c_start === -1) {\n c_start = c_value.indexOf(c_name + \"=\");\n }\n if (c_start === -1) {\n c_value = \"\";\n } else {\n c_start = c_value.indexOf(\"=\", c_start) + 1;\n var c_end = c_value.indexOf(\";\", c_start);\n if (c_end === -1)\n {\n c_end = c_value.length;\n }\n c_value = unescape(c_value.substring(c_start, c_end));\n }\n return c_value;\n}", "function getCookie(name) {\n\n var arg = name + \"=\";\n\n var alen = arg.length;\n\n var clen = document.cookie.length;\n\n var i = 0;\n\n while (i < clen) {\n\n var j = i + alen;\n\n if (document.cookie.substring(i, j) == arg) {\n\n return getCookieVal(j);\n\n }\n\n i = document.cookie.indexOf(\" \", i) + 1;\n\n if (i == 0) break; \n\n }\n\n return \"\";\n\n}", "function getCookie(name) {\n\t\tvar key = name + \"=\";\n\t\tvar cookies = document.cookie.split(\";\");\n\t\tvar result = null;\n\t\t$.each(cookies, function(index, value) {\n\t\t\tvar thisCookie = value;\n\t\t\twhile (thisCookie.charAt(0) == \" \") {\n\t\t\t\tthisCookie = thisCookie.substring(1, thisCookie.length);\n\t\t\t}\n\t\t\tif (thisCookie.indexOf(key) == 0) {\n\t\t\t\tresult = thisCookie.substring(key.length, thisCookie.length);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t});\n\t\treturn result;\n\t}", "function getCookie(name)\n{\n\tvar s = document.cookie.indexOf(name + \"=\");\n\tif(s == -1) {\n\t\treturn null;\n\t}\n\ts += name.length + 1;\n\tvar e = document.cookie.indexOf(\";\", s);\n\tif(e == -1) {\n\t\te = document.cookie.length;\n\t}\n\treturn unescape(document.cookie.substring(s, e));\n}", "function Get_Cookie(name){var start=document.cookie.indexOf(name+'=');var len=start+name.length+1;if((!start)&&(name!=document.cookie.substring(0,name.length)))\nreturn null;if(start==-1)\nreturn null;var end=document.cookie.indexOf(';',len);if(end==-1)end=document.cookie.length;if(end==start){return'';}\nreturn unescape(document.cookie.substring(len,end));}", "function getCookie(c_name)\r\n{\r\nvar i,x,y,ARRcookies=document.cookie.split(\";\");\r\nfor (i=0;i<ARRcookies.length;i++)\r\n{\r\n x=ARRcookies[i].substr(0,ARRcookies[i].indexOf(\"=\"));\r\n y=ARRcookies[i].substr(ARRcookies[i].indexOf(\"=\")+1);\r\n x=x.replace(/^\\s+|\\s+$/g,\"\");\r\n if (x==c_name)\r\n {\r\n return unescape(y);\r\n }\r\n }\r\n}", "function getCookie(name) {\n var cookieName = name + '=';\n var ca = document.cookie.split(';');\n for (var i = 0; i < ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) === ' ') c = c.substring(1, c.length);\n if (c.indexOf(cookieName) === 0) return c.substring(cookieName.length, c.length);\n }\n return null;\n}", "function getCookie(name) {\n var dc = document.cookie;\n var prefix = name + \"=\";\n var begin = dc.indexOf(\"; \" + prefix);\n if (begin == -1) {\n begin = dc.indexOf(prefix);\n if (begin != 0) return null;\n }\n else\n {\n begin += 2;\n var end = document.cookie.indexOf(\";\", begin);\n if (end == -1) {\n end = dc.length;\n }\n }\n // because unescape has been deprecated, replaced with decodeURI\n //return unescape(dc.substring(begin + prefix.length, end));\n return decodeURI(dc.substring(begin + prefix.length, end));\n}", "function getCookie(name) {\n \n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n // Does this cookie string begin with the name we want?\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n //RETORNANDO EL TOKEN\n return cookieValue;\n\n }//end function getCookie", "function getCookie(name)\n{\n\tvar start = document.cookie.indexOf(name + \"=\");\n\tvar len = start + name.length + 1;\n\tif ((!start) && (name != document.cookie.substring(0, name.length))) return null;\n\tif (start == -1) return null;\n\tvar end = document.cookie.indexOf(';', len);\n\tif (end == -1) end = document.cookie.length;\n\treturn unescape(document.cookie.substring(len, end));\n}" ]
[ "0.83762145", "0.82966024", "0.82700825", "0.8269215", "0.8231766", "0.8228545", "0.8223539", "0.82220185", "0.82174534", "0.82174534", "0.82174534", "0.82174534", "0.82174534", "0.8206991", "0.82008797", "0.8199155", "0.8190016", "0.81881773", "0.8175136", "0.8173049", "0.8158401", "0.8148545", "0.81459945", "0.8145779", "0.81432366", "0.8141399", "0.81349635", "0.8123196", "0.81158555", "0.81158555", "0.8110552", "0.81095564", "0.8109001", "0.8107874", "0.81057733", "0.8097917", "0.80915684", "0.80870503", "0.80868614", "0.80868614", "0.80868614", "0.80860615", "0.80860364", "0.808077", "0.807945", "0.8078991", "0.80782443", "0.8077252", "0.8071442", "0.8060751", "0.8057222", "0.8055897", "0.80438364", "0.80428964", "0.8041956", "0.80417323", "0.8033569", "0.8028424", "0.8021812", "0.8016381", "0.80149657", "0.8011195", "0.80100113", "0.80030555", "0.8000879", "0.79936475", "0.79853976", "0.79773724", "0.7962295", "0.79597074", "0.7954733", "0.79515463", "0.79512006", "0.7949421", "0.7941061", "0.79367065", "0.79347056", "0.7932496", "0.7932272", "0.7930917", "0.792928", "0.7929079", "0.79229176", "0.7915139", "0.79121995", "0.7906714", "0.789823", "0.7896915", "0.78880835", "0.78835785", "0.7882562", "0.78769493", "0.7875353", "0.78644437", "0.7863462", "0.7857718", "0.78550583", "0.785447", "0.7851852", "0.78517395", "0.7848173" ]
0.0
-1
The functions below will create a header with csrftoken
function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "_applyHeaders(headers){\n\t\tif(!this.csrfToken) throw new Error('No CSRF Token provided use the setToken method first')\n\t\theaders.append('X-CSRF-TOKEN',this.csrfToken)\n\t\theaders.append('X-Requested-With','XMLHttpRequest')\n\t\tif(this.headers)this.headers.forEach(h => headers.append(h.name,h.value));\n\t\treturn headers\n\t}", "_getCSRFToken() {\n let that = this;\n return that._request('GET', that._getUrl('simplecsrf/token.json'), {}, that.localHeaders)\n .then(function (res) {\n console.log(\"CSRF\",res.body);\n that.csrf = res.body.token;\n });\n }", "function initialiseHeader(){\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n } \n });\n}", "function includeCSRFToken ({ method, csrf=true, headers }) {\n if (!csrf || !CSRF_METHODS.includes(method)) return\n const token = getTokenFromDocument(csrf)\n if (!token) return\n return {\n headers: { ...headers, 'X-CSRF-Token': token }\n }\n}", "getSecureHeader() {\n let token = sessionStorage.getItem('auth_token');\n // To access data from the server while authenticated the\n // token must be included in the request.\n let headers = new _angular_common_http__WEBPACK_IMPORTED_MODULE_1__[\"HttpHeaders\"]();\n headers = headers.set('Content-Type', 'application/json; charset=utf-8');\n headers = headers.append('Authorization', 'Bearer ' + token);\n return headers;\n }", "function handleCsrfToken(){\n var token = $(\"meta[name='_csrf']\").attr(\"content\");\n var header = $(\"meta[name='_csrf_header']\").attr(\"content\");\n $(document).ajaxSend(function(e, xhr, options) {\n xhr.setRequestHeader(header, token);\n });\n }", "function setAuthHeaders(xhr) {\n var timeStamp = toISOString(new Date());\n var signatureHash = CryptoJS.HmacSHA1(timeStamp, sessionData.auth.secret).toString();\n\n xhr.setRequestHeader('x-authtoken', sessionData.auth.authtoken);\n xhr.setRequestHeader('x-signature', signatureHash);\n xhr.setRequestHeader('x-request-timestamp', timeStamp);\n}", "function addRestCsrfCustomHeader(xhr, settings) {\n// if (settings.url == null || !settings.url.startsWith('/webhdfs/')) {\n\t if (settings.url == null ) {\n return;\n }\n var method = settings.type;\n if (restCsrfCustomHeader != null && !restCsrfMethodsToIgnore[method]) {\n // The value of the header is unimportant. Only its presence matters.\n if (restCsrfToken != null) {\n xhr.setRequestHeader(restCsrfCustomHeader, restCsrfToken);\n } else {\n xhr.setRequestHeader(restCsrfCustomHeader, '\"\"');\n }\n }\n }", "function setCsrfToken(request, response, next) {\n response.cookie('XSRF-TOKEN', request.csrfToken());\n next();\n}", "get noTokenHeader() {\n return new HttpHeaders({\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-cache',\n Pragma: 'no-cache',\n Expires: 'Sat, 01 Jan 2000 00:00:00 GMT'\n });\n }", "function getSecurityHeaders() {\n\n var headers = {\n ModuleId: servicesFramework.getModuleId(),\n TabId: servicesFramework.getTabId(),\n };\n\n var antiForgeryKey = servicesFramework.getAntiForgeryKey();\n\n headers[antiForgeryKey] = servicesFramework.getAntiForgeryValue();\n\n // for some reason this is what DNN accepts for ValidateAntiForgeryToken\n headers[\"RequestVerificationToken\"] = servicesFramework.getAntiForgeryValue();\n\n return headers;\n }", "function attachCSRF(req, csrftoken) {\n if (shouldSendCSRF(req.method)) {\n req.headers['X-CSRFToken'] = csrftoken\n }\n return req\n}", "function ajaxCsrfToken() {\n\t$.ajaxSetup({\n\t headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }\n\t});\n}", "get authHeader() {\n const localStorageToken = localStorage.getItem(this.config.jwtTokenName);\n const token = localStorageToken ? 'Bearer ' + localStorageToken : '';\n const authHeader = new HttpHeaders({\n Authorization: token,\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-cache',\n Pragma: 'no-cache',\n Expires: 'Sat, 01 Jan 2000 00:00:00 GMT'\n });\n return authHeader;\n }", "function createHeaders(token, contentLength){\n var headers ={\n 'Authorization': 'Bearer ' + token,\n 'Content-Type': 'application/json'\n };\n \n return headers;\n}", "function newToken() {\n $.ajaxSetup({\n dataType: \"json\",\n contentType: \"application/json\",\n headers: {\n Authorization: \"Bearer \" + localStorage.getItem(\"TOKEN\")\n }\n });\n}", "setHeader() {\n if (this.hasValidToken()) {\n axios.defaults.headers.common['Authorization'] = `Bearer ${this.token}`;\n }\n }", "axPost (url, data, token = null) {\n let req = Object.assign({}, defaultRequest('post', url), { data })\n\n if (token) {\n req.headers['Authorization'] = `Token ${token}`\n }\n\n return req\n }", "csrfToken() {\n if (!this.isSafe() && !this.isCrossOrigin()) {\n return up.protocol.csrfToken()\n }\n }", "function makeHeaders(token, json) {\n let headers = {};\n if (token) {\n headers['access_token'] = token;\n }\n if (json) {\n headers['Content-Type'] = 'application/json';\n }\n return headers;\n}", "static token() {\n return document.querySelector('meta[name=\"csrf-token\"]').content\n }", "function getTokenedRequest (cb) {\n request({\n url: getUrl('frcsTkn'),\n headers: {\n 'X-CSRF-Token': 'Fetch'\n },\n json: true\n }, function (err, res, body) {\n if (err) return cb(err)\n var cookie = res.headers &&\n res.headers['set-cookie'] &&\n res.headers['set-cookie'][0].split(';')[0]\n var tokenedRequest = request.defaults({\n headers: {\n 'X-CSRF-Token': body.data.token,\n 'Cookie': cookie\n },\n json: true\n })\n cb(null, tokenedRequest)\n })\n}", "function set_token($token){\n $.AMUI.utils.cookie.set('s_token',$token);\n set_headers();\n }", "function getCsrfToken(request) {\n return request.headers['x-xsrf-token'];\n}", "function setCsrfToken () {\n return function* setCsrfCookieMidleware (next) {\n yield next\n if (this.session)\n this.cookies.set('XSRF-TOKEN', this.csrf, {httpOnly: false})\n }\n}", "function addToken(config) {\n var token = authService.getToken();\n if (token) {\n config.headers = config.headers || {};\n config.headers.Token = token;\n }\n var company = authService.getCompany();\n if (company) {\n config.headers = config.headers || {};\n config.headers.CompanyId = company.id;\n }\n return config;\n }", "function getCSRFToken() {\r\n var csrfToken = $('#forgeryToken').val();\r\n return csrfToken;\r\n }", "headers () {\n return {\n 'content-type': 'application/json',\n 'accept': 'application/json',\n 'Authorization': localStorage.getItem('jwt')\n }\n }", "function fetchHeaders() {\n // x-csrf-token\n let requiredHeaders = new Set(['authorization', document.cookie.indexOf('twid') > -1 ? 'x-csrf-token' : 'x-guest-token']);\n let headers = {};\n\n return new Promise((resolve, reject) => {\n (function(setRequestHeader) {\n XMLHttpRequest.prototype.setRequestHeader = function(key, value) {\n let shouldResolve = false;\n if (requiredHeaders.has(key)) {\n headers[key] = value;\n shouldResolve = Object.keys(headers).length === requiredHeaders.size;\n } \n setRequestHeader.apply(this, arguments);\n\n if (shouldResolve) {\n // restore to default handler\n XMLHttpRequest.prototype.setRequestHeader = setRequestHeader;\n }\n resolve(headers);\n };\n })(XMLHttpRequest.prototype.setRequestHeader);\n });\n}", "function csrfSafeSend(xhr, settings){\n if (!csrfSafeMethod(settings.type) && !this.crossDomain) {\n xhr.setRequestHeader(\"X-CSRFToken\", csrftoken);\n }\n\n}", "function wrapJwtInHeader(token) {\n return { headers: { Authorization: 'Bearer ' + token } };\n}", "function setCSRF_Token_ajax(){\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n }", "function csrf($httpProvider) {\n // CSRF Support\n $httpProvider.defaults.xsrfCookieName = 'csrftoken';\n $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';\n}", "function csrf($httpProvider) {\n // CSRF Support\n $httpProvider.defaults.xsrfCookieName = 'csrftoken';\n $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';\n}", "function authToken() {\n return $('meta[name=\"csrf-token\"]').attr('content');\n}", "function setJWTinHeader(jwt) {\n Axios.defaults.headers.common[\"x-jwt\"] = jwt;\n}", "async getHeaders(options) {\n let headers = {};\n if (options && options.headers) {\n // customise headers\n const { headers: customHeaders } = options;\n headers = customHeaders;\n return headers;\n }\n const token = localStorage.getItem(\"token\");\n if (token && typeof token === \"string\") headers.Authorization = `bearer ${token.replace(/['\"]+/g, \"\")}`;\n headers[\"Content-Type\"] = \"application/json\";\n headers = { ...headers };\n return headers;\n }", "setHeader(state) {\n const id_token = localStorage.getItem('id_token')\n state.authenticated = !!id_token\n if (state.authenticated) {\n ApiService\n .setHeader(localStorage.getItem('id_token'))\n }\n }", "function csrfcookie() {\n var cookieValue = null,\n name = 'csrftoken';\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}", "function ensureToken(req, res, next){\n const bearerHeader = req.headers[\"authorization\"];\n if (typeof bearerHeader != 'undefined') {\n const bearer = bearerHeader.split(\" \");\n const bearerToken = bearer[1];\n req.token = bearerToken;\n next();\n } else {\n res.sendStatus(403);\n }\n}", "function appendCsrfTokenToForm() {\r\n\tif (window.redcap_csrf_token) {\r\n\t\tsetTimeout(function(){ \r\n\t\t\t$('form').each(function(){ \r\n\t\t\t\t$(this).append('<input type=\"hidden\" name=\"redcap_csrf_token\" value=\"'+redcap_csrf_token+'\">') \r\n\t\t\t});\r\n\t\t},100); \r\n\t}\r\n}", "static post(option) {\n \n return $.ajax({\n\n type: 'POST',\n url: option.url,\n data: JSON.stringify(option.data),\n dataType: 'json',\n contentType: 'application/json',\n beforeSend: (xhr) => {\n xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('auth_token')}`);\n }\n });\n }", "function createCookieToken(token) {\n setCookie(\"token\", token);\n}", "function configure($httpProvider, CSRF_TOKEN) {\n $httpProvider.defaults.headers.common[\"X-Csrf-Token\"] = CSRF_TOKEN;\n $httpProvider.defaults.headers.common[\"X-Requested-With\"] = \"XMLHttpRequest\";\n }", "function csrfcookie () {\n var cookieValue = null,\n name = 'csrftoken';\n if (document.cookie && document.cookie !== '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = cookies[i].trim();\n if (cookie.substring(0, name.length + 1) == (name + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(name.length + 1));\n break;\n }\n }\n }\n return cookieValue;\n}", "static getBearerAuthHeader(token) {\n return { Authorization: 'Bearer ' + token };\n }", "get apiHeader() {\n const token = this.apiKey ? 'Bearer ' + this.apiKey : '';\n const apiHeader = new HttpHeaders({\n Authorization: token,\n 'Content-Type': 'application/json',\n 'Cache-Control': 'no-cache',\n Pragma: 'no-cache',\n Expires: 'Sat, 01 Jan 2000 00:00:00 GMT'\n });\n return apiHeader;\n }", "function makeAuthToken() {\n var token = 'Auth'+ new Date().getTime();\n\n return token;\n }", "function request(config) {\n config.headers = config.headers || {};\n if ($cookieStore.get('token')) {\n config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');\n }\n return config;\n }", "function addAuthHeaderFromCookie() {\n return compose()\n .use(function(req, res, next) {\n if(req.cookies.token) {\n req.headers.authorization = 'Bearer ' + _.trim(req.cookies.token, '\\\"');\n }\n return next();\n });\n}", "getAuthHeader(token) {\n return {\n Authorization: `Bearer ${token}`,\n };\n }", "function setGlobalSessionInfo(res, jqXHR){\n\tCSRF_ParamName = jqXHR.getResponseHeader('X-CSRF-PARAM');\n\tCSRF_token = jqXHR.getResponseHeader('X-CSRF-TOKEN');\n}", "function createHeaderForRequest(request)\n{\n\trequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');\n\trequest.setRequestHeader('username', currentUser.getUsername());\n\trequest.setRequestHeader('jid', currentUser.getJid());\n\trequest.setRequestHeader('country', 'tw');\n\trequest.setRequestHeader('timezone', '8');\n}", "getAuthHeader () {\n return {\n 'Authorization': 'Bearer ' + window.localStorage.getItem('id_token')\n }\n }", "static getAuthHeader() {\n let token = AuthService.getAuthToken();\n if (token) {\n return {\n 'Authorization': 'Bearer ' + AuthService.getAuthToken()\n };\n } else {\n return {};\n }\n }", "function ensureToken(req, res, next) {\n const bearerHeader = req.headers[\"authorization\"];\n if (typeof bearerHeader !== 'undefined') {\n req.token = bearerHeader;\n next();\n } else {\n res.status(200).json({ error: \"Unauthorized access\" });\n }\n}", "function setJwt(jwt) {\n axios.defaults.headers.common['x-auth-token'] = jwt;\n}", "getAuthHeader() {\n return {\n 'Authorization': 'Bearer ' + localStorage.getItem('id_token')\n }\n }", "bless(request) {\n // create headers if does not already exist\n if(request.headers == null) request.headers = {}\n // assign authentication bearer token\n request.headers[\"Authorization\"] = \"Bearer \" + this.token;\n return request;\n }", "headers(options = {}) {\n let headers = Object.assign({},\n {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n ReactOnRails.authenticityHeaders(),\n options);\n\n\n return headers;\n }", "function preBuild() {\n\tvar form = new FormData();\t\n\tform.append('token', session_token);\t\n\treturn form;\n}", "setAuthHeader (token = '') {\n axios.defaults.headers.common['Authorization'] = `Bearer ${token}`\n }", "setHeaders(res){\n res.set('x-timestamp', Date.now())\n }", "function getCSRFToken() {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n if (cookie.substring(0, 10) == ('csrftoken' + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(10));\n break;\n }\n }\n }\n return cookieValue;\n}", "function getToken() {\n var meta = document.querySelector(\"meta[name=\\\"csrf-token\\\"]\");\n return meta && meta.getAttribute('content');\n}", "function request(config) {\n\t var token = $sessionStorage.authData && $sessionStorage.authData.Token;\n\t\n\t if (token) {\n\t config.headers.Authorization = token;\n\t config.headers = config.headers || {};\n\t }\n\t\n\t return config;\n\t }", "function ensureToken(req, res, next) {\n var headerToken = req.header(\"token\");\n var bodyToken = req.body.token;\n if ((!headerToken || headerToken.length < 1) && (!bodyToken || bodyToken.length < 1)){\n res.json({success: false, message: \n \"Token is invalid. Please try clearing browsing history and logging in again\"});\n }\n else{\n logger(\"ensured that token was provided. continuing with request...\");\n if (headerToken && headerToken.length > 0){ next(headerToken) }\n else{\n next(bodyToken);\n }\n }\n}", "request(config) {\n config.headers = config.headers || {};\n if(localStorageService.get('token') && Util.isSameOrigin(config.url)) {\n config.headers.Authorization = localStorageService.get('token');\n }\n return config;\n }", "function setAuthHeaders() {\n var token = AuthStorage.getToken();\n if (token) {\n $http.defaults.headers.common.Authorization = token;\n } else {\n $http.defaults.headers.common.Authorization = '';\n }\n }", "static getApiAuthHeader() {\n return {'authorization': `bearer ${Auth.getToken()}`};\n }", "function checkAndAddHeaders(args){\n\t\t// check if we have headers object\n\t\tif (args.headers) {\n\t\t\t// we do, check if we have csrfid\n\t\t\tif (args.headers.csrfid) {\n\t\t\t\t// we do just print and continue\n\t\t\t\tconsole.debug('Found a csrfid ' + args.headers.csrfid);\n\t\t\t} else {\n\t\t\t\t// we do not, add csrfid to existing header\n\t\t\t\targs.headers.csrfid = getCookie('com.ibm.ws.console.CSRFToken');\n\t\t\t}\n\t\t} else {\n\t\t\t// add headers\n\t\t\targs.headers= {\n\t\t \tcsrfid: getCookie('com.ibm.ws.console.CSRFToken')\n\t \t};\n\t\t\t\n\t\t}\n\t}", "function soaringSpotAuthHeaders( keys ) {\n\n // This is used to confirm all is fine\n const nonce = crypto.randomBytes(30).toString('base64');\n\n // Form the message\n const dt = new Date().toISOString();\n const message = nonce + dt + keys.client_id;\n\n // And hash it\n const hash = crypto.createHmac('sha256', keys.secret).update(message).digest('base64');\n const auth_header = 'http://api.soaringspot.com/v1/hmac/v1 ClientID=\"'+keys.client_id+'\", Signature=\"'+hash+'\", Nonce=\"'+nonce+'\", Created=\"'+dt+'\"';\n\n return {\n headers: {\n 'Authorization': auth_header\n }\n };\n}", "function getCSRFToken()\n\t{\n\t\tvar input = document.getElementById(\"csrftoken\");\n\t\treturn input.value;\n\t\t\n\t}", "function setHeaders(apiKey, secret, path, method_, body, headers) {\n var strBody = stringifyOption(body);\n var timestamp = String(floor(Date.now() / 1000.0));\n var hmac = CryptoJs.HmacSHA256(methodName(method_) + (timestamp + (path + strBody)), secret);\n var signature = EncBase64.stringify(hmac);\n headers[\"X-Swp-Api-Key\"] = apiKey;\n headers[\"X-Swp-Signature\"] = signature;\n headers[\"X-Swp-Timestamp\"] = timestamp;\n return /* () */0;\n}", "setAuthHeader(token) {\n if (token) {\n apiAxios.defaults.headers.common['Authorization'] = `Bearer ${token}`;\n } else {\n delete apiAxios.defaults.headers.common['Authorization'];\n }\n }", "getAuthHeader() {\n return {\n 'Authorization': 'Bearer ' + localStorage.getItem('access_token')\n }\n }", "function appendCSRF(url) {\n if (lastCsrfToken) {\n url = (url.indexOf('?') === -1) ? url + '?' : url + '&';\n url += 'csrf_token=' + lastCsrfToken;\n }\n return url;\n}", "function getCSRFToken() {\n var cookieValue = null;\n if (document.cookie && document.cookie != '') {\n var cookies = document.cookie.split(';');\n for (var i = 0; i < cookies.length; i++) {\n var cookie = jQuery.trim(cookies[i]);\n if (cookie.substring(0, 10) == ('csrftoken' + '=')) {\n cookieValue = decodeURIComponent(cookie.substring(10));\n break;\n }\n }\n }\n return cookieValue;\n }", "function verified_token(req,res, next){\n const bearerHeader=req.headers['authorization'];\n if(typeof bearerHeader!=='undefined'){\n\n //remove space\n const bearer=bearerHeader.split(' ');\n // console.log(bearer)\n const bearerToken=bearer[1];\n console.log(bearerToken)\n req.token=bearerToken;\n // return res.send(bearerToken)\n // next middleware \n next()\n }else{ \n console.log(\"undefine values\")\n res.sendStatus(403);\n } \n}", "function generateOauthHeader(url, method, oauthToken = '', extraHeaders = {}, formData = {}) {\n if (!url || !method) {\n return '';\n }\n\n const authObject = Object.assign({\n oauth_consumer_key: process.env.TWITTER_CONSUMER_KEY,\n oauth_nonce: generateNonce(),\n oauth_signature_method: 'HMAC-SHA1',\n oauth_timestamp: Math.floor(new Date() / 1000),\n oauth_version: '1.0'\n }, extraHeaders);\n\n authObject.oauth_signature = generateSignature(\n url,\n method,\n Object.assign(authObject, formData),\n process.env.TWITTER_SECRET_KEY,\n oauthToken\n );\n\n return authObject;\n}", "function setToken(token) {\n $http.defaults.headers.common.Authorization = 'Bearer ' + token;\n }", "function attachCsrfToken(url, cookie, value) {\n return (req, res, next) => {\n if (req.url == url) {\n res.cookie(cookie, value);\n }\n next();\n };\n}", "prepareHeaders(value = null) {\n const headers = {\n API_KEY: API.HOST_API_KEY // always send api key with every request header\n };\n if (this.sessionId) {\n headers.SESSION_ID = this.sessionId; // always send session id with every request header\n }\n if (typeof value === 'string' && value != null) {\n headers['Content-Type'] = 'text/plain;charset=utf-8';\n } else {\n headers['Content-Type'] = 'application/json;charset=utf-8';\n }\n return headers;\n }", "#genHeaders(headerNames) {\n\t\tconst headers = {};\n\n\t\tif (headerNames.includes('Content-Type')) headers['Content-Type'] = 'application/x-www-form-urlencoded';\n\t\tif (headerNames.includes('Authorization')) headers['Authorization'] = `OAuth ${this.accessToken}`;\n\n\t\treturn headers;\n\t}", "function fetchWithCSRFToken(url, otherParts, headers = {}) {\n const csrfToken = getCookie(\"csrftoken\");\n const defaultHeaders = {\n \"X-CSRFToken\": csrfToken\n };\n const combinedHeaders = Object.assign({}, defaultHeaders, headers);\n return fetch(\n url,\n Object.assign({}, otherParts, { headers: combinedHeaders })\n );\n}", "function sign(req, resp, next) {\n const { url, method = 'GET', params = {}, headers = {} } = req.body\n\n headers['x-bce-date'] = new Date().toISOString()\n const signature = auth.generateAuthorization(method, url, params, headers, undefined, undefined, ['Host'])\n\n headers['Authorization'] = signature\n req.body.headers = headers\n\n next()\n}", "signRequest(webResource) {\n return __awaiter(this, void 0, void 0, function* () {\n const tokenResponse = yield this.getToken();\n webResource.headers.set(ms_rest_js_1.Constants.HeaderConstants.AUTHORIZATION, `${tokenResponse.tokenType} ${tokenResponse.accessToken}`);\n return webResource;\n });\n }", "token(value){ window.localStorage.setItem('token', value)}", "destroyToken() {\n axios.defaults.headers.common = {};\n localStorage.removeItem(btoa('token'));\n }", "function getToken(request, response) {\n\n // let token=request.headers['x-access-token'] || request.headers['Authorization'];\n try {\n var re = new RegExp('Bearer (.*)');\n var r = request.headers['authorization'].match(re);\n var token = r[1];\n }\n catch (err) {\n console.log(err);\n }\n return token;\n}", "function createAuthToken(ctx, builderFn) {\n const authToken = builderFn(ctx);\n authToken.setUseStubAuth(\n !!ctx.request.headers[constants.UDS_BVT_REQUEST_HEADER],\n );\n return authToken;\n}", "function verificarToken(req, res, next) {\n const bearerHeader = req.headers['Authorization'];\n \n if (typeof bearerHeader !== 'undefined') {\n const bearer = bearerHeader.split(' ');\n const bearerToken = bearer[1];\n req.token = bearerToken;\n console.log(bearerToken);\n next();\n } else {\n res.sendStatus(403);\n }\n}", "function verifTokenInHeaders(req, res, next) {\nif( extractAndVerifToken(req.headers.authorization))\nnext();\nelse\nres.status(401).send(null);//401=Unautorized or 403=Forbidden\n}", "function createToken() {\n stripe.createToken($scope.card).then(function(result) {\n if (result.error) {\n $scope.cardError = result.error.message;\n $scope.submitting = false;\n } else {\n // Send the token to your server\n stripeTokenHandler(result.token);\n }\n });\n }", "function getBearerTokenHeader() {\n return {\n 'authorization': `Bearer ${process.env.BEARER_TOKEN}`\n };\n}", "function csrfPOST(action, form_el, success) {\n var csrftoken = getCookie(\"csrftoken\");\n if (csrftoken === null) {\n console.log(\"CSRF cookie not found!\");\n return;\n }\n $.ajax({\n url: action,\n type: \"POST\",\n headers: {\"X-CSRFToken\": csrftoken},\n data: form_el.serialize(),\n dataType: \"json\",\n success: success\n });\n}", "function setupXHR() {\n const csrfUnsafeMethod = method => !(/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));\n\n $.ajaxSetup({\n beforeSend: (xhr, settings) => {\n if (csrfUnsafeMethod(settings.type)) {\n xhr.setRequestHeader('X-CSRFToken', Cookies.get('csrftoken'));\n }\n },\n });\n }", "function createHeader (authType, methodType, userData) {\n const header = {\n method: methodType,\n headers: {\n 'Authorization': authentication(authType),\n 'Content-Type':'application/json'\n }\n };\n if(methodType === 'POST' || methodType === 'PUT'){\n header.body = JSON.stringify(userData);\n };\n\n return header;\n}", "function setHeader(xhr) {\n xhr.setRequestHeader('X-Mashape-Key', 'This has been removed.');\n}", "function setHeaderRequest(){\n return { headers: { 'Content-Type': 'application/json; charset=utf-8' }}\n }", "csrfToken() {\n let selector = document.querySelector('meta[name=\"csrf-token\"]');\n\n if (this.options.csrfToken) {\n return this.options.csrfToken;\n } else if (selector) {\n return selector.getAttribute('content');\n }\n\n return null;\n }" ]
[ "0.71804297", "0.67748964", "0.6758145", "0.6676204", "0.6669014", "0.66189396", "0.65342796", "0.6527486", "0.64885753", "0.64783436", "0.64601994", "0.6452166", "0.6411458", "0.6408495", "0.637205", "0.63708967", "0.6355116", "0.6311636", "0.6299637", "0.62848836", "0.62478495", "0.6234922", "0.6224269", "0.617766", "0.6170238", "0.6167554", "0.61607593", "0.6089541", "0.6056965", "0.6049239", "0.60379523", "0.60319555", "0.60265267", "0.60265267", "0.6025286", "0.5960834", "0.59484303", "0.59354377", "0.5924276", "0.5920101", "0.5917583", "0.5912418", "0.5892814", "0.58867085", "0.5885843", "0.5883417", "0.5875611", "0.5874939", "0.58443576", "0.5811643", "0.58096975", "0.580951", "0.58023316", "0.5797577", "0.5789539", "0.57661235", "0.57625383", "0.57527685", "0.57519275", "0.57475907", "0.574654", "0.57195926", "0.57115424", "0.571048", "0.5693039", "0.5692773", "0.5687529", "0.56811726", "0.56790197", "0.56749254", "0.5674601", "0.5666831", "0.5663507", "0.5648054", "0.56390876", "0.5621986", "0.56095773", "0.5597624", "0.55948466", "0.5593021", "0.5589325", "0.5587516", "0.55774885", "0.5576121", "0.5556375", "0.5549871", "0.5523612", "0.55158246", "0.5513812", "0.5502644", "0.5497083", "0.54849446", "0.5471536", "0.5466047", "0.5459918", "0.54543644", "0.5454148", "0.54532653", "0.54510784", "0.54501706", "0.54482883" ]
0.0
-1
Not needed if render is part of 60fps animation routine controls.addEventListener('change', render); Our preferred controls via DeviceOrientation
function setOrientationControls(e) { if (!e.alpha) { return; } controls = new THREE.DeviceOrientationControls(camera, true); controls.connect(); controls.update(); renderer.domElement.addEventListener('click', fullscreen, false); window.removeEventListener('deviceorientation', setOrientationControls, true); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function onScreenOrientationChange(event){\n\tcontrols.disconnect();\n\tif (window.innerWidth > window.innerHeight) camera = new THREE.PerspectiveCamera( 75, window.innerHeight / window.innerWidth, 1, 1100 );\n\telse camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 1100 );\n\trenderer.setSize( window.innerWidth, window.innerHeight );\n\tcontrols = new DeviceOrientationController( camera, renderer.domElement );\n\tcontrols.connect();\n\tinfo.innerHTML += \"<br>rotation\"; \n}", "function setOrientationControls(e) {\r\n\tif (e.alpha) {\r\n\t\tinitVRControls ();\r\n\t}\r\n\telse {\r\n\t\tinitbrowserControls ();\r\n\t\tvar camera = entities.cameras.perspCamera;\r\n\t\tentities.cameras.position.init( camera );\r\n\t}\r\n}", "function setOrientationControls(e) {\n if (!e.alpha) {\n return;\n }\n\n controls = new THREE.DeviceOrientationControls(camera, true);\n controls.connect();\n controls.update();\n\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n }", "function setOrientationControls(e) {\n if (!e.alpha) {\n return;\n }\n\n controls = new THREE.DeviceOrientationControls(camera, true);\n controls.connect();\n controls.update();\n\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n }", "function setOrientationControls(e) {\n if (!e.alpha) {\n return;\n }\n self.controls = new THREE.DeviceOrientationControls(this.camera, true);\n self.controls.connect();\n self.controls.update();\n self.element.addEventListener('click', fullscreen, false);\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n }", "function setOrientationControls(e) {\n if (!e.alpha) {\n return;\n }\n\n controls = new THREE.DeviceOrientationControls(camera, true);\n controls.connect();\n controls.update();\n\n element.addEventListener('click', fullscreen, false);\n\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n }", "function setOrientationControls(e) {\r\n if (!e.alpha) {\r\n return;\r\n }\r\n\r\n controls = new THREE.DeviceOrientationControls(camera, true);\r\n controls.connect();\r\n controls.update();\r\n\r\n element.addEventListener('click', fullscreen, false);\r\n\r\n window.removeEventListener('deviceorientation', setOrientationControls, true);\r\n }", "function setOrientationControls(e) {\n if (!e.alpha) {\n return;\n }\n\n // controls = new THREE.OrbitControls(camera, true);\n // controls.connect();\n // controls.update();\n\n element.addEventListener('click', fullscreen, false);\n\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n }", "function setOrientationControls(e) {\n if (! e.alpha) {\n return;\n }\n cbm.controls = new THREE.DeviceOrientationControls(cbm.camera, true);\n cbm.controls.connect();\n cbm.controls.update();\n cbm.element.addEventListener('click', fullscreen, false);\n window.removeEventListener('deviceorientation', setOrientationControls, true);\n}", "function handleOrientationChange() {\n setTimeout(function() {\n calculateDeviceOrientation();\n }, 500);\n }", "function deviceOrientationTest(event) \n{\n window.removeEventListener('deviceorientation', deviceOrientationTest);\n if (event.beta != null && event.gamma != null) \n\t\t{\n window.addEventListener('deviceorientation', onDeviceOrientationChange, false);\n movementTimer = setInterval(onRenderUpdate, 10); \n }\n}", "function updateOrientation(e) {\n var a = Math.round(e.alpha); // Left and Right\n var g = Math.round(e.gamma);// Up and down\n // The below rules for fixing gamma and alpha were found by watching initial values and playing with the phone\n // Fix gamma so it doesn't jump\n if(g < 0)\n {\n g+=180;\n }\n\n g -= 90;\n g = g > CamMotion.verticalMax ? CamMotion.verticalMax : g;\n g = g < CamMotion.verticalMin ? CamMotion.verticalMin : g;\n \n // Fix alpha so it doesn't jump\n // There are different rules if gamma is more than or less than 0\n if(g > 0)\n {\n a -= 180; \n }\n else\n {\n if(a > 180)\n {\n a -= 360;\n }\n }\n a = a > CamMotion.horizontalMax ? CamMotion.horizontalMax : a;\n a = a < -CamMotion.horizontalMax ? -CamMotion.horizontalMax : a;\n \n // This may be useful for debugging other phones someday so leaving it here\n //$('#rotAlpha').text(a);\n //$('#rotBeta').text(b);\n //$('#rotGamma').text(g);\n \n CamMotion.vertical = -g;\n CamMotion.horizontal = -a;\n\n // Update the tilt display\n updateTiltDot();\n \n // Safely send the new info\n safeSendData();\n }", "function cameraVideoPageInitialised()\n{\n function handleOrientation(event)\n {\n var absolute = event.absolute;\n var alpha = event.alpha;\n var beta = event.beta;\n var gamma = event. gamma;\n }// Step 1: Check for and intialise deviceMotion\n cameraVideoPage.setHeadsUpDisplayHTML(absolute);\n cameraVideoPage.setHeadsUpDisplayHTML(alpha);\n cameraVideoPage.setHeadsUpDisplayHTML(beta);\n cameraVideoPage.setHeadsUpDisplayHTML(gamma);\n \n}", "rotateCamera(){\n\t\tif(this.state.rotationIndex==1){\n\t\t\tdocument.getElementById('on1').setAttribute('set_bind','true');\n\t\t\tthis.setState({rotationIndex: 2, in: 87, out: 83, left: 65, right: 68});\n\t\t}else if(this.state.rotationIndex==2){\n\t\t\tdocument.getElementById('on2').setAttribute('set_bind','true');\n\t\t\tthis.setState({rotationIndex: 3, in: 65, out: 68, left: 83, right: 87});\n\t\t}else if(this.state.rotationIndex==3){\n\t\t\tdocument.getElementById('on3').setAttribute('set_bind','true');\n\t\t\tthis.setState({rotationIndex: 4, in: 83, out: 87, left: 68, right: 65});\n\t\t}else if(this.state.rotationIndex==4){\n\t\t\tdocument.getElementById('on4').setAttribute('set_bind','true');\n\t\t\tthis.setState({rotationIndex: 1, in: 68, out: 65, left: 87, right: 83});\n\t\t}\n\t}", "function DeviceOrientationControlMethod() {\n this._dynamics = {\n yaw: new Marzipano.Dynamics(),\n pitch: new Marzipano.Dynamics()\n };\n\n this._deviceOrientationHandler = this._handleData.bind(this);\n\n if (window.DeviceOrientationEvent) {\n window.addEventListener('deviceorientation', this._deviceOrientationHandler);\n } else {\n alert('DeviceOrientationEvent not defined');\n }\n\n this._previous = {};\n this._current = {};\n this._tmp = {};\n\n this._getPitchCallbacks = [];\n}", "function cameraUpdateOrientation()\n {\n if(CamMotion.UP || CamMotion.DOWN || CamMotion.RIGHT || CamMotion.LEFT)\n {\n if(CamMotion.UP)\n {\n CamMotion.vertical += CamMotion.rotationSpeed;\n CamMotion.vertical = CamMotion.vertical > CamMotion.verticalMax ? CamMotion.verticalMax : CamMotion.vertical;\n }\n if(CamMotion.DOWN)\n {\n CamMotion.vertical -= CamMotion.rotationSpeed;;\n CamMotion.vertical = CamMotion.vertical < CamMotion.verticalMin ? CamMotion.verticalMin : CamMotion.vertical;\n }\n if(CamMotion.RIGHT)\n {\n CamMotion.horizontal += CamMotion.rotationSpeed;;\n CamMotion.horizontal = CamMotion.horizontal > CamMotion.horizontalMax ? CamMotion.horizontalMax : CamMotion.horizontal;\n }\n if(CamMotion.LEFT)\n {\n CamMotion.horizontal -= CamMotion.rotationSpeed;;\n CamMotion.horizontal = -CamMotion.horizontal > CamMotion.horizontalMax ? -CamMotion.horizontalMax : CamMotion.horizontal;\n }\n // Update the tilt display\n updateTiltDot();\n // Send new info only if the last packet hasn't been sent, helps with slow connections\n safeSendData();\n }\n }", "function update()\n {\n // Send time to shaders\n var delta = clock.getDelta();\n landscapeUniforms.time.value += delta;\n landscapeMaterial.needsUpdate = true;\n\n // Move\n controls.update();\n }", "function deviceOrientationTest(event) {\n\twindow.removeEventListener('deviceorientation', deviceOrientationTest);\n\twindow.addEventListener('deviceorientation', onDeviceOrientationChange, false);\n\tmovementTimer = setInterval(onRenderUpdate, 10); \n\t//if (event.beta != null && event.gamma != null) {\n\t\t//alert(event.beta + \" \" + event.gamma); \n\t\t//window.addEventListener('deviceorientation', onDeviceOrientationChange, false);\n\n\t//}\n}", "function init() {\n //Find our div containers in the DOM\n var dataContainerOrientamation = document.getElementById('dataContainerOrientation');\n var dataContainerMotion = document.getElementById('dataContainerMotion');\n \n //Check for support for DeviceOrientation event\n if(window.DeviceOrientationEvent) {\n window.addEventListener('deviceorientation', function(event) {\n alpha = event.alpha;\n beta = event.beta;\n gamma = event.gamma;\n }, true);\n } \n \n /*\n // Check for support for DeviceMotion events\n if(window.DeviceMotionEvent) {\n window.addEventListener('devicemotion', function(event) {\n alpha = event.accelerationIncludingGravity.x;\n beta = event.accelerationIncludingGravity.y;\n gamma = event.accelerationIncludingGravity.z;\n var r = event.rotationRate;\n var html = 'Acceleration:<br />';\n html += 'x: ' + x +'<br />y: ' + y + '<br/>z: ' + z+ '<br />';\n html += 'Rotation rate:<br />';\n if(r!=null) html += 'alpha: ' + r.alpha +'<br />beta: ' + r.beta + '<br/>gamma: ' + r.gamma + '<br />';\n dataContainerMotion.innerHTML = html; \n });\n }\n */ \n}", "function render() {\n\n // Get the difference from when the clock was last updated and update the controls based on that value.\n var delta = clock.getDelta();\n controls.update(delta);\n\n // Update the scene through the manager.\n manager.render(scene, camera);\n\n // Call the render function again\n requestAnimationFrame( render );\n\n}", "function deviceOrientationTest(event) {\n\twindow.removeEventListener('deviceorientation', deviceOrientationTest);\n\tif (event.beta != null && event.gamma != null) {\n\t\twindow.addEventListener('deviceorientation', onDeviceOrientationChange, false);\n\t\tmovementTimer = setInterval(onRenderUpdate, 10); \n\t}\n}", "function onControlChange() {\n renderer.render(scene, camera);\n}", "function deviceOrientationTest(event) {\n\twindow.removeEventListener('deviceorientation', deviceOrientationTest);\n\tif (event.beta !== null && event.gamma !== null) {\n\t\twindow.addEventListener('deviceorientation', onDeviceOrientationChange, false);\n\t\tmovementTimer = setInterval(onRenderUpdate, 10); \n\t}\n}", "function init() {\n var surface = document.getElementById('surface');\n\tlastOrientation = {};\n\twindow.addEventListener('resize', doLayout, false);\n\tsurface.addEventListener('mousemove', onMouseMove, false);\n\tsurface.addEventListener('mousedown', onMouseDown, false);\n\tsurface.addEventListener('mouseup', onMouseUp, false);\n\tsurface.addEventListener('touchmove', onTouchMove, false);\n\tsurface.addEventListener('touchstart', onTouchDown, false);\n\tsurface.addEventListener('touchend', onTouchUp, false);\n\twindow.addEventListener('deviceorientation', deviceOrientationTest, false);\n\tlastMouse = {x:0, y:0};\n\tlastTouch = {x:0, y:0};\n\tmouseDownInsideball = false;\n\ttouchDownInsideball = false;\n\tdoLayout(document);\n}", "function handleDeviceorientationEvent(e) {\n var alpha = normaliseAlpha(e);\n var beta = normaliseBeta(e);\n var gamma = normaliseGamma(e);\n\n emit(alpha, beta, gamma);\n render(alpha, beta, gamma);\n debug(alpha, beta, gamma, e);\n }", "function init() {\n\n renderer = new THREE.WebGLRenderer({\n antialias: false\n });\n renderer.setPixelRatio(Math.floor(window.devicePixelRatio));\n\n // Append the canvas element created by the renderer to document body element.\n document.body.appendChild(renderer.domElement);\n\n // Create a three.js scene.\n scene = new THREE.Scene();\n\n // Create a three.js camera.\n camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);\n\n // Apply VR headset positional data to camera.\n controls = new THREE.VRControls(camera);\n\n dollyCam = new THREE.PerspectiveCamera();\n dollyCam.add(camera);\n dollyCam.position.x = 5;\n scene.add(dollyCam);\n // enable gamepad controlls\n\n // Apply VR stereo rendering to renderer.\n effect = new THREE.VREffect(renderer);\n effect.setSize(window.innerWidth, window.innerHeight);\n // load the whole scene\n createRoom(scene);\n stats.showPanel(0); // 0: fps, 1: ms, 2: mb, 3+: custom\n document.body.appendChild(stats.domElement);\n\n //load the data from file\n var loading = $.getJSON(\"data.json\");\n //wait for the loading to be done to continue using the file\n loading.done(function(loaded) {\n // load and diplay the data we got from the sensor\n var dataVis = loadData(loaded);\n scene.add(dataVis[0]);\n scene.add(dataVis[1]);\n // add controls to the scene\n moveCon = new moveCon(dollyCam, camera, dataVis[0], dataVis[1]);\n\n\n // Request animation frame loop function\n lastRender = 0;\n\n //the the vrDisplay and kick of render loop\n navigator.getVRDisplays().then(function(displays) {\n if (displays.length > 0) {\n vrDisplay = displays[0];\n // Kick off the render loop.\n vrDisplay.requestAnimationFrame(animate);\n }\n });\n\n });\n}", "setupView() {\n const self = this;\n const renderer = this.renderer;\n const view = this.renderer.view;\n const container = this.container;\n const deviceScale = this.deviceScale;\n\n view.style.position = 'absolute';\n\n document.body.appendChild(this.renderer.view);\n\n this.windowWidth = window.innerWidth;\n this.windowHeight = window.innerHeight;\n\n container.position.x = renderer.width / 2;\n container.position.y = renderer.height / 2;\n\n container.scale.x = deviceScale;\n container.scale.y = deviceScale;\n\n this.viewCssWidth = 0;\n this.viewCssHeight = 0;\n this.resize(this.windowWidth, this.windowHeight);\n\n\n function resizeRenderer() {\n self.resize(window.innerWidth, window.innerHeight);\n }\n\n window.addEventListener('resize', resizeRenderer);\n window.addEventListener('orientationchange', resizeRenderer);\n }", "function render() {\n\tvar delta = clock.getDelta();\n\tcameraControls.update(delta);\n\tTWEEN.update();\n\trenderer.render(scene, camera);\n\tif(hasFinishedInit == true)\n\t{\n\t\tmirror.visible = false;\n\t\tmirrorCamera.updateCubeMap( renderer, scene );\n\t\tif(topDownPOV == false)\n\t\t{\n\t\t\tmirror.visible = true;\n\t\t}\n\t}\n}", "function initializeCheckOrientation(){\n window.addEventListener(\"orientationchange\", function() {\n setTimeout(function(){\n check_orientation();\n }, 150);\n });\n check_orientation();\n }", "function updateOrientation(){\n // var res = getPossibleOrientations();\n var res = getPossibleOrientationsWithTimes();\n var orientations = res.orientations;\n var times = res.times;\n\n // if there are any possible orientations, we're just going\n // to take the first one and trigger a cut\n if (orientations !== null && times && times.length > 0\n && (orientations[0] !== sts.current_orientation\n || times[0].toString() !== sts.current_orientation_time )) {\n //console.log(orientations[0] + \" orientations[0]\");\n var first_orientation = orientations[0];\n if (sts.cuts.regular_cuts && !sts.cuts.all_regular_cuts_stopped) {\n // orient important to consistant direction\n if (sts.current_orientation === undefined || sts.current_orientation === null) {\n sts.current_orientation = 0;\n //document.getElementById('print-current-orientation').innerHTML = sts.current_orientation;\n }\n var regular_cut_orientation = first_orientation + (sts.theta.current - sts.current_orientation);\n if (sts.specs.isMobile) {\n regular_cut_orientation = first_orientation - (sts.theta.current - sts.current_orientation);\n }\n //console.log(sts.current_orientation + \"sts current orientation\");\n vrView.setOrientation(regular_cut_orientation);\n recordInteraction(\"regularCut\", regular_cut_orientation);\n\n } else if (sts.cuts.regular_cuts && sts.cuts.all_regular_cuts_stopped) {\n recordInteraction(\"noCutPerformed\");\n } else {\n // normal, orient important to viewer\n vrView.setOrientation(first_orientation);\n console.log(\"setOrientation: \" + first_orientation);\n recordInteraction(\"forcedCut\", first_orientation);\n }\n sts.current_orientation = first_orientation;\n sts.current_orientation_time = times[0].toString();\n //document.getElementById('print-current-orientation').innerHTML = sts.current_orientation;\n //console.log(first_orientation);\n }\n}", "onDeviceReorientation() {\n this.data.orientation = (window.orientation * this.RAD) || 0;\n }", "onDeviceReorientation() {\n this.data.orientation = (window.orientation * this.RAD) || 0;\n }", "function render() {\n \trequestAnimationFrame( render );\n control.update(0.5);\n \trenderer.render( scene, camera );\n }", "function render() {\n \trequestAnimationFrame( render );\n control.update(0.5);\n \trenderer.render( scene, camera );\n }", "render({ time }) {\n controls.update();\n scene.rotation.x = time / 30;\n // scene.rotation.z = time / 50;\n renderer.render(scene, camera);\n }", "onWindowResize() {\n //Das Div in dem der VisualizationsCanvas liegt wird var wrapper zugewiesen\n let wrapper = $('#visualizationsCanvasDiv');\n //die Hoehe des divs wird entsprechend dem verhältnis der vorhandenenn hoehe und dem canvas div zu vorhandenen Hoehe angepasst\n wrapper.height((window.innerHeight * (wrapper.width() / window.innerWidth)));\n //Aspect = Hoehen zu Breiten Verhaeltnis\n var aspect = $(\"#visualizationsCanvasDiv\").width() / $(\"#visualizationsCanvasDiv\").height();\n //Wenn Kamera links starten soll(linke Ecke des Canvas = 0) sonst startet Kamera in der Mitte\n if (this.startLeft) {\n this.camera.left = 0;\n this.camera.right = this.frustumSize * aspect;\n } else {\n this.camera.left = this.frustumSize * aspect / -2;\n this.camera.right = this.frustumSize * aspect / 2;\n }\n //Oberes und unteres Ende der Kamera wird gesetzt \n this.camera.top = this.frustumSize / 2;\n this.camera.bottom = this.frustumSize / -2;\n //Kamera wird aktualisiert\n this.camera.updateProjectionMatrix();\n this.camera.updateMatrixWorld();\n //Renderer Groesse wird neu gesetzt\n this.renderer.setSize(wrapper.width(), wrapper.height());\n if (window.actionDrivenRender)\n this.render();\n }", "function displayInformation_orientationChanged(args) {\r\n oDisplayOrientation = args.target.currentOrientation;\r\n setPreviewRotation();\r\n }", "function renderView() {\n\t\t// request new frame\n requestAnimationFrame(function(){\n renderView();\n });\n\t\trenderer.render(scene, camera);\n\t\t\n\t\tif(rotation_enabled){\n\t\t\trender_model.rotation.x += 0.0015;\n\t\t\trender_model.rotation.y += 0.0015;\n\t\t}\n\t\t//bump_map.needsUpdate = true;\n\t\t//ao_map.needsUpdate = true;\n\t\t\n\t}", "function initControls() {\n\tcontrols = new THREE.TrackballControls(camera, renderer.domElement);\n\tcontrols.rotateSpeed = 0.5;\n\tcontrols.minDistance = 500;\n\tcontrols.maxDistance = 6000;\n\tcontrols.noRotate = false;\n\tcontrols.staticMoving = true;\n\tcontrols.dynamicDampingFactor = 0.1;\n\tcontrols.target.set(550, -600, 0);\n\n\tcontrols.addEventListener('change', render);\n\twindow.addEventListener('resize', onWindowResize, false);\n}", "function update() {\n let data = deviceOrientation.getScreenAdjustedEuler();\n alpha = data.alpha;\n\n // Convert alpha values from (0 to 360) to (-180 to 180).\n let x = ((alpha - alphaOffset + 180) % 360) - 180;\n\n // Stop at max angles.\n x = Math.max(-maxAngles.x, Math.min(x, maxAngles.x));\n let y = Math.max(-maxAngles.y, Math.min(data.beta, maxAngles.y));\n\n // Convert from (-180 to 180) to (-1 to 1) and reverse direction.\n x = x / maxAngles.x * -1;\n y = y / maxAngles.y * -1;\n\n socket.emit('position', {x: x, y: y});\n\n requestAnimationFrame(update);\n}", "animate(){\n // Use a binder to bind this function to this object.\n this.animationID = requestAnimationFrame( this.animate.bind(this) );\n\n this.controls.update();\n\n this.scene.rotation.x += 0.0008;\n this.scene.rotation.y += 0.0015;\n \n this.render();\n}", "onRender() {\n if ( !this.mRunning )\n return;\n\n if ( SPE_USES_PREVIEW_IMAGE ) {\n document.querySelector( '.spline-preview-image-container' ).style.display = 'none';\n\n SPE_USES_PREVIEW_IMAGE = false;\n }\n\n if ( this.mPlayHandler && !this.mPlayHandler.isEnable ) {\n this.mPlayHandler.activate();\n }\n\n if ( this.mOrbitControls ) {\n this.mOrbitControls.update();\n }\n if ( this.mScene && this.mMainCamera ) {\n this.mRenderer.autoClear = true;\n this.mRenderer.render( this.mScene, this.mMainCamera );\n }\n }", "display(context, program_state) {\n const desired_camera = this.cameras[this.selection];\n if (!desired_camera || !this.enabled)\n return;\n const dt = program_state.animation_delta_time;\n program_state.set_camera(desired_camera.map((x, i) => Vec.from(program_state.camera_inverse[i]).mix(x, .01 * dt)));\n }", "function orient() {\n // reset orientation to initial\n reference_orientation_component.autoView(1000);\n}", "function updateRender() { controls.update(); TWEEN.update(); renderer.render(scene, camera); requestAnimFrame(updateRender); }", "function init() {\r\n console.log(\"hello\");\r\n try {\r\n canvas = document.getElementById(\"glcanvas\");\r\n renderer = new THREE.WebGLRenderer({\r\n canvas: canvas,\r\n antialias: true\r\n });\r\n } catch (e) {\r\n document.getElementById(\"canvas-holder\").innerHTML =\r\n \"<h3><b>Sorry, WebGL is required but is not available.</b><h3>\";\r\n return;\r\n }\r\n document.addEventListener(\"keydown\", doKey, false);\r\n document.getElementById(\"anim1\").addEventListener(\"click\", doPlayControl);\r\n document.getElementById(\"anim2\").addEventListener(\"click\", doStopControl);\r\n\r\n document.getElementById(\"light1\").checked = true;\r\n document.getElementById(\"light1\").onchange = doChangeAboveLight;\r\n document.getElementById(\"light2\").checked = true;\r\n document.getElementById(\"light2\").onchange = doChangeViewLight;\r\n document.getElementById(\"light3\").checked = false;\r\n document.getElementById(\"light3\").onchange = doChangeAmbientLight;\r\n document.getElementById(\"light4\").checked = false;\r\n document.getElementById(\"light4\").onchange = doChangeRedLight;\r\n\r\n document.getElementById(\"range1\").oninput = doSlideChange;\r\n\r\n createScene();\r\n controls = new THREE.TrackballControls(camera, canvas);\r\n controls.noPan = true;\r\n render();\r\n doFrame();\r\n\r\n doChangeAmbientLight();\r\n doChangeRedLight();\r\n}", "animate() {\n this.graphics.rotation = this.rotateClockwise\n ? this.graphics.rotation + this.rotateSpeed\n : this.graphics.rotation - this.rotateSpeed\n }", "animate(dSec,vrHelper){\n\n if( this.control ) {\n this.control.animate(dSec,vrHelper);\n }\n\n var limit = 5000.0;\n var min = new BABYLON.Vector3(-limit,-limit,-limit);\n var max = new BABYLON.Vector3(+limit,+limit,+limit);\n this.speedPosition = BABYLON.Vector3.Clamp(this.speedPosition,min,max);\n\n this.root.locallyTranslate(this.speedPosition.scale(dSec)); // relatige to ship OR: this.root.translate(this.speedPosition, 1 , Space.LOCAL); // relatige to ship\n\n this.root.rotate(BABYLON.Axis.Y, this.speedRotation.y*dSec, BABYLON.Space.LOCAL); // not .WORLD\n\n // Does the VR-Helper do the mouse rotation?\n // Is there a way to disable it?\n // We have to UNDO it: Does not work that nice!\n var euler = this.root.rotationQuaternion.toEulerAngles();\n this.root.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(euler.y, 0, 0);\n\n // NO!: https://doc.babylonjs.com/resources/rotation_conventions#euler-angles-to-quaternions\n // thisroot.rotationQuaternion.addInPlace(BABYLON.Quaternion.RotationYawPitchRoll(speedRotation.y, speedRotation.x, speedRotation.z) );\n\n var cameraOffset = vrHelper.isInVRMode ? this.cameraOffset1 : this.cameraOffset3;\n\n var camPos = new BABYLON.AbstractMesh(\"camPos\");\n camPos.rotationQuaternion = this.root.rotationQuaternion;\n camPos.position = this.root.position.clone();\n camPos.locallyTranslate(cameraOffset);\n setCamera( camPos.position,\n camPos.rotationQuaternion,\n vrHelper );\n\n }", "init() {\n // Scene basic setup\n this.renderer.setSize(window.innerWidth, window.innerHeight);\n this.renderer.setPixelRatio(window.devicePixelRatio || 1);\n this.renderer.shadowMap.enabled = true;\n \n this.controls.target.set(0, 0, 0);\n this.controls.update();\n\n document.body.appendChild(this.renderer.domElement);\n\n\n // Window resize event handler\n window.addEventListener('resize', () => {\n this.camera.aspect = window.innerWidth / window.innerHeight;\n this.camera.updateProjectionMatrix();\n \n this.renderer.setSize(window.innerWidth, window.innerHeight);\n this.renderer.setPixelRatio(window.devicePixelRatio || 1);\n\n this.stateList[this.state].onResize(this.renderer.domElement.width, this.renderer.domElement.height);\n });\n }", "function handleOrientation(event){\n\t\talpha=Math.floor(event.alpha);\n\t\tbeta=Math.floor(event.beta);\n\t\tgamma=Math.floor(event.gamma);\n\t\t\n\t\tif(windowWidth<645){\n\t\t\t// gets motion info from phones\n\t\t\t// checks if mobile device is being tipped slowly\n\t\t\tif(beta<0 && xmotion<1 && ymotion<5 && xmotion<5){\n\t\t\t\t// determine how much to increase water level on desktop\n\t\t\t\tvar level=Math.abs(map(beta, -180, 180, 0, 20));\n\t\t\t\t// decrease water level on phone display\n\t\t\t\twaterLevel=waterLevel-level;\n\t\t\t\tif(waterLevel<0){\n\t\t\t\t\twaterLevel=0;\n\t\t\t\t\tlevel=0;\n\t\t\t\t}\n\t\t\t\t// console.log('the team is ' + team);\n\t\t\t\t// document.getElementById('gamma').innerHTML=\"inside pour \"+level;\n\n\t\t\t\t// send how much to increase water by and which team\n\t\t\t\tsocket.emit('orientation', {\n\t\t\t\t\t'waterLevel': level,\n\t\t\t\t\t'team':team\n\t\t\t\t\t// 'alpha': alpha,\n\t\t\t\t\t// 'beta': beta,\n\t\t\t\t\t// 'gamma':gamma\n\t\t\t\t});\n\n\t\t\t}\n\t\t}\n\t\t// send values to the DOM so that we can see them\n\t\t// document.getElementById('alpha').innerHTML=alpha;\n\t\t// document.getElementById('beta').innerHTML=beta;\n\t\t// document.getElementById('gamma').innerHTML=gamma;\n\t\t// document.getElementById('wlevel').innerHTML=waterLevel;\n\t\t// socket.emit('orientation', {\n\t\t// \t\t\t'waterLevel': waterLevel,\n\t\t// \t\t\t'team':team\n\t\t// \t\t\t// 'alpha': alpha,\n\t\t// \t\t\t// 'beta': beta,\n\t\t// \t\t\t// 'gamma':gamma\n\t\t// \t\t});\n\n\t}", "function render() {\n requestAnimationFrame( render );\n control.update();\n renderer.render( scene, camera );\n}", "function init()\n{\n lastOrientation = {};\n window.addEventListener('resize', doLayout, false);\n document.body.addEventListener('mousemove', onMouseMove, false);\n document.body.addEventListener('mousedown', onMouseDown, false);\n document.body.addEventListener('mouseup', onMouseUp, false);\n document.body.addEventListener('touchmove', onTouchMove, false);\n document.body.addEventListener('touchstart', onTouchDown, false);\n document.body.addEventListener('touchend', onTouchUp, false);\n window.addEventListener('deviceorientation', deviceOrientationTest, false);\n lastMouse = {x:0, y:0};\n lastTouch = {x:0, y:0};\n mouseDownInsideball = false;\n touchDownInsideball = false; \n doLayout(document); \n}", "function calibrateDevice(deviceName) {\n var deviceName = document.querySelector(deviceName)\n\n // When the respective devices have been loaded in the dom, firstly, the scrollbars are hidden and then the zoom factor is decreased from the default of 1 to 0.6 to match the zoom out of the app\n deviceName.addEventListener('dom-ready', () => {\n // This is to hide scrollbars in the devices\n deviceName.insertCSS(`\n ::-webkit-scrollbar {\n display: none;\n }\n `)\n // Make the devices zoom factor 60% of their original to match the zoom out done in main.js to the app window\n deviceName.setZoomFactor(0.6)\n\n // For the back button\n document.getElementById(\"backButton\").addEventListener(\"click\", () => {\n // If can go back, then go back\n if (deviceName.canGoBack) {\n deviceName.goBack()\n } else {\n // For some reason, anything put in here has no effect\n }\n })\n\n // For the forward button\n document.getElementById(\"forwardButton\").addEventListener(\"click\", () => {\n // If can go forward, then go forward\n if (deviceName.canGoForward) {\n deviceName.goForward()\n } else {\n // For some reason, anything put in here has no effect\n }\n })\n\n // To reload the webviews\n document.getElementById(\"reloadButton\").addEventListener(\"click\", () => {\n // Reload\n deviceName.reload()\n })\n\n // For the back button\n document.getElementById(\"homeButton\").addEventListener(\"click\", () => {\n // Go to index.html\n location.href = '../index.html'\n })\n })\n}", "display( context, program_state )\n {\n const desired_camera = this.cameras[ this.selection ];\n if( !desired_camera || this.enabled )\n return;\n const dt = program_state.animation_delta_time;\n program_state.set_camera( desired_camera.map( (x,i) => Vec.from( program_state.camera_inverse[i] ).mix( x, .01*dt ) ) ); \n }", "function ChangeOrientation(){\n html=document.getElementsByTagName(\"html\")[0];\n global_width=html.offsetWidth;\n global_height=html.offsetHeight;\n \n if(prev_width!=global_width || prev_height!=global_height){\n console.log(\"change\")\n prev_height=global_height\n prev_width=global_width\n prev_toggle_nav_state=toggle_nav\n \n align_burguer();\n }\n requestAnimationFrame(ChangeOrientation)\n}", "function setOrientation(orientation){\n if(orientation)\n camera.rotation.z=Math.PI/2; ///=+\n else\n camera.rotation.z=0;\n}", "function render() {\n\t\tcontrols.update(clock.getDelta());\n\t\trenderer.render( scene, camera );\n\t}", "function cameraControls(canvas) {\n var mouseIsDown = false;\n var lastPosition = {\n x: 0,\n y: 0\n };\n canvas.addEventListener(\"mousedown\", function (e) {\n mouseIsDown = true;\n lastPosition = {\n x: e.clientX,\n y: e.clientY\n };\n }, false);\n canvas.addEventListener(\"mousemove\", function (e) {\n if (mouseIsDown) {\n params.view.lambda += (e.clientX - lastPosition.x) / params.rotationSensitivity;\n params.view.lambda %= Math.PI * 2;\n params.view.phi += (e.clientY - lastPosition.y) / params.rotationSensitivity;\n params.view.phi %= Math.PI * 2;\n }\n lastPosition = {\n x: e.clientX,\n y: e.clientY\n };\n\n }, false);\n canvas.addEventListener(\"mouseup\", function () {\n mouseIsDown = false;\n }, false);\n}", "initControls() {\n this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);\n\n this.controls.target = new THREE.Vector3(0, 0, 0);\n\n this.controls.enableDamping = false; // an animation loop is required when either damping or auto-rotation are enabled\n this.controls.dampingFactor = 0.25;\n\n this.controls.screenSpacePanning = false;\n this.controls.minDistance = 100;\n this.controls.maxDistance = 500;\n\n this.controls.maxPolarAngle = Math.PI / 2;\n }", "function setup_controls() {\n var canvas = document.getElementById(\"wwtcanvas\");\n\n function new_event(action, attributes, deprecated) {\n if (!deprecated) {\n var event = new CustomEvent(action);\n } else {\n var event = document.createEvent(\"CustomEvent\");\n event.initEvent(action, false, false);\n }\n\n if (attributes) {\n for (var attr in attributes)\n event[attr] = attributes[attr];\n }\n\n return event;\n }\n\n const wheel_up = new_event(\"wwt-zoom\", { deltaY: 53, delta: 53 }, true);\n const wheel_down = new_event(\"wwt-zoom\", { deltaY: -53, delta: -53 }, true);\n const mouse_left = new_event(\"wwt-move\", { movementX: 53, movementY: 0 }, true);\n const mouse_up = new_event(\"wwt-move\", { movementX: 0, movementY: 53 }, true);\n const mouse_right = new_event(\"wwt-move\", { movementX: -53, movementY: 0 }, true);\n const mouse_down = new_event(\"wwt-move\", { movementX: 0, movementY: -53 }, true);\n const rotate_left = new_event(\"wwt-rotate\", { movementX: 53, movementY: 0 }, true);\n const rotate_right = new_event(\"wwt-rotate\", { movementX: -53, movementY: 0 }, true);\n\n\n const zoomCodes = {\n \"KeyI\": wheel_up,\n \"KeyO\": wheel_down,\n 73: wheel_up,\n 79: wheel_down\n };\n\n const moveCodes = {\n \"KeyA\": mouse_left,\n \"KeyW\": mouse_up,\n \"KeyD\": mouse_right,\n \"KeyS\": mouse_down,\n \"KeyJ\": rotate_left,\n \"KeyL\": rotate_right,\n 65: mouse_left,\n 87: mouse_up,\n 68: mouse_right,\n 83: mouse_down,\n 74: rotate_left,\n 76: rotate_right,\n };\n\n window.addEventListener(\"keydown\", function (event) {\n // \"must check the deprecated keyCode property for Qt\"\n\n // Check whether keyboard events initiate zoom methods\n if (zoomCodes.hasOwnProperty(event.code) || zoomCodes.hasOwnProperty(event.keyCode)) {\n // remove the zoom_pan instructions\n $(\"#zoom_pan_instrux\").delay(5000).fadeOut(1000);\n $(\"#page_title\").delay(5000).fadeOut(1000);\n\n // show reset button if enabled\n if (reset_enabled) {\n $(\"#reset_target\").show();\n }\n\n var action = zoomCodes.hasOwnProperty(event.code) ? zoomCodes[event.code] : zoomCodes[event.keyCode];\n\n // Possible to cut this? I don't see action.shiftKey being used anywhere.\n if (event.shiftKey)\n action.shiftKey = 1;\n else\n action.shiftKey = 0;\n\n canvas.dispatchEvent(action);\n }\n\n // Check whether keyboard events initiate move methods\n if (moveCodes.hasOwnProperty(event.code) || moveCodes.hasOwnProperty(event.keyCode)) {\n // remove the zoom_pan instructions\n $(\"#zoom_pan_instrux\").delay(5000).fadeOut(1000);\n $(\"#page_title\").delay(5000).fadeOut(1000);\n\n // show reset button if enabled\n if (reset_enabled) {\n $(\"#reset_target\").show();\n }\n\n var action = moveCodes.hasOwnProperty(event.code) ? moveCodes[event.code] : moveCodes[event.keyCode];\n\n\n // Possible to cut this? I don't see action.shiftKey/altKey being used anywhere.\n if (event.shiftKey)\n action.shiftKey = 1\n else\n action.shiftKey = 0;\n\n if (event.altKey)\n action.altKey = 1;\n else\n action.altKey = 0;\n\n canvas.dispatchEvent(action);\n }\n });\n\n canvas.addEventListener(\"wwt-move\", (function (proceed) {\n return function (event) {\n if (!proceed)\n return false;\n\n if (event.shiftKey)\n delay = 500; // milliseconds\n else\n delay = 100;\n\n setTimeout(function () { proceed = true }, delay);\n\n wwt_ctl.move(event.movementX, event.movementY);\n }\n })(true));\n\n canvas.addEventListener(\"wwt-rotate\", (function (proceed) {\n return function (event) {\n if (!proceed)\n return false;\n\n if (event.shiftKey)\n delay = 500; // milliseconds\n else\n delay = 100;\n\n setTimeout(function () { proceed = true }, delay);\n\n wwt_ctl._tilt(event.movementX, event.movementY);\n }\n })(true));\n\n canvas.addEventListener(\"wwt-zoom\", (function (proceed) {\n return function (event) {\n if (!proceed)\n return false;\n\n if (event.shiftKey)\n delay = 500; // milliseconds\n else\n delay = 100;\n\n setTimeout(function () { proceed = true }, delay);\n\n if (event.deltaY < 0) {\n wwt_ctl.zoom(1.05);\n }\n else {\n wwt_ctl.zoom(0.95);\n }\n\n }\n })(true));\n\n }", "static render() {\n // Throttle framerate during playback\n if(renderer.playbackMode) {\n // Update time/elapsed at frame\n var newTime = performance.now();\n renderer.m_elapsed = newTime - renderer.m_then;\n\n // Check if interval passed\n if(renderer.m_elapsed > renderer.m_fpsInterval) {\n renderer.m_then = newTime - (renderer.m_elapsed % renderer.m_fpsInterval);\n renderer.scrubFrames(1); // Advance frame\n }\n }\n\n renderer.anim.renderFrame(renderer.animFrame); // Render current anim frame\n\n if(!renderer.playbackMode)\n dispatchEvent(Renderer.frameEvent); // Let editor parts know window is framing\n\n renderer.m_updateRequest = requestAnimationFrame(Renderer.render); // Request a new frame\n }", "function render()\n{\n gl.clear( gl.COLOR_BUFFER_BIT );\n\n if (direction == true)\n {\n theta += speed;\n }\n else \n {\n theta -= speed;\n }\n gl.uniform1f(thetaLoc, theta);\n\n gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n window.requestAnimFrame(render);\n}", "function handleOrientation(event) { //[1]\r\n \r\n // Getting angle (beta value) from parameter object and store into beta variable\r\n var beta = event.beta;\r\n \r\n \r\n // Step 2: Smoothing sensor data\r\n \r\n // Storing beta values into array \r\n array[i]=beta;\r\n i++;\r\n \r\n // Perform smoothing (averaging) when array is filled\r\n if (i=== array.length)\r\n {\r\n // Resetting average and sum values before calculating average\r\n\t\t\t\tavg = 0;\r\n\t\t\t\tsum = 0;\r\n \r\n //averaging values\r\n for (var j = 0;j<array.length;j++)\r\n {\r\n sum+=array[j];\r\n }\r\n avg=sum/array.length;\r\n \r\n // Reset data array and index counter for next round\r\n i=0;\r\n array.fill(0);\r\n }\r\n \r\n \r\n // Output angle (beta values) and smoothed angle (average beta) to screen\r\n //output=\"beta: \" + beta.toFixed(1) + \"<br />\" + \"i: \" + i + \"<br />\" + \"beta avg: \" + avg.toFixed(1) + \"<br />\";\r\n output=\"beta: \" + beta.toFixed(1) + \"<br />\" + \"beta average: \" + avg.toFixed(0) + \"<br />\";\r\n cameraVideoPage.setHeadsUpDisplayHTML(output);\r\n\r\n }", "initScene() {\n\n const canvas = this.canvas.current;\n const renderer = new Three.WebGLRenderer({ canvas });\n const scene = new Three.Scene();\n const camera = new Three.PerspectiveCamera(\n 75, // Field of view\n 1, // Aspect ratio\n 0.1, // Near Plane\n 50 // Far Plane\n );\n\n camera.position.set(0, 0, 2);\n camera.lookAt(0, 0, 0);\n\n scene.background = new Three.Color({ color: 'white'});\n\n const controls = new OrbitControls(camera, canvas);\n controls.target.set(0, 0, 0);\n controls.update();\n\n renderer.render(scene, camera);\n\n this.setState({\n renderer,\n scene,\n camera,\n controls\n }, function() {\n\n requestAnimationFrame(this.configDisplay);\n this.renderIcosahedron();\n\n });\n\n }", "function on_draw_gui_decoder()\n{\n //Define decoder configuration GUI\n ScanaStudio.gui_add_ch_selector(\"ch_servo\",\"Servo channel\",\"Servomotor\");\n ScanaStudio.gui_add_combo_box(\"type\",\"Servomotor type\");\n ScanaStudio.gui_add_item_to_combo_box(\"Standart (angle and speed)\", true);\n ScanaStudio.gui_add_item_to_combo_box(\"Continuous rotation (sense and speed of rotation)\",false);\n ScanaStudio.gui_add_engineering_form_input_box(\"pulse_min\",\"Pulse width min (0 °)\",100e-6,10e-3,1e-3,\"s\");\n ScanaStudio.gui_add_engineering_form_input_box(\"pulse_max\",\"Pulse width max (180 °)\",100e-6,10e-3,2e-3,\"s\");\n ScanaStudio.gui_add_text_input(\"angle_range\",\"Angle Range (°)\",\"180\");\n ScanaStudio.gui_add_engineering_form_input_box(\"frequency\",\"Frequency\",5,500,50,\"Hz\");\n ScanaStudio.gui_add_combo_box(\"display\",\"Angle Display\");\n ScanaStudio.gui_add_item_to_combo_box(\"°\",true);\n ScanaStudio.gui_add_item_to_combo_box(\"%\",false);\n ScanaStudio.gui_add_new_tab(\"Virtual Analog Channels\",true);\n ScanaStudio.gui_add_check_box(\"angle_disp_deg\", \"Display a graphic for angle in °\", false);\n ScanaStudio.gui_add_check_box(\"angle_disp_percent\", \"Display a graphic for angle in %\", false);\n ScanaStudio.gui_add_check_box(\"speed_disp\", \"Display a graphic for speed in sec/60°\", false);\n ScanaStudio.gui_add_check_box(\"speed_display_perc\", \"Display a graphic for speed in %\", false);\n\n ScanaStudio.gui_end_tab();\n}", "updateDebugGraphics() {\n this.debugGraphics.rotation = -this.ent.rotation;\n }", "render ({ time, deltaTime }) {\n mesh.rotation.y += deltaTime * (5 * Math.PI / 180);\n controls.update();\n renderer.render(scene, camera);\n }", "animate() {\n this.renderScene()\n this.frameId = window.requestAnimationFrame(this.animate)\n this.camera.rotation.z -= .0004;\n this.clouds1.rotation.y += .001;\n this.clouds2.rotation.y += .001;\n\n this.yinYang.rotation.y += 0.00;\n this.earth.rotation.y += 0.001;\n this.fire.rotation.y += 0.001;\n this.metal.rotation.y += 0.001;\n this.water.rotation.y += 0.001;\n this.wood.rotation.y += 0.001;\n }", "function updateForFrame() {\r\n rotatingComponents.rotation.y += rotateSpeed;\r\n}", "function initializeComplete() {\n initialized = true;\n logMessage('Device Initialized');\n\n document.getElementById(\"btnStartDevice\").textContent = \"Stop Device\";\n setVideoCaptureDeviceList();\n setAudioCaptureDeviceList();\n\n // Enclosure Info\n var enclosureLocation = webcamList[0].enclosureLocation;\n if (enclosureLocation) {\n if (enclosureLocation.panel === Windows.Devices.Enumeration.Panel.back) {\n logMessage(\"Rear Facing (away from user) Camera Initialized\");\n rotateVideoOnOrientationChange = true;\n reverseVideoRotation = false;\n } else if (enclosureLocation.panel === Windows.Devices.Enumeration.Panel.front) {\n logMessage(\"Front Facing (towards user) Camera Initialized\");\n rotateVideoOnOrientationChange = true;\n reverseVideoRotation = true;\n } else {\n rotateVideoOnOrientationChange = false;\n }\n }\n else {\n logMessage(\"No PLD location info present for this webcam\");\n rotateVideoOnOrientationChange = false;\n }\n\n // Photo Capture Source\n var photoSource = mediaCaptureMgr.mediaCaptureSettings.photoCaptureSource;\n if (photoSource === Capture.PhotoCaptureSource.videoPreview) {\n logMessage(\"Photo Capture Source is the VideoPreview Stream\");\n } else if (photoSource === Capture.PhotoCaptureSource.photo) {\n logMessage(\"Photo Capture Source is the Photo Stream\");\n } else if (photoSource === Capture.PhotoCaptureSource.auto) {\n logMessage(\"Photo Capture Source is Auto (Error)\");\n } else {\n logMessage(\"***Something very wrong happened. Check the Photo Capture Source***\");\n }\n // Start Preview\n startPreview();\n vpsController = mediaCaptureMgr.videoDeviceController.variablePhotoSequenceController;\n var selFrames = document.getElementById(\"lstFrames\");\n var j = 0;\n for(j = 0;j<selFrames.options.length;j++){\n selFrames.options[j] = null;\n }\n \n if (!vpsController.supported) {\n document.getElementById(\"btnVPS\").disabled = true;\n document.getElementById(\"lstFrames\").disabled = true;\n document.getElementById(\"btnVPSAddFrame\").disabled = true;\n document.getElementById(\"btnVPSRemoveFrame\").disabled = true;\n } else {\n\n document.getElementById(\"lstFrames\").disabled = false;\n document.getElementById(\"btnVPSAddFrame\").disabled = false;\n document.getElementById(\"btnVPSRemoveFrame\").disabled = false;\n }\n document.getElementById(\"btnPreview\").disabled = false;\n rotWidth = previewTag.width;\n rotHeight = previewTag.height;\n setupVPSDeviceControls();\n}", "display(context, program_state) {\n const desired_camera = this.cameras[this.selection];\n if (!desired_camera || !this.enabled) return;\n const dt = program_state.animation_delta_time;\n program_state.set_camera(\n desired_camera.map((x, i) =>\n Vec.from(program_state.camera_inverse[i]).mix(x, 0.01 * dt)\n )\n );\n program_state.projection_transform = Mat4.perspective(\n Math.PI / 4,\n context.width / context.height,\n 1,\n 2500\n );\n }", "function animate() {\n requestAnimationFrame(animate);\n TORUS.rotation.x += 0.01;\n TORUS.rotation.y += 0.005;\n TORUS.rotation.z += 0.01;\n\n CONTROLS.update(); // reflects changes (onMouseUp) in the UI as new start point for the next change (onMouseDown) \n\n RENDERER.render(SCENE,CAMERA);\n }", "function calculateDeviceOrientation(e) {\n isLandscape =\n document.documentElement.clientHeight < document.documentElement.clientWidth;\n isRotatedClockwise = window.orientation === -90;\n }", "function onInit(){\n _canvasWidth = window.innerWidth < 1920 ? Math.floor(window.innerWidth): 1920;\n _canvasHeight = window.innerWidth < 1920 ? Math.floor(window.innerWidth / 2.14) : 900;\n\n _startX = _canvasWidth * onGetRatio(80, 1920, null);\n _startY = _canvasWidth * onGetRatio(120, 1920, null);\n _sec1TitleY = _canvasHeight * onGetRatio(120, null, 900);\n _sec1BodyY = _canvasHeight * onGetRatio(370, null, 900);\n _sec1CaptionY = _canvasHeight * onGetRatio(819, null, 900);\n _sec1Avocado1X = _canvasWidth * onGetRatio(788, 1920, null);\n _sec1Avocado1LineX = _canvasWidth * onGetRatio(712, 1920, null);\n _sec1Avocado1Y = _canvasHeight * onGetRatio(198, null, 900);\n _sec1Avocado2X = _canvasWidth * onGetRatio(1280, 1920, null);\n _sec1Avocado2LineX = _canvasWidth * onGetRatio(1722, 1920, null);\n \n onSec1init();\n}", "function drawScene() {\n // calculate deltatime\n calculateDeltaTime();\n\n // run some updates\n camera.update();\n scene.update();\n\n // Clear the canvas before we start drawing on it.\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // render 3d cubes\n render3DCube(mesh_1, camera, shader);\n render3DCube(mesh_2, camera, shader);\n\n // rotate mesh 1\n //mesh_1.rotation[0] += 0.01;\n //mesh_1.rotation[1] += 0.01;\n\n // rotate mesh 2\n //mesh_2.rotation[1] += 0.01;\n //console.log(1000 * deltatime);\n // move camera\n\n /*\n if(input.getKey(input.keycode.A)){\n camera.position[2] -= 0.1;\n }\n if(input.getKey(input.keycode.D)){\n camera.position[2] += 0.1;\n }\n\n // forward backwards\n if(input.getKey(input.keycode.W)){\n camera.position[0] += 0.1;\n }\n if(input.getKey(input.keycode.S)){\n camera.position[0] -= 0.1;\n }\n\n // up down\n if(input.getKey(input.keycode.SHIFT)){\n camera.position[1] -= 0.1;\n }\n if(input.getKey(input.keycode.SPACE)){\n camera.position[1] += 0.1;\n }\n */\n\n // get some mouse info\n //if(input.getMouseDown()){\n // console.log(\"mouseX: \" + input.getMouseX() + \" mouseY: \" + input.getMouseY() + \"!\");\n //}\n\n // set camera rotation\n if(input.isPhoneMovement()){\n camera.setYaw(-input.getPhoneX());\n camera.setPitch(input.getPhoneY())\n }else{\n camera.setYaw(input.getMouseX());\n camera.setPitch(-input.getMouseY())\n }\n}", "constructor( context, control_box, canvas = context.canvas )\r\n { super( context, control_box );\r\n [ this.context, this.roll, this.look_around_locked, this.invert ] = [ context, 0, true, true ]; // Data members\r\n [ this.thrust, this.pos, this.z_axis ] = [ Vec.of( 0,0,0 ), Vec.of( 0,0,0 ), Vec.of( 0,0,0 ) ];\r\n // The camera matrix is not actually stored here inside Movement_Controls; instead, track\r\n // an external matrix to modify. This target is a reference (made with closures) kept\r\n // in \"globals\" so it can be seen and set by other classes. Initially, the default target\r\n // is the camera matrix that Shaders use, stored in the global graphics_state object.\r\n this.target = function() { return context.globals.movement_controls_target() }\r\n context.globals.movement_controls_target = function(t) { return context.globals.graphics_state.camera_transform };\r\n context.globals.movement_controls_invert = this.will_invert = () => true;\r\n context.globals.has_controls = true;\r\n\r\n [ this.radians_per_frame, this.meters_per_frame, this.speed_multiplier ] = [ 1/200, 20, 1 ];\r\n \r\n // *** Mouse controls: ***\r\n this.mouse = { \"from_center\": Vec.of( 0,0 ) }; // Measure mouse steering, for rotating the flyaround camera:\r\n const mouse_position = ( e, rect = canvas.getBoundingClientRect() ) => \r\n Vec.of( e.clientX - (rect.left + rect.right)/2, e.clientY - (rect.bottom + rect.top)/2 );\r\n // Set up mouse response. The last one stops us from reacting if the mouse leaves the canvas.\r\n document.addEventListener( \"mouseup\", e => { this.mouse.anchor = undefined; } );\r\n canvas .addEventListener( \"mousedown\", e => { e.preventDefault(); this.mouse.anchor = mouse_position(e); } );\r\n canvas .addEventListener( \"mousemove\", e => { e.preventDefault(); this.mouse.from_center = mouse_position(e); } );\r\n canvas .addEventListener( \"mouseout\", e => { if( !this.mouse.anchor ) this.mouse.from_center.scale(0) } ); \r\n }", "function render() {\n\n // var chassis = scene.getObjectByName('chassis');\n\n if ( initAnim ) { idx = 0; }\n\n computePosRot( result, offset_x );\n\n if ( scene !== undefined ) {\n\n // update wheel-knuckle 1 position and orientation\n // wheel1.setRotationFromMatrix( aw1 );\n wheel1.rotation.y += -0.5;\n wheel1.position.set( w1p.x, 0.0, wheel_radius );\n\n // update position of global reference axis system\n globalAxis.position.x = w1p.x;\n\n // update camera position\n camera.position.x = w1p.x - 1;\n camera.lookAt(wheel1.position);\n\n // update time simulation on canvas\n valueNode.nodeValue = 't[s] = ' + time_sim.toFixed(1);\n\n // render scene\n renderer.render( scene, camera );\n }\n}", "render(){\n // this.options.zoomValue = this.controls.target.distanceTo( this.controls.object.position )\n \n TWEEN.update(); \n \n this.controls.update();\n\n this.calculateIntersections();\n\n this.renderer.render(this.scene, this.camera);\n\n requestAnimationFrame(this.render.bind(this));\n }", "async function changeFired() {\n await document.documentElement.requestFullscreen();\n let orientations = [\n \"portrait-primary\",\n \"portrait-secondary\",\n \"landscape-primary\",\n \"landscape-secondary\"\n ];\n console.log(`changes made again`);\n if (screen.orientation.type.includes(\"portrait\")) {\n orientations = orientations.reverse();\n }\n\n function log(orientation) {\n console.log(\n `${screen.orientation.type} + ${orientation}: should be the same`\n );\n }\n for (const orientation of orientations) {\n screen.orientation.addEventListener(\"change\", log(orientation));\n await screen.orientation.lock(orientation);\n screen.orientation.removeEventListener(\"change\", log(orientation));\n }\n screen.orientation.unlock();\n return document.exitFullscreen();\n}", "preRender()\n {\n super.preRender();\n \n let matrix = device.orthographicMatrix;\n \n spriteStrategyManager.render( matrix );\n }", "function tick() {\n if (!FlagIsRenderable) {\n requestAnimationFrame(tick);\n return;\n }\n let deltaTime = Date.now() - prevTime;\n let rotDelta = mat4.create();\n let lightDir = controls.lightDirection;\n let lightDirection = vec3.fromValues(lightDir[0], lightDir[1], lightDir[2]);\n camera.update();\n let position = camera.getPosition();\n stats.begin();\n processAudio();\n /*---------- Render Shadow Map into Buffer ----------*/\n // gl.bindFramebuffer(gl.FRAMEBUFFER, shadowMapBuffer.frameBuffer);\n // gl.viewport(0, 0, window.innerWidth, window.innerHeight);\n // renderer.clear();\n // shadowMapShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n // setShadowMapData(shadowMapShader);\n // renderScene(shadowMapShader, shadowMapShader);\n /*---------- Render Scene ----------*/\n gl.bindFramebuffer(gl.FRAMEBUFFER, null);\n gl.viewport(0, 0, window.innerWidth, window.innerHeight);\n renderer.clear();\n // gl.disable(gl.DEPTH_TEST);\n // skyShader.setTime(frameCount);\n // skyShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n // renderer.render(camera, skyShader, [sky]);\n // gl.enable(gl.DEPTH_TEST);\n mainShader.setTime(frameCount);\n mainShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n particleShader.setTime(frameCount);\n particleShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n visualShader.setTime(frameCount);\n visualShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n regularShader.setEyePosition(vec4.fromValues(position[0], position[1], position[2], 1));\n mainShader.setLightPosition(vec3.fromValues(lightDirection[0], lightDirection[1], lightDirection[2]));\n regularShader.setLightPosition(vec3.fromValues(lightDirection[0], lightDirection[1], lightDirection[2]));\n particleShader.setLightPosition(vec3.fromValues(lightDirection[0], lightDirection[1], lightDirection[2]));\n mainShader.setPointLights(sceneLights);\n // mainShader.setShadowTexture(1);\n // regularShader.setShadowTexture(1);\n // gl.activeTexture(gl.TEXTURE1);\n // gl.bindTexture(gl.TEXTURE_2D, shadowMapBuffer.frameTexture);\n mainShader.setTexture(0);\n mainShader.setTexture(1);\n particleShader.setTexture(0);\n particleShader.setTexture(1);\n regularShader.setTexture(0);\n regularShader.setTexture(1);\n mainAtlas.bind(0);\n envMap.bind(1);\n renderScene(mainShader, particleShader, regularShader, deltaTime);\n frameCount++;\n stats.end();\n if (shouldCapture) {\n downloadImage();\n shouldCapture = false;\n }\n prevTime = Date.now();\n // Tell the browser to call `tick` again whenever it renders a new frame\n requestAnimationFrame(tick);\n }", "componentDidMount() {\n // For Dimention Changing Runtime Responsiveness\n AddOrientation(this);\n }", "function handleOrientation(event){\n\t\tbeta = Math.floor(event.beta);\n\t\tgamma = Math.floor(event.gamma);\n\n\t\t//send the values to the DOM so we can actually see what they are \n\t\t// document.getElementById('alpha').innerHTML = alpha;\n\t\t// document.getElementById('beta').innerHTML = beta;\n\t\t// document.getElementById('gamma').innerHTML = gamma;\n\n\t\tsocket.emit('orientation',{\n\t\t\t// 'alpha':alpha,\n\t\t\t'beta': beta,\n\t\t\t'gamma': gamma\n\t\t});\n\n\t}", "display() {\n requestAnimationFrame(()=>{this.display();});\n\n if(this.effectController.showGround){\n this.drawPlane(1,12,12);\n }else{\n this.removePlane();\n }\n\n if(this.effectController.showAxes){\n this.drawAxes(15);\n }else{\n this.removeAxes();\n }\n\n if(this.viewSide!=this.effectController.viewSide)\n {\n this.setLookDirection(this.effectController.viewSide);\n this.viewSide = this.effectController.viewSide;\n }\n\n if(this.lightType!=this.effectController.lightType){\n this.setLightType(this.effectController.lightType);\n this.lightType = this.effectController.lightType;\n }\n \n if(this.lightType == \"1\"){\n this.headLight.position.copy(this.camera.position);\n }\n\n this.renderer.render(this.scene, this.camera);\n this.controls.update();\n }", "function render() {\n\tvar allowedToMove = false;\n\t// Here we control how the camera looks around the scene.\n\tcontrols.activeLook = false;\n\tif (mouseOverCanvas) {\n\t\tif (mouseDown) {\n\t\t\tcontrols.activeLook = true;\n\t\t}\n\t}\n\tvectorPosition = camera.getWorldPosition( cameraPosVector );\n\tif (vectorPosition.x != cameraPosition.x || vectorPosition.y != cameraPosition.y || vectorPosition.z != cameraPosition.z) {\n\t\tcameraPosition.x = vectorPosition.x;\n\t\tcameraPosition.y = vectorPosition.y;\n\t\tcameraPosition.z = vectorPosition.z;\n\t} else {\n\t\t//console.log(\"i am saving time\");\n\t}\n\t//var log = document.getElementById('log');\n\n\n\tif (checkCollision('forward') == true) {\n\t\tcontrols.moveForward = false;\n\t\t//log.innerHTML = \"FORWARD HIT!\";\n\t}\n\tif (checkCollision('backward') == true) {\n\t\tcontrols.moveBackward = false;\n\t\t//log.innerHTML = \"BACKWARD HIT!\";\n\t}\n\tvar deltaTime = clock.getDelta();\n\n\t// Update the controls.\n\tcontrols.update(deltaTime);\n\n\t// Render the scene.\n\trenderer.render(scene, camera);\n\n\t// Update the stats.\n\tstats.update();\n\n\t// Request the next frame.\n\t/* The \"requestAnimationFrame()\" method tells the browser that you\n\t wish to perform an animation and requests that the browser call a specified\n\t function to update an animation before the next repaint. The method takes\n\t as an argument a callback to be invoked before the repaint. */\n\trequestAnimationFrame(render);\n}", "function addControls() {\n controls = new TrackballControls(camera);\n controls.addEventListener('change', render);\n controls.rotateSpeed = 1.0;\n controls.zoomSpeed = 10;\n controls.panSpeed = 0.8;\n\n controls.noZoom = false;\n controls.noPan = false;\n\n controls.staticMoving = true;\n controls.dynamicDampingFactor = 0.3;\n}", "function render() {\n renderer.render(scene, camera)\n //moving the camera\n \n //lets make sure we can move camera smoothly based on user's performance. \n var time = performance.now();\n var delta = ( time - prevTime ) / 1000;\n \n\t\t\t//reset z velocity to be 0 always. But override it if user presses up or w. See next line... \n\t\t\t\t\tvelocity.z -= velocity.z * 90.0 * delta;\n //if the user pressed 'up' or 'w', set velocity.z to a value > 0. \n if ( moveForward ) velocity.z -= 400.0 * delta;\n \n //pass velocity as an argument to translateZ and call it on camera.\n camera.translateZ( velocity.z * delta );\n \n \tprevTime = time;\n \n //ignore this\n activateParticleWave();\n }", "make_control_panel(graphics_state)\r\n // Draw the scene's buttons, setup their actions and keyboard shortcuts, and monitor live measurement\r\n {\r\n let r = Math.PI/8.\r\n this.control_panel.innerHTML += \"Use these controls to <br> fly your rocket!<br>\";\r\n this.key_triggered_button( \"Rotate up\", [ \"w\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.rotation(r, Vec.of(1,0,0)))\r\n });\r\n this.key_triggered_button( \"Rotate left\", [ \"a\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.rotation(r, Vec.of(0,0,1)))\r\n\r\n });\r\n this.key_triggered_button( \"Rotate down\", [ \"s\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.rotation(-r, Vec.of(1,0,0)))\r\n });\r\n this.new_line();\r\n this.key_triggered_button( \"Rotate right\", [ \"d\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.rotation(-r, Vec.of(0,0,1)))\r\n });\r\n this.key_triggered_button( \"Fire Booster\", [ \"'\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.translation([0, 0.5, 0]))\r\n }); \r\n this.key_triggered_button( \"Fire Reverse Booster\", [ \"[\" ], () => {\r\n this.rocket_transform = this.rocket_transform.times(Mat4.translation([0, -0.5, 0]))\r\n }); this.key_triggered_button( \"Fire laser\", [ \";\" ], () => {\r\n //This shit don't work\r\n let laser_tf = this.rocket_transform;\r\n laser_tf = laser_tf.times(Mat4.translation([0,3,0])); //Current tip of rocket height\r\n laser_tf = laser_tf.times(Mat4.scale([1, 3, 1]));\r\n laser_tf = laser_tf.times(Mat4.translation([0,this.t,0]));\r\n this.shapes.box.draw(graphics_state, laser_tf, this.plastic.override({color: Color.of(57/255,1,20/255,1)}));\r\n });\r\n }", "function figureMeshAndContolDevice() {\n figureMaterial();\n Figure();\n\n oneSideMesh = new THREE.Mesh(geometry, material);\n\n scene = new THREE.Scene();\n scene.background = new THREE.Color(0x000000);\n scene.add(oneSideMesh);\n\n controls = new THREE.DeviceOrientationControls(oneSideMesh);\n}", "display() {\n // ---- BEGIN Background, camera and axis setup\n\n // Clear image and depth buffer everytime we update the scene\n this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);\n this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT);\n\n // Initialize Model-View matrix as identity (no transformation)\n this.updateProjectionMatrix();\n this.loadIdentity();\n\n // Apply transformations corresponding to the camera position relative to\n // the origin\n this.applyViewMatrix();\n\n // Update all lights used\n this.updateLights();\n\n /*this.pushMatrix();\n this.translate(-100, -5, 0);\n this.scale(400, 1, 250);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.floor.display();\n this.popMatrix();\n\n // Ring core\n this.pushMatrix();\n this.translate(0, 5, 0);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.scale(40, 40, 1);\n this.ringMat.apply();\n this.ringCore.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(0, -5, 0);\n this.rotate(Math.PI / 2, 1, 0, 0);\n this.scale(40, 40, 1);\n this.ringCore.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(0, 0, 20);\n this.scale(40, 10, 1);\n this.ringApron.apply();\n this.ringCore.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(0, 0, -20);\n this.rotate(Math.PI, 0, 1, 0);\n this.scale(40, 10, 1);\n this.ringCore.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(20, 0, 0);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(40, 10, 1);\n this.ringCore.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 0, 0);\n this.rotate(-Math.PI / 2, 0, 1, 0);\n this.scale(40, 10, 1);\n this.ringCore.display();\n this.popMatrix();\n\n this.defaultMaterial.apply();\n\n this.pushMatrix();\n this.translate(16.25,0,16.25);\n this.rotate(Math.PI/4,0,1,0);\n this.stairs.display();\n this.popMatrix();\n\n \n\n this.defaultMaterial.apply();\n\n this.pushMatrix();\n this.translate(20, -5, 20);\n this.scale(1, 22, 1);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.ringPost.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, -5, -20);\n this.scale(1, 22, 1);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.ringPost.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(20, -5, -20);\n this.scale(1, 22, 1);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.ringPost.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, -5, 20);\n this.scale(1, 22, 1);\n this.rotate(-Math.PI / 2, 1, 0, 0);\n this.ringPost.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 11.5, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRopeApp.apply();\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 15, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 8, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(20, 11.5, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(20, 15, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(20, 8, -20);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 11.5, -20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 15, -20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 8, -20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 11.5, 20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 15, 20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-20, 8, 20);\n this.rotate(Math.PI / 2, 0, 1, 0);\n this.scale(0.25, 0.25, 40);\n this.ringRope.display();\n this.popMatrix();\n\n this.defaultMaterial.apply();\n\n // ramp\n\n this.pushMatrix();\n this.translate(-120, 5, 0);\n this.ramp.display();\n this.popMatrix();\n\n // barrier\n\n this.pushMatrix();\n this.barrierApp.apply();\n this.barrier.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(-30, 0, -75);\n this.chairApp.apply();\n this.chairs.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(35, 0, 75);\n this.rotate(Math.PI, 0, 1, 0);\n this.chairs.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(65, 0, -35);\n this.rotate(-Math.PI / 2, 0, 1, 0);\n this.chairs.display();\n this.popMatrix();\n\n this.defaultMaterial.apply();\n\n\n this.pushMatrix();\n this.translate(-195, 5, 0);\n this.scale(50, 20, 40);\n this.stage.display();\n this.popMatrix();\n\n \n this.pushMatrix();\n this.translate(Math.sin(this.inc)*10,70,Math.cos(this.inc)*10);\n this.rotate(this.inc,0,1,0);\n this.scale(10,10,10);\n \n this.pushMatrix();\n this.rotate(-Math.PI/2,1,0,0);\n this.scale(2.5,2.5,2.5);\n this.zephyr.apply();\n this.sphere.display();\n this.popMatrix();\n\n this.defaultMaterial.apply();\n\n this.pushMatrix();\n this.scale(2.5,1,2.5);\n this.rotate(Math.PI/2,1,0,0);\n this.circle.display();\n this.popMatrix();\n\n this.pushMatrix();\n this.rotate(Math.PI/2,0,0,1);\n this.torus.display();\n this.popMatrix();\n\n var angle = 2*Math.PI/20;\n var x = Math.cos(angle)*2.7;\n var z = Math.sin(angle)*2.7;\n\n for(let i = 0; i < 21; i++)\n {\n x = Math.cos(angle*i)*2.7;\n z = Math.sin(angle*i)*2.7;\n\n this.pushMatrix();\n this.translate(x,0.3,z);\n this.rotate(- angle*i + Math.PI/2,0,1,0);\n this.rotate(-Math.PI/4,1,0,0);\n this.scale(0.25,0.25,0.25);\n this.sphere.display();\n this.popMatrix(); \n\n }\n\n this.popMatrix();\n\n this.pushMatrix();\n this.translate(Math.sin(this.inc)*10,70,Math.cos(this.inc)*10);\n this.rotate(this.inc,0,1,0);\n this.scale(7.5,70,7.5); \n this.rotate(Math.PI/2,1,0,0);\n this.rick.apply();\n this.cylinder.display();\n this.popMatrix();\n\n this.defaultMaterial.apply();\n this.inc += 0.1;*/\n\n this.pushMatrix();\n this.rick.apply();\n //this.triangle.updateTexCoords(1.0,1.0);\n this.cylinder.display();\n this.popMatrix();\n\n\n // Draw axis\n if (this.drawAxis) this.axis.display();\n\n // ---- END Background, camera and axis setup\n\n // ---- BEGIN Scene drawing section\n\n // ---- END Scene drawing section\n }", "function handleOrientation() {\n if (device.landscape()) {\n removeClass('portrait');\n addClass('landscape');\n walkOnChangeOrientationList('landscape');\n } else {\n removeClass('landscape');\n addClass('portrait');\n walkOnChangeOrientationList('portrait');\n }\n\n setOrientationCache();\n}", "update () {\n this.updateAngle()\n\n const videoMesh = this.el.getObject3D('mesh')\n videoMesh.renderOrder = this.data.onTop ? 990 : undefined\n videoMesh.material.depthTest = this.data.onTop\n videoMesh.material.depthWrite = this.data.onTop\n }", "render() {\n this.vrEffect.render(this.scene, this.camera);\n }", "function controls(){\n\tdocument.addEventListener(\"keydown\", onDocumentKeyDown, false);\n\tfunction onDocumentKeyDown(event) {\n\t var keyCode = event.which;\n\t \n\t if (keyCode == 40 && animating == false) {//down\n\t \tresetToPlayerPOV();\n\t \tif(playerDirection.equals(new THREE.Vector2(0,-playerViewDistance)))//North\n\t \t{\n\t \t\tplayerDirection.set(0,playerViewDistance);//South\n\t \t}else if(playerDirection.equals(new THREE.Vector2(playerViewDistance,0)))//East\n\t \t{\n\t \t\tplayerDirection.set(-playerViewDistance,0);//West\n\t \t}else if(playerDirection.equals(new THREE.Vector2(0,playerViewDistance)))//South\n\t \t{\n\t \t\tplayerDirection.set(0,-playerViewDistance);//North\n\t \t}else if(playerDirection.equals(new THREE.Vector2(-playerViewDistance,0)))//West\n\t \t{\n\t \t\tplayerDirection.set(playerViewDistance,0);//East\n\t \t}\n\t \trotateCamera(playerDirection.getComponent(0),playerDirection.getComponent(1));\n\t } else if (keyCode == 37 && animating == false) {//left\n\t \tresetToPlayerPOV();\n\t \tif(playerDirection.equals(new THREE.Vector2(0,-playerViewDistance)))//North\n\t \t{\n\t \t\tplayerDirection.set(-playerViewDistance,0);//West\n\t \t}else if(playerDirection.equals(new THREE.Vector2(playerViewDistance,0)))//East\n\t \t{\n\t \t\tplayerDirection.set(0,-playerViewDistance);//North\n\t \t}else if(playerDirection.equals(new THREE.Vector2(0,playerViewDistance)))//South\n\t \t{\n\t \t\tplayerDirection.set(playerViewDistance,0);//East\n\t \t}else if(playerDirection.equals(new THREE.Vector2(-playerViewDistance,0)))//West\n\t \t{\n\t \t\tplayerDirection.set(0,playerViewDistance);//South\n\t \t}\n\t \trotateCamera(playerDirection.getComponent(0),playerDirection.getComponent(1));\n\t } else if (keyCode == 38 && animating == false) {//up\n\t \tif(playerToMirrorPOV == true)\n \t\t{\n \t\t\tresetToPlayerPOV();\n \t\t}else{\n \t\t\tresetToMirrorPOV();\n \t\t}\n\t } else if (keyCode == 39 && animating == false) {//right\n\t \tresetToPlayerPOV();\n\t \tif(playerDirection.equals(new THREE.Vector2(0,-playerViewDistance)))//North\n\t \t{\n\t \t\tplayerDirection.set(playerViewDistance,0);//East\n\t \t}else if(playerDirection.equals(new THREE.Vector2(playerViewDistance,0)))//East\n\t \t{\n\t \t\tplayerDirection.set(0,playerViewDistance);//South\n\t \t}else if(playerDirection.equals(new THREE.Vector2(0,playerViewDistance)))//South\n\t \t{\n\t \t\tplayerDirection.set(-playerViewDistance,0);//West\n\t \t}else if(playerDirection.equals(new THREE.Vector2(-playerViewDistance,0)))//West\n\t \t{\n\t \t\tplayerDirection.set(0,-playerViewDistance);//North\n\t \t}\n\t \trotateCamera(playerDirection.getComponent(0),playerDirection.getComponent(1));\n\t } else if (keyCode == 86) { //\"v\"\n\t \t//Top down view of the area\n\t \tif(animating == false){\n\t \t\tif(topDownPOV == true)\n\t \t\t{\n\t \t\t\tresetToPlayerPOV();\n\t \t\t}else{\n\t \t\t\tresetToTopDownPOV();\n\t \t\t}\n\t \t}\n\t } else if (keyCode == 32 && animating == false) { // spacebar\n\t \t//move player\n\t \tresetToPlayerPOV();\n\t \tdeterminePlayerMovement();\n\t }else if (keyCode == 81 && animating == false){ // q\n\t \t//cheat\n\t \tcurrentLevel++;\n\t\t\tif(currentLevel >= MAXLEVEL)\n\t\t\t{\n\t\t\t\tclearMap();\n\t\t\t\talert(\"Congratulations, you are officially rich (Not in your real dimension)\");\n\t\t\t}else{\n\t\t\t\tclearMap();\n\t\t\t\tgenerateMapLevel(currentLevel);\n\t\t\t\tcreateLevel(currentLevel);\n\t\t\t}\n\t }else if (keyCode == 68 && animating == false){ //d = drill\n\t \t//drill\n\t \tattemptDrill();\n\t }else if (keyCode == 82 && animating == false){ // r\n\t \t//reset level\n\t \talert(\"Another pay day has been lost\")\n\t\t\tclearMap();\n\t\t\tgenerateMapLevel(currentLevel);\n\t\t\tcreateLevel(currentLevel);\n\t }else if (keyCode == 8 && welcomePageUp == true){ // backspace\n\t \tscene.remove(welcomeObject);\n\t \twelcomeObject = null;\n\t \twelcomePageUp = false;\n\t }\n\t};\n}", "function render() {\n\t\t\t\t\t\t// var timer = Date.now() * 0.0005;\n\t\t\t\t\t // camera.position.x = 10;\n\t\t\t\t\t\t// camera.position.y = 4;\n\t\t\t\t\t\t// camera.position.z = Math.sin(timer) * 10;\n\t\t\t\t\t\trenderer.render(scene, camera);\n\n\t\t\t\t\t}", "function render() {\n cameraThree.position.x += (mouseX - cameraThree.position.x) * .0005;\n cameraThree.position.y += (-mouseY - cameraThree.position.y) * .0005;\n var delta = clock.getDelta();\n\n controls.update(delta);\n\n //update GUI\n // cube.rotation.x += controls.rotationSpeed;\n // cube.rotation.y += controls.rotationSpeed;\n // cube.rotation.z += controls.rotationSpeed;\n // step += controls.bouncingSpeed;\n // sphere.position.x = 20 + (10 * (Math.cos(step)));\n // sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));\n // worldSphere.radius = guicontrols.worldradius\n // worldSphere = createMesh(new THREE.SphereGeometry(worldRadius, 10, 10));\n\n worldRadius = guicontrols.worldradius\n //gui ends\n for (var i = 0; i < experiences.length; i++) {\n if (videos[i].readyState === videos[i].HAVE_ENOUGH_DATA) {\n if (readyAllVideos == true) {\n\n // for (var k = 0; k < experiences.length; k++) {\n\n // if (whichMobile == \"iOS_mobile\") {\n\n // time = Date.now();\n // var elapsed = (time - lastTime) / 1000;\n\n // // render\n // if (elapsed >= ((1000 / framesPerSecond) / 1000)) {\n // videos[i].currentTime = videos[i].currentTime + elapsed;\n // videoImageContexts[i].drawImage(videos[i], 0, 0, videos[i].videoWidth, videos[i].videoHeight);\n // if (allvideoTextures[i])\n // allvideoTextures[i].needsUpdate = true;\n // lastTime = time;\n // }\n\n // // if we are at the end of the video stop\n // var currentTime = (Math.round(parseFloat(videos[i].currentTime) * 10000) / 10000);\n // var duration = (Math.round(parseFloat(videos[i].duration) * 10000) / 10000);\n // if (currentTime >= duration) {\n // // console.log('currentTime: ' + currentTime + ' duration: ' + videoo.duration);\n // // restart\n // videos[i].currentTime = 0;\n // return;\n // }\n\n // } else {\n\n if (videos[i].readyState === videos[i].HAVE_ENOUGH_DATA) {\n videoImageContexts[i].drawImage(videos[i], 0, 0);\n if (allvideoTextures[i])\n allvideoTextures[i].needsUpdate = true;\n }\n // }\n // }\n }\n\n\n }\n }\n renderer.render(scene, cameraThree);\n}", "function updateCameraForRender(self) {\n var cam = self.noa.camera\n var tgt = cam.getTargetPosition()\n self._cameraHolder.position.copyFromFloats(tgt[0], tgt[1], tgt[2])\n self._cameraHolder.rotation.x = cam.pitch\n self._cameraHolder.rotation.y = cam.heading\n self._camera.position.z = -cam.currentZoom\n\n // applies screen effect when camera is inside a transparent voxel\n var id = self.noa.getBlock(self.noa.camera.getPosition())\n checkCameraEffect(self, id)\n}", "function checkControlOrientation(scope){\n scope.control.isVertical = scope.control.height > scope.control.width;\n scope.control.isHorizontal = !scope.control.isVertical;\n\n if (scope.view.turnView){\n scope.control.isVertical = !scope.control.isVertical;\n scope.control.isHorizontal = !scope.control.isHorizontal;\n }\n }", "function addControls() {\n\tcontrols = new TrackballControls(camera);\n\tcontrols.addEventListener( 'change', render);\n\tcontrols.rotateSpeed = 1.0;\n\tcontrols.zoomSpeed = 10;\n\tcontrols.panSpeed = 0.8;\n\n\tcontrols.noZoom = false;\n\tcontrols.noPan = false;\n\n\tcontrols.staticMoving = true;\n\tcontrols.dynamicDampingFactor = 0.3;\n}", "render() {\n\n // Calculate delta\n if (!this.lastFrameTime) this.lastFrameTime = Date.now()\n this.delta = Math.min(1, (Date.now() - this.lastFrameTime) / 1000)\n this.lastFrameTime = Date.now()\n\n // Check if should be rendering\n if (!this.isRendering)\n return\n\n // Request another frame\n requestAnimationFrame(this.render)\n\n }" ]
[ "0.7324144", "0.7053003", "0.70370686", "0.70370686", "0.6963566", "0.6923311", "0.6886208", "0.68041205", "0.68027234", "0.6730315", "0.65977156", "0.6527159", "0.64324874", "0.6430578", "0.63880664", "0.62806225", "0.6267883", "0.6175145", "0.6174572", "0.61252576", "0.6104504", "0.60786927", "0.60716647", "0.6065912", "0.6047447", "0.60353595", "0.6004139", "0.59995866", "0.599491", "0.5987402", "0.5986368", "0.5986368", "0.5945152", "0.5945152", "0.5922085", "0.58933914", "0.5892358", "0.5887941", "0.5858965", "0.5843801", "0.5833078", "0.58168113", "0.5815163", "0.5813023", "0.5811666", "0.5800461", "0.579358", "0.578562", "0.577807", "0.5772769", "0.57668704", "0.576352", "0.57609767", "0.5750602", "0.5749747", "0.5749504", "0.5747164", "0.57352346", "0.5714599", "0.5714035", "0.570246", "0.5702142", "0.5692208", "0.56918067", "0.56909126", "0.5685273", "0.56712365", "0.5663958", "0.56569827", "0.5653887", "0.5653292", "0.5653198", "0.5652504", "0.56500506", "0.5645112", "0.5644457", "0.56339353", "0.5625274", "0.5614933", "0.5614035", "0.5610502", "0.5607509", "0.56008047", "0.5600584", "0.5595683", "0.55903244", "0.5581111", "0.5580639", "0.5569066", "0.5565432", "0.5564299", "0.5560259", "0.5560055", "0.55536383", "0.5548418", "0.55422014", "0.55409425", "0.55397433", "0.5539296", "0.5535619" ]
0.7035945
4
BEGIN add search history feature
function SearchHistory(maxLength) { this.maxLength = maxLength || 40; this.hist = []; } // function SearchHistory()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function add_event() {\n search_submit();\n //activeLoadMore();\n activeHistory();\n}", "function addQueryToHistory(query) {\n\n}", "function push_history() {\n\tedit_history_index++;\n\tsave_history();\n\tedit_history.length = edit_history_index+1;\n}", "async function handleAddSearch() {\n let newSavedSearch = savedsearch.concat([{ name: \"\", url: props.location.search }]);\n setSavedSearch(newSavedSearch);\n }", "function addHistory(event) {\n\n //Ignores/exits function if search item is empty\n if (searchItem.value.length < 1) return;\n console.log(searchItem.value)\n\n //used to create a variable \n //that hold list of searchItems in localStorage or parses\n //stringified list of items in local storage into a list\n var saved = JSON.parse(localStorage.getItem('searchItems'));\n console.log(saved)\n\n //if saved value is null/false set value to empty list\n //since no searchItems have been added\n if (!saved) {\n saved = []\n };\n\n //if there are 3 searchItems remove the oldest\n //in order to make room for new item/limit list length\n if (saved.length === 3) {\n saved.shift()\n }\n //push new searchItem's value into list\n saved.push(searchItem.value)\n\n // Clear input\n searchItem.value = '';\n\n // saves list to localStorage as a string\n localStorage.setItem('searchItems', JSON.stringify(saved));\n\n //function to create buttons of search items\n displayHistory()\n}", "function addHistory( data ) {\n\n if ( typeof(aio.history) != 'object' ) { aio.history = []; } // Change aio.history to array\n if ( typeof(aio.history) == 'object' && aio.history.length > 19 ) { aio.history.pop(); } // Delete oldest record if total exceeds 20\n\n // Add this new record\n aio.history.unshift( data );\n updateHistory();\n\n}", "function updateSearchHistory() {\r\n\t// displays searches alphabetically\r\n\t// getSearches returns searches in order of when they occurred\r\n\t\r\n\tvar taskIdx = selectedTaskIdx();\r\n\tvar searches = getSearches(taskIdx);\r\n\tif (searches.length==0) {\r\n\t\t$(\"#search_history\").html('No searches, yet');\r\n\t}\r\n\telse {\r\n\t\tvar sortedSearches = sortSearchesAlphabetically(taskIdx);\r\n\t\tvar html = '<ol>';\r\n\t\tfor (var i=0; i<sortedSearches.keys.length; i++) {\r\n\t\t\tvar key = sortedSearches.keys[i];\r\n\t\t\tvar search = sortedSearches.dict[key];\r\n\t\t\tvar query = search.query;\r\n\t\t\tvar links = search.links;\r\n\t\t\thtml += \"<li>\";\r\n\t\t\thtml += htmlEscape(query);\r\n\t\t\tif (links.length > 0) {\r\n\t\t\t\thtml += '<ul class=\"search_history_links\">';\r\n\t\t\t\tfor (var j=0; j<links.length; j++) {\r\n\t\t\t\t\tvar link = links[j];\r\n\t\t\t\t\tvar rating = link.rating == null ? UNRATED : link.rating;\r\n\t\t\t\t\thtml += '<li class=\"' + rating + '\">';\r\n\t\t\t\t\thtml += getLinkHtml(link.url, link.title, 20, rating, \"return onHistoryLinkClicked(event,'\"+htmlEscape(query)+\"');\");\r\n\t\t\t\t\thtml += \"&nbsp;\";\r\n\t\t\t\t\thtml += getRatingImage(rating);\r\n\t\t\t\t\thtml += '</li>';\r\n\t\t\t\t}\r\n\t\t\t\thtml += '</ul>';\r\n\t\t\t}\r\n\t\t\thtml += '</li>';\r\n\t\t}\r\n\t\thtml += '</ol>';\r\n\t\t$(\"#search_history\").html(html);\r\n\t}\r\n}", "function storeHistory() {\n\n if (search) {\n\n storageArr.unshift(search);\n localStorage.setItem('history', JSON.stringify(storageArr));\n return;\n }\n\n}", "function addEvents() {\n if (solr.options.call == 2 && Boolean($('#keyword_default').val())) {\n $('#keyword').val($('#keyword_default').val());\n solr.onSearchEvent();\n }\n}", "onSearch() {\n try {\n const searchText = this.getSearchHash();\n if (searchText === this.priorSearchText)\n return;\n this.engine.search(searchText);\n this.priorSearchText = searchText;\n }\n catch (ex) {\n this.publish(\"error\", ex.message);\n }\n }", "saveHistory(query) {\n let searchHistory = localStorage.getItem('searchHistory');\n searchHistory = searchHistory ? JSON.parse(searchHistory) : [];\n searchHistory.push({\n query,\n time: Date.now(),\n });\n searchHistory = takeRight(searchHistory, 50); // Latest 50 searches\n this.setState({\n searchHistory: searchHistory,\n });\n localStorage.setItem('searchHistory', JSON.stringify(searchHistory));\n }", "function search(config) {\n var settings = config.settings,\n filters = config.filters;\n\n historyView.displayThrobber();\n\n EHistory.search({\n text: settings.text || '',\n startTime: new Date(settings.startTime || 0).getTime() ,\n endTime: new Date(settings.endTime || Date.now()).getTime(),\n maxResults: historyModel.pageSize\n }, filters, function(results){\n historyModel.append(results);\n });\n }", "afterSearch(result, params) {\n console.log(\"Hereeeeeeeeeee 12\");\n }", "function init() {\n // gets local storage\n var storedHistory = JSON.parse(localStorage.getItem('history'))\n // If local storage isn't null\n if (storedHistory !== null) {\n // Updates storage array with the storedHistory\n storageArr = storedHistory\n var historyOLEl = document.getElementById('historyOL')\n // resets search history\n while (historyOLEl.firstChild) {\n historyOLEl.removeChild(historyOLEl.childNodes[0]);\n }\n // sets search history\n for (var i = 0; i < 4; i++) {\n if (i < storedHistory.length) {\n const historyItem = document.createElement('li')\n historyItem.textContent = storedHistory[i]\n historyOLEl.append(historyItem)\n // makes searches clickable to make them appear in search bar\n historyItem.addEventListener('click', function (event) {\n event.preventDefault();\n \n searchInputEl.value = historyItem.textContent\n \n });\n }\n }\n }\n\n return;\n}", "function handleNewSearch(data){\n setNewNavigation(data);\n clearOldResults(data);\n renderResults(data);\n}", "beginProcess() {\n this.index.start = this.history.length;\n }", "function addHistoryFeed(params, cb){\n //\n var timeStamp = new Date();\n var id = objID();\n var histObj ={\n _id: id,\n type: params.type, //'lusent' or 'sentanno'\n refs: {\n frameName: params.framename,\n luName: params.luname,\n sentenceID: params.sentenceid\n },\n cDate : timeStamp,\n cBy: params.username,\n text: createHistStr(params.type, params)\n };\n var histMod = new Models.historyModel(histObj)\n histMod.save(cb);\n}", "function newSearch() {\n window.location.href = \"../list/?service=\" + svcSearch +\"&range=\" + distSearch+\"/\"\n }", "function updateHistory() {\n // The city grabbed from the search bar\n let newCity = $(searchInput).val().trim();\n // Clear the search bar now that data is saved\n searchInput.value = \"\";\n // Bring up the empy error modal if search bar is empty\n if (!newCity) {\n emptyModal();\n return;\n }\n else {\n // Search city based on the input and reload array\n searchCityWeather(newCity, true);\n }\n }", "addToHistory({ commit }, command) {\n commit('ADD_TO_HISTORY', command)\n }", "updateRecents() {\n if (this['searchTerm']) {\n const enabledIds = this.searchManager.getEnabledSearches().map(osSearch.getSearchId).sort();\n\n const recentIndex = olArray.findIndex(this['recentSearches'], function(recent) {\n return recent.term == this['searchTerm'];\n }.bind(this));\n\n if (recentIndex > -1) {\n // already in the array, so move it to the top\n googArray.moveItem(this['recentSearches'], recentIndex, 0);\n } else {\n const recent = /** @type {!osx.search.RecentSearch} */ ({\n ids: enabledIds,\n term: this['searchTerm']\n });\n\n this['recentSearches'].unshift(recent);\n\n if (this['recentSearches'].length > Controller.MAX_RECENT_) {\n this['recentSearches'].length = Controller.MAX_RECENT_;\n }\n }\n\n this.saveRecent_();\n }\n }", "function delegate_history(data) {\n\tif(haswebsql) {\n\t\tsstorage.lastviewed=Ext.encode(data);\n\t\tglossdb.data.addhistory(data.title,data.target);\n\t}\n\telse {\n\t\tstorage.lastviewed = Ext.encode(data);\n\t}\n}", "function loadSearch() {\n let storedHistory = JSON.parse(localStorage.getItem(\"searchHistory\"));\n if (storedHistory !== null) {\n searchHistory = storedHistory\n }\n saveSearch();\n}", "function saveSearchHistory(searchInput) {\n searchHistory.push(searchInput);\n localStorage.setItem(PLACEHOLDER_KEY, JSON.stringify(searchHistory));\n}", "function History() {\n}", "function addToHistoryBasic(){\n\tvar inputScreen = document.querySelector('.screen');\n\tvar expression = inputScreen.innerHTML;\n\tvar newHistElt = document.createElement(\"div\");\n\tnewHistElt.className = 'history-element';\n newHistElt.innerHTML = expression;\n newHistElt.addEventListener('click',function(){addHistExprToScreen(expression)},false);\n //don't add empty strings to the history box\n if(expression != ''){\n \t//add the expression to the history box\n \thistoryBox.appendChild(newHistElt);\n }\n //auto-scroll to the bottom of the box when a new expression is added\n historyBox.scrollTop = historyBox.scrollHeight;\n}", "function addToHistoryAdv(){\n\tif (!this.classList.contains(\"disabled\")){\n\t\tvar newHistElt = document.createElement(\"div\");\n\t\tnewHistElt.className = 'history-element';\n\t newHistElt.innerHTML = advancedExpr;\n\t newHistElt.addEventListener('click',function(){addHistExprToScreen(newHistElt.innerHTML)},false);\n\t historyBox.appendChild(newHistElt);\n\t //auto-scroll to the bottom of the box when a new expression is added\n\t historyBox.scrollTop = historyBox.scrollHeight;\n\t}\n}", "function setHistory() {\n // clear undo history\n $('#undoHistoryList')\n .empty();\n\n // load new history list from server\n getHistoryFromServer(addHistList);\n}", "function _triggerSearch() {\n Mediator.pub(\n CFG.CNL.DICTIONARY_SEARCH,\n (_searchIsActive ? _$search.val() : \"\")\n );\n }", "function addInHistory(data){\n if(history.length > 100) history.shift();\n history.push(data);\n}", "function initSearch() {\r\n\tconsole.log(\"searchReady\");\r\n}", "function addToSearchHistory() {\n searchedCities.empty();\n for (let i = 0; i < previousCities.length; i++) {\n let cityNames = previousCities[i];\n\n let liElement = $(\"<li>\");\n liElement.text(cityNames);\n liElement.attr(\"class\", \"previous-city\");\n\n searchedCities.append(liElement);\n }\n}", "function firstLoadForTab_Search()\n{\n //console.log('first load for search tab');\n \n tryPopulateDB();\n \n global_pagesLoaded.search = true;\n}", "function searchHistory(event) {\n event.preventDefault();\n selectedCity = event.target.getAttribute(\"id\");\n saveStorage();\n updateSearchHistory();\n getWeather().then(() => {\n checkDisplayWeather();\n updateWeatherDisplay();\n });\n}", "function initializeHistoryExample() {\n pubnubStocks.bind('mousedown,touchstart', loadHistoryBtn, function() {\n pubnubStocks.history({\n limit: 5,\n channel: 'MSFT',\n callback: function(msgs) {\n historyOut.innerHTML = JSON.stringify(msgs[0]);\n },\n });\n\n return false;\n });\n }", "function histTransaction(history, state, dispatch, redo) {\n var preserveItems = mustPreserveItems(state), histOptions = historyKey.get(state).spec.config;\n var pop = (redo ? history.undone : history.done).popEvent(state, preserveItems);\n if (!pop) { return }\n\n var selection = pop.selection.resolve(pop.transform.doc);\n var added = (redo ? history.done : history.undone).addTransform(pop.transform, state.selection.getBookmark(),\n histOptions, preserveItems);\n\n var newHist = new HistoryState(redo ? added : pop.remaining, redo ? pop.remaining : added, null, 0);\n dispatch(pop.transform.setSelection(selection).setMeta(historyKey, {redo: redo, historyState: newHist}).scrollIntoView());\n}", "getHistory() {\n app.pageIndex--;\n app.searchProjects = app.history[app.pageIndex - 1];\n console.log(app.pageIndex);\n console.log(app.history.length);\n }", "async function allSearch(searchTerm) {\n\tconst wikipedia = await wikiSearch(searchTerm);\n\tconst youtube = await youTubeSearch(searchTerm);\n const listenNotes = await listenNotesSearch(searchTerm);\n\tconst apiNews = await apiNewsSearch(searchTerm);\n\t\n\tconst historyItem = {\n\t\twikipedia,\n\t\tyoutube,\n\t\tlistenNotes,\n apiNews,\n\t\tsearchTerm,\n\t};\n\n\tappendHistory(historyItem);\n}", "function concHistory(newInput){\n history += newInput;\n setHistory(history);\n }", "function emitSearch(event){ if (event.which == 13) {addSearch();}}", "function addToHistory(line){\n history.push(line);\n restoreText = '';\n }", "beforeSearch(params, populate) {\n console.log(\"Hereeeeeeeeeee 11\");\n }", "function startNewSearch (searchName) {\n\tif (!searchName || searchName === '') {\n\t\tconsole.error('[Model][startNewSearch]: Empty searchName');\n\t\treturn false;\n\t}\n\tupdateImageList([]);\n\tresetPage();\n\tsetSearchName(searchName);\n\t//resetRequestStatus();\n\tsetSelectIdx(0);\n\tmakeRequest();\n}", "function onLinkFollowed(query, url, title) {\t\r\n var taskIdx = selectedTaskIdx();\r\n addLinkFollowed(taskIdx, query, url, title, true);\r\n gCurrentSearch = {\"query\":query, \"url\":url };\r\n\tupdateSearchHistory();\r\n}", "function loadSearchHistory() {\n if (localStorage.getItem('previous-search') === null) {\n } else if (localStorage.getItem('previous-search') === '') {\n\n }\n else {\n prevSearchArr = prevSearchArr.concat(JSON.parse(localStorage.getItem('previous-search')));\n console.log(prevSearchArr);\n for (var i = 0; i < prevSearchArr.length; i++) {\n var searchedItem = $('<div>');\n var prevSearchBtn = $('<button>');\n prevSearchBtn.addClass('button secondary');\n prevSearchBtn.text(prevSearchArr[i]);\n searchedItem.attr('style', 'margin-bottom: 15px;')\n searchedItem.append(prevSearchBtn);\n prevSearchList.append(searchedItem);\n }\n }\n}", "function extendSearchWithAutoComplete(cm) {\n \n function addToSearchHistory(cm, query) {\n getSearchHistory(cm).add(query);\n } // function addToSearchHistory()\n\n // tracks search history\n cm.on(\"searchEntered\", addToSearchHistory);\n cm.on(\"replaceEntered\", addToSearchHistory);\n\n // add auto complete by search history to search dialog\n cm.on(\"searchDialog\", setupDialogAutoComplete);\n } // function extendSearchWithAutoComplete(..)", "resetHistory() {\n this.autoList.removeAll();\n var history = JSON.parse(localStorage.getItem('searchHistory'));\n if (history) {\n for (var i = 0; i < history.length; i++) {\n this.addBack(history[i]);\n }\n }\n }", "function trackSearch(extendTrack) {\n var payload = {\n name: 'jobSearch',\n tag: !vm.pageOnlyTracking ? 'event1' : null,\n location: $location.search().where,\n keywords: $location.search().q,\n pageIndex: $location.search().page_index ? $location.search().page_index : 1,\n }\n\n if (extendTrack) {\n angular.merge(payload, extendTrack);\n }\n\n $rootScope.track(payload);\n vm.pageOnlyTracking = false;\n }", "function handleBtnClick(event) {\n var searchHistory = [];\n\n searchHistory = state.searchTerms;\n event.preventDefault();\n // call hacker news api to retrieve articles based upon searchTerm\n API.getHackerNews(searchTerm)\n .then(news => {\n // store returned list into state variable of news\n setNews(news.data.hits);\n console.log(news.data.hits[3].url);\n })\n .catch(err => console.log(err));\n searchHistory.push(searchTerm);\n // store new search term into \"store\" for state management\n dispatch({\n type: \"searchTerms\",\n searchTerms: searchHistory\n });\n }", "function displayNewSearchResults(event) {\n let searchTerm = event.target.value;\n let currentSearch = giphy[\"query\"][\"q\"];\n if (searchTerm !== currentSearch && searchTerm !== \"\") {\n giphy[\"query\"][\"q\"] = searchTerm;\n updateOffset(true);\n update();\n }\n}", "function searchHistory(city) {\n var oldHistory = JSON.parse(localStorage.getItem(\"searchHistory\"));\n var newHistory = [];\n\n if (!Array.isArray(oldHistory)) {\n newHistory.unshift(city); // if object retrieved from storage is not an array add the city to new history array\n } else {\n newHistory = oldHistory; // add the old history to the new history\n };\n\n // add city if missing from newHistory array\n if (!newHistory.includes(city)) {\n newHistory.unshift(city);\n };\n\n localStorage.setItem(\"searchHistory\", JSON.stringify(newHistory)); // save newHistory array to storage.\n\n renderBtns(newHistory); // re-renders buttons with new list\n}", "function searchVisitHistory() {\r\n\t\r\n\thistoryClear();\t// Clear of the visit history table.\r\n\t\r\n\t// Set phone number\r\n\t//document.querySelector( '#usrId' ).value = document.querySelector( '#phone1' ).value + document.querySelector( '#phone2' ).value + document.querySelector( '#phone3' ).value;\r\n\t\r\n\tpageNo = firstPageNo;\t// Initiate variable of page number.\r\n\t\r\n\t// Check search conditions.\r\n\t//console.log( \"from = \" + document.querySelector( \"#sFromDate\" ).value );\r\n\t//console.log( \"to = \" + document.querySelector( \"#sToDate\" ).value );\r\n\tif( document.querySelector( \"#sFromDate\" ).value > document.querySelector( \"#sToDate\" ).value ) {\r\n\t\tshowComModal( {msg:mLang.get(\"checkdatestartandend\"),closeCallbackFnc:function(){ document.querySelector( \"#sFromDate\" ).nextElementSibling.focus() }} );\r\n\t \treturn false;\r\n\t}\r\n\t\r\n\t// Send ajax data.\r\n\tajaxSend( \"./findVisitHistory.json\" \r\n\t\t\t, { usrId\t: document.querySelector( 'input[name=\"usrId\"]'\t).value\r\n\t\t\t\t, fDt\t: document.querySelector( \"#sFromDate\" \t\t\t).value\r\n\t\t\t\t, tDt\t: document.querySelector( \"#sToDate\" \t\t\t).value\r\n\t\t\t\t, usrNm\t: document.querySelector( \"#usrNm\" \t\t\t).value\r\n\t\t\t }\r\n\t\t\t, searchVisitHistoryAft );\r\n\t\r\n}", "save() {\n if (this._history.length > 9){\n this._history.shift();\n }\n this._history.push(this.internalData);\n // Make the commit to setup the index and the state\n this.commit();\n }", "function history() {\n var searchList = $(\"#search-history\");\n var addCity = $('<button>');\n addCity.attr('class', 'btn text-light bg-dark');\n addCity.attr('id', city);\n addCity.text(city);\n searchList.append(addCity);\n}", "createdHookScopeIndex () {\n this.fetchRecords()\n }", "append (behavior) {\n return this.history.append(behavior)\n }", "function updateWatchHistory() {\n\tchrome.history.search({\n\t\t'text': '',\n\t\tmaxResults: 1\n\t}, function(historyItems) {\n\t\tvar str = historyItems[0].url;\n if(str.includes(\"netflix.com/watch\")){\n \t getNetflixMediaTitle();\n }else if(str.includes(\"hotstar\")&&str.includes(\"watch\")){\n \tconsole.log(historyItems[0].title);\n \t//getHotstarTitle();\n }else if(str.includes(\"primevideo\")&&str.includes(\"detail\")){\n //console.log(historyItems[0].title);\n getPrimeMediaTitle();\n }\n \n\t});\n}", "saveSearchRecord(val) {\n let r = Storage.get(Storage.KEYS.SEARCH_HISTORY)\n let arr = []\n if(r == null) {\n arr.push(val)\n // Storage.set('search-history', arr)\n Storage.set(Storage.KEYS.SEARCH_HISTORY, arr)\n this.props.updateLists(arr)\n } else {\n if(r.indexOf(val) === -1) {\n r.length >= 4 ? r.splice(0, 1, val) : r.unshift(val)\n // Storage.set('search-history', r)\n } else {\n let index = r.indexOf(val)\n r.splice(index, 1)\n r.unshift(val)\n }\n Storage.set(Storage.KEYS.SEARCH_HISTORY, r)\n this.props.updateLists(r)\n }\n this.props.hideNameList(val)\n }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function listenBefore(hook) {\n\t return history.listenBefore(function (location, callback) {\n\t _runTransitionHook2['default'](hook, addQuery(location), callback);\n\t });\n\t }", "function getSearchHistory() {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", 'http://localhost:8080/getSearchHistory');\n xhr.onload = function () {\n var res_str = JSON.stringify(xhr.responseText);\n var result = JSON.parse(res_str);\n displayHistory(result);\n }\n xhr.send();\n }", "_seedHistory() {\n log('Seeding history...');\n COMMON_ENTRY_POINTS.forEach((entryPoint) => this._addEntryPoint(entryPoint));\n this._writeHistoryFile();\n }", "function searchVisitHistoryAft( responseText ) {\r\n\t//console.log( responseText );\r\n\tif( responseText != NOT_EXIST_DATA ) {\r\n\t\t// Fill searched data.\r\n\t\tviewMetaInfo\t( JSON.parse(responseText).chVisitMeta \t);\r\n\t\tviewVisitHistory( JSON.parse(responseText).chVisit \t\t)\r\n\t} else {\r\n\t\t// There's no data. \r\n\t\tshowComModal( {msg:mLang.get(\"nosearchdata\")} );\r\n\t \treturn false;\t\t\t\t\t\r\n\t}\r\n}", "function onSearch() {\n var wasActive = !!activeSearch\n activeSearch = searchBox.value\n if (!wasActive) {\n viewer.addFilter(searchFilter)\n }\n clearOption.style.visibility = \"visible\"\n onSearchBlur()\n viewer.filter()\n refreshFilterPane()\n }", "function qodeOnWindowLoad() {\r\n qodeInitelementorListingSimpleSearch();\r\n }", "function searchHistory(query, proj, options, cb){\n console.log('DEBUG: searchDecisions')\n //({framename: \"asdasd\",luname: \"refs.luname\"}, query) = > {asdasd: query['framename'], 'refs.luname': query['luname']}\n var q =q2coll(query, '- refs.frameName - refs.luName sentenceID -')\n console.log(\"history query is: \", JSON.stringify(q));\n if (query['framename']) q['refs.frameName'] = query['framename'];\n console.log(\"history query is: \", JSON.stringify(q));\n if (query['type']) q['type'] = query['type'];\n if (query['username']) q['cBy'] = query['username'];\n if (query['decisionid']) q['_id'] = query['decisionid'];\n Models.historyModel.find(q, proj, options,cb);\n}", "function history() {\r\n sidebar.toggleHistory();\r\n}", "function listenBefore(hook) { // 59\n return history.listenBefore(function (location, callback) { // 60\n _runTransitionHook2['default'](hook, addQuery(location), callback);\n }); // 62\n } // 63", "startSearching() {\n // Initializing the pre search data so that the data can be recovered when search is finished\n this._preSearchData = this.crudStore.getData();\n }", "function oneSearchResult() {\n\toFocus = true;\n\t$.cookie('last_tab', '#account');\n}", "function recentQuickSearchBackButton_click() {\n var quickSearch = new helm.QuickSearch();\n var restoreSearch = quickSearch.recentSearches.getPrevious.call(quickSearch);\n if (restoreSearch != null) {\n var $QuickSearchTextBox_helm = $(\"#QuickSearchTextBox_helm\");\n\n //Infragistics igniteUI igTextEditor text box displays the recent Quick Search text as faded gray - italic. Fix This here.\n $QuickSearchTextBox_helm.toggleClass(\"ui-igedit-nullvalue\", false); \n \n\n $QuickSearchTextBox_helm.igTextEditor(\"text\", restoreSearch.searchText);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchStateCombo_helm\"), restoreSearch.stateAbbreviation);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchSubStatusCombo_helm\"), restoreSearch.subStatusTypeSkey);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchOrgCombo_helm\"), restoreSearch.searchAllOrgs);\n }\n\n \n }" ]
[ "0.71103793", "0.6877549", "0.65531814", "0.6381389", "0.62352484", "0.6163838", "0.6159021", "0.61563605", "0.61354864", "0.6108241", "0.6086516", "0.60528195", "0.6029893", "0.59965044", "0.59960973", "0.5982239", "0.59191203", "0.5918128", "0.5902587", "0.588985", "0.5877781", "0.5869101", "0.58647966", "0.5851951", "0.58467203", "0.58318806", "0.58187103", "0.58184737", "0.57990766", "0.57966465", "0.5788482", "0.5767663", "0.5757534", "0.5740081", "0.5738837", "0.5730605", "0.57297736", "0.5709955", "0.57095134", "0.5690696", "0.5683896", "0.56795174", "0.5665796", "0.5658259", "0.5654752", "0.5644522", "0.5632367", "0.5630955", "0.56282485", "0.56046927", "0.55979556", "0.55957985", "0.5581731", "0.55761784", "0.55718976", "0.5565758", "0.55468374", "0.55415493", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.55379635", "0.5532627", "0.5525019", "0.5521616", "0.55126315", "0.5512544", "0.55078053", "0.5506219", "0.5503304", "0.549879", "0.5493002", "0.5488187" ]
0.5550745
56
END search history feature Setup auto complete of searches by search history.
function setupDialogAutoComplete(cm, inpElt) { function getSearchHistoryHints(inpValue) { var res = []; var hist = getSearchHistory(cm).getAll(); for (var i = hist.length - 1; i >= 0; i--) { // all search query starts with inpValue, // including "" as inpValue if (!inpValue || hist[i].indexOf(inpValue) === 0) { if (res.indexOf(hist[i]) < 0) { // remove duplicates res.push(hist[i]); } } } // keep the reverse history order return res; } // function getCodeMirrorCommandHints() function autoCompleteSearchCmd(event) { // if Ctrl-space, if ("Ctrl-Space" === CodeMirror.keyName(event)) { event.preventDefault(); /// console.debug('Trying to to complete "%s"', event.target.value); var inpValue = event.target.value; var inpElt = event.target; CodeMirror.showHint4Dialog(cm, function() { var data = {}; data.list = getSearchHistoryHints(inpValue); data.inpElt = inpElt; return data; }, { pressEnterOnPick: false } ); } // if ctrl-space } // function autoCompleteSearchCmd(..) // // the main setup logic: add keydown to the input box specified // use keydown event rather than keypress to handle some browser compatibility issue // inpElt.onkeydown = autoCompleteSearchCmd; } // function setupDialogAutoComplete(..)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function extendSearchWithAutoComplete(cm) {\n \n function addToSearchHistory(cm, query) {\n getSearchHistory(cm).add(query);\n } // function addToSearchHistory()\n\n // tracks search history\n cm.on(\"searchEntered\", addToSearchHistory);\n cm.on(\"replaceEntered\", addToSearchHistory);\n\n // add auto complete by search history to search dialog\n cm.on(\"searchDialog\", setupDialogAutoComplete);\n } // function extendSearchWithAutoComplete(..)", "function initAutoComplete(){\n // jQuery(\"#contact_sphinx_search\")\n // jQuery(\"#account_sphinx_search\")\n // jQuery(\"#campaign_sphinx_search\")\n // jQuery(\"#opportunity_sphinx_search\")\n // jQuery(\"#matter_sphinx_search\")\n jQuery(\"#search_string\").keypress(function(e){\n if(e.which == 13){\n searchInCommon();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n\n jQuery(\"#lawyer_search_query\").keypress(function(e){\n if(e.which == 13){\n searchLawyer();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n}", "function setAutocomplete(tags){\n var dataArr = new Array();\n for ( var i = 0; i < tags.children.length; i++ ){\n for ( var j = 0; j < tags.children[i].children.length; j++ ){\n // use title, tag for label, category by tags\n var data = new Object();\n data['category'] = tags.children[i].title // tag name\n data['label'] = tags.children[i].children[j].title; // bookmark name\n dataArr.push(data);\n }\n }\n console.log(dataArr);\n $( \"#search\" ).bookmarkcomplete({\n delay: 0,\n source: dataArr\n });\n}", "function init() {\n // gets local storage\n var storedHistory = JSON.parse(localStorage.getItem('history'))\n // If local storage isn't null\n if (storedHistory !== null) {\n // Updates storage array with the storedHistory\n storageArr = storedHistory\n var historyOLEl = document.getElementById('historyOL')\n // resets search history\n while (historyOLEl.firstChild) {\n historyOLEl.removeChild(historyOLEl.childNodes[0]);\n }\n // sets search history\n for (var i = 0; i < 4; i++) {\n if (i < storedHistory.length) {\n const historyItem = document.createElement('li')\n historyItem.textContent = storedHistory[i]\n historyOLEl.append(historyItem)\n // makes searches clickable to make them appear in search bar\n historyItem.addEventListener('click', function (event) {\n event.preventDefault();\n \n searchInputEl.value = historyItem.textContent\n \n });\n }\n }\n }\n\n return;\n}", "resetHistory() {\n this.autoList.removeAll();\n var history = JSON.parse(localStorage.getItem('searchHistory'));\n if (history) {\n for (var i = 0; i < history.length; i++) {\n this.addBack(history[i]);\n }\n }\n }", "function add_event() {\n search_submit();\n //activeLoadMore();\n activeHistory();\n}", "function updateSearchHistory() {\r\n\t// displays searches alphabetically\r\n\t// getSearches returns searches in order of when they occurred\r\n\t\r\n\tvar taskIdx = selectedTaskIdx();\r\n\tvar searches = getSearches(taskIdx);\r\n\tif (searches.length==0) {\r\n\t\t$(\"#search_history\").html('No searches, yet');\r\n\t}\r\n\telse {\r\n\t\tvar sortedSearches = sortSearchesAlphabetically(taskIdx);\r\n\t\tvar html = '<ol>';\r\n\t\tfor (var i=0; i<sortedSearches.keys.length; i++) {\r\n\t\t\tvar key = sortedSearches.keys[i];\r\n\t\t\tvar search = sortedSearches.dict[key];\r\n\t\t\tvar query = search.query;\r\n\t\t\tvar links = search.links;\r\n\t\t\thtml += \"<li>\";\r\n\t\t\thtml += htmlEscape(query);\r\n\t\t\tif (links.length > 0) {\r\n\t\t\t\thtml += '<ul class=\"search_history_links\">';\r\n\t\t\t\tfor (var j=0; j<links.length; j++) {\r\n\t\t\t\t\tvar link = links[j];\r\n\t\t\t\t\tvar rating = link.rating == null ? UNRATED : link.rating;\r\n\t\t\t\t\thtml += '<li class=\"' + rating + '\">';\r\n\t\t\t\t\thtml += getLinkHtml(link.url, link.title, 20, rating, \"return onHistoryLinkClicked(event,'\"+htmlEscape(query)+\"');\");\r\n\t\t\t\t\thtml += \"&nbsp;\";\r\n\t\t\t\t\thtml += getRatingImage(rating);\r\n\t\t\t\t\thtml += '</li>';\r\n\t\t\t\t}\r\n\t\t\t\thtml += '</ul>';\r\n\t\t\t}\r\n\t\t\thtml += '</li>';\r\n\t\t}\r\n\t\thtml += '</ol>';\r\n\t\t$(\"#search_history\").html(html);\r\n\t}\r\n}", "async function handleAddSearch() {\n let newSavedSearch = savedsearch.concat([{ name: \"\", url: props.location.search }]);\n setSavedSearch(newSavedSearch);\n }", "function init() {\n\n\tvar iSearchText = $.bbq.getState( 'iSearchText' , true ) || undefined;\n\tvar iStart = $.bbq.getState('iStart', true) || 0;\n\tvar iSortCol = $.bbq.getState('iSortCol', true) || 1;\n\tvar iSortDir = $.bbq.getState('iSortDir', true) || 'ASC';\n\n\t$(\"input#searchChain\").keypress(function(e)\n\t{\n\t\t// if the key pressed is the enter key\n\t\t if (e.which == 13)\n\t\t {\n\t\t\t getChainList($(this).val(),0,0,'asc');\n\t\t\t e.preventDefault(); \n\t\t }\n\t\t\t \n\t});\n\n\t$('#searchByChain').click(searchByChain);\n\n\t//Auto complete search for top five records in a dropdown\n\t$(\"#searchChain\").autocomplete({\n minLength: 1,\n source: function( request, response){\n \tvar searchText = $('#searchChain').val()=='' ? undefined : $('#searchChain').val();\n \t$.ajax({\n \t\turl : HOST_PATH + \"admin/chain/search-chain/keyword/\" + searchText + \"/flag/0\",\n \t\t\tmethod : \"post\",\n \t\t\tdataType : \"json\",\n \t\t\ttype : \"post\",\n \t\t\tsuccess : function(data) {\n \t\t\t\t\n \t\t\t\tif (data != null) {\n \t\t\t\t\t\n \t\t\t\t\t//pass array of the respone in respone object of the autocomplete\n \t\t\t\t\tresponse(data);\n \t\t\t\t} \n \t\t\t},\n \t\t\terror: function(message) {\n \t\t\t\t\n \t // pass an empty array to close the menu if it was initially opened\n \t response([]);\n \t }\n \t\t });\n },\n select: function( event, ui ) {}\n }); \n\n\t// call to keyword list function while loading\n\tif ($(\"table#chainTable\").length) {\n\t\tgetChainList(iSearchText,iStart, iSortCol, iSortDir);\n\t}\n\n\n\t$(window).bind('hashchange', function(e) {\n\t\tif (hashValue != location.hash && click == false) {\n\t\t\tchainListTbl.fnCustomRedraw();\n\t\t}\n\t});\n\n\tif( $(\"form#addChainForm\").length > 0 )\n\t{\n\t\taddChainValidation();\n\t}\n}", "function updateHistory() {\n // The city grabbed from the search bar\n let newCity = $(searchInput).val().trim();\n // Clear the search bar now that data is saved\n searchInput.value = \"\";\n // Bring up the empy error modal if search bar is empty\n if (!newCity) {\n emptyModal();\n return;\n }\n else {\n // Search city based on the input and reload array\n searchCityWeather(newCity, true);\n }\n }", "function start() {\n var mc = autocomplete(document.getElementById('search'))\n .keys(keys)\n .dataField(\"State\")\n .placeHolder(\"Search States - Start typing here\")\n .width(960)\n .height(500)\n .onSelected(onSelect)\n .render();\n}", "function search_init(){\n\n // DOM contact points.\n var form_elt = '#search_form';\n var search_elt = '#search';\n\n // Helper lifted from bbop-js: bbop.core.first_split\n // For documentation, see:\n // http://cdn.berkeleybop.org/jsapi/bbop-js/docs/files/core-js.html\n var first_split = function(character, string){\n\tvar retlist = null;\n\n\tvar eq_loc = string.indexOf(character);\n\tif( eq_loc == 0 ){\n retlist = ['', string.substr(eq_loc +1, string.length)];\n\t}else if( eq_loc > 0 ){\n var before = string.substr(0, eq_loc);\n var after = string.substr(eq_loc +1, string.length);\n retlist = [before, after];\n\t}else{\n retlist = ['', ''];\n\t}\n\t\n\treturn retlist;\n };\n\n // Override form submission and bump to search page.\n jQuery(form_elt).submit(\n\tfunction(event){\n\t event.preventDefault();\n\t \n\t var val = jQuery(search_elt).val();\n\t var newurl = \"http://\"+window.location.host+\"/search/\"\n\t\t+encodeURIComponent(val);\n\t window.location.replace(newurl);\n\t});\n\n // Arguments for autocomplete box.\n var ac_args = {\n\tposition : {\n \t my: \"right top\",\n at: \"right bottom\",\n\t collision: \"none\"\n\t},\n\tsource: function(request, response) {\n\t console.log(\"trying autocomplete on \"+request.term);\n\n\t // Argument response from source gets map as argument.\n\t var _parse_data_item = function(item){\n\t\t\n\t\t// If has a category, append that; if not try to use\n\t\t// namespace; otherwise, nothing.\n\t\tvar appendee = '';\n\t\tif( item ){\n\t\t if( item['category'] ){\n\t\t\tappendee = item['category'];\n\t\t }else if( item['id'] ){\n\t\t\t// Get first split on '_'.\n\t\t\tvar fspl = first_split('_', item['id']);\n\t\t\tif( fspl[0] ){\n\t\t\t appendee = fspl[0];\n\t\t\t}\n\t\t }\n\t\t}\n\n\t\treturn {\n\t\t label: item.term,\n\t\t tag: appendee,\n\t\t name: item.id\n\t\t};\n\t };\n\t var _on_success = function(data) {\n\n\t\t// Pare out duplicates. Assume existance of 'id'\n\t\t// field. Would really be nice to have bbop.core in\n\t\t// here...\n\t\tvar pared_data = [];\n\t\tvar seen_ids = {};\n\t\tfor( var di = 0; di < data.length; di++ ){\n\t\t var datum = data[di];\n\t\t var datum_id = datum['id'];\n\t\t if( ! seen_ids[datum_id] ){\n\t\t\t// Only add new ids to pared data list.\n\t\t\tpared_data.push(datum);\n\t\t\t\n\t\t\t// Block them in the future.\n\t\t\tseen_ids[datum_id] = true;\n\t\t }\n\t\t}\n\n\t\tvar map = jQuery.map(pared_data, _parse_data_item);\n\t\tresponse(map);\n\t };\n\n\t var query = \"/autocomplete/\"+request.term+\".json\";\n\t jQuery.ajax({\n\t\t\t url: query,\n\t\t\t dataType:\"json\",\n\t\t\t /*data: {\n\t\t\t prefix: request.term,\n\t\t\t },*/\n\t\t\t success: _on_success\n\t\t\t});\n\t},\n\tmessages: {\n noResults: '',\n\t results: function() {}\n },\n\tselect: function(event,ui) {\n\t if (ui.item !== null) { \n\t\tvar newurl = \"http://\"+window.location.host+\"/search/\"\n\t \t +encodeURIComponent(ui.item.label);\n\t\twindow.location.replace(newurl);\n\t }\n\t}\t\n };\n\n // Create our own custom rendering to make the categories a little\n // nicer to look at (as minor data).\n // http://jqueryui.com/autocomplete/#custom-data\n var jac = jQuery(search_elt).autocomplete(ac_args);\n jac.data('ui-autocomplete')._renderItem = function(ul, item){\n\tvar li = jQuery('<li>');\n\tli.append('<a alt=\"'+ item.name +'\" title=\"'+ item.name +'\">' +\n\t\t '<span class=\"autocomplete-main-item\">' +\n\t\t item.label +\n\t\t '</span>' + \n\t\t '&nbsp;' + \n\t\t '<span class=\"autocomplete-tag-item\">' +\n\t\t item.tag +\n\t\t '</span>' + \n\t\t '</a>');\n\tli.appendTo(ul);\n\treturn li;\n };\n}", "function setupAutocomplete(data) {\t\n\n\t$(\"#addTermText\").focus();\n\t$(\"#addTermText\").keydown(function(event){\n\t\tif (event.keyCode == '13') {\n\t\t\taddTerm();\n\t\t}\n\t});\n}", "function newSearch() {\n window.location.href = \"../list/?service=\" + svcSearch +\"&range=\" + distSearch+\"/\"\n }", "function setUpAutoComplete(searchUrl) {\n $(\"#search-input\").autocomplete({\n source: function(request, response) {\n $.ajax({\n url: searchUrl,\n dataType: 'jsonp',\n data: {\n 'action': \"opensearch\",\n 'format': \"json\",\n 'search': request.term\n },\n success: function (data) {\n response(data[1]);\n }\n });\n }\n });\n}", "afterSearch(searchText, result) {\n }", "async function allSearch(searchTerm) {\n\tconst wikipedia = await wikiSearch(searchTerm);\n\tconst youtube = await youTubeSearch(searchTerm);\n const listenNotes = await listenNotesSearch(searchTerm);\n\tconst apiNews = await apiNewsSearch(searchTerm);\n\t\n\tconst historyItem = {\n\t\twikipedia,\n\t\tyoutube,\n\t\tlistenNotes,\n apiNews,\n\t\tsearchTerm,\n\t};\n\n\tappendHistory(historyItem);\n}", "function addHistory(event) {\n\n //Ignores/exits function if search item is empty\n if (searchItem.value.length < 1) return;\n console.log(searchItem.value)\n\n //used to create a variable \n //that hold list of searchItems in localStorage or parses\n //stringified list of items in local storage into a list\n var saved = JSON.parse(localStorage.getItem('searchItems'));\n console.log(saved)\n\n //if saved value is null/false set value to empty list\n //since no searchItems have been added\n if (!saved) {\n saved = []\n };\n\n //if there are 3 searchItems remove the oldest\n //in order to make room for new item/limit list length\n if (saved.length === 3) {\n saved.shift()\n }\n //push new searchItem's value into list\n saved.push(searchItem.value)\n\n // Clear input\n searchItem.value = '';\n\n // saves list to localStorage as a string\n localStorage.setItem('searchItems', JSON.stringify(saved));\n\n //function to create buttons of search items\n displayHistory()\n}", "function displayNewSearchResults(event) {\n let searchTerm = event.target.value;\n let currentSearch = giphy[\"query\"][\"q\"];\n if (searchTerm !== currentSearch && searchTerm !== \"\") {\n giphy[\"query\"][\"q\"] = searchTerm;\n updateOffset(true);\n update();\n }\n}", "function setupAutoComplete() {\n $('#newTagTextBox').autocomplete({\n source: htData,\n change: function(event, ui) {\n var newHT = $('#newTagTextBox').val();\n if(htData.includes(newHT)) {\n createAnInfoMessage($.i18n.prop('htviewer_newht_exists', newHT));\n return;\n }\n \n $.ajax({\n url: '/api/hashtags/',\n type: 'POST',\n data: newHT,\n contentType: 'text/plain',\n error: function(xhr,textStatus,errorThrown) {\n createAnErrorMessage($.i18n.prop('htviewer_newht_error', newHT));\n }\n }).then(function(data) {\n createAnInfoMessage($.i18n.prop('htviewer_newht_success', newHT));\n window.location.reload();\n });\n }\n });\n}", "function SearchHistory(maxLength) {\n this.maxLength = maxLength || 40;\n this.hist = []; \n } // function SearchHistory()", "function searchHistory(event) {\n event.preventDefault();\n selectedCity = event.target.getAttribute(\"id\");\n saveStorage();\n updateSearchHistory();\n getWeather().then(() => {\n checkDisplayWeather();\n updateWeatherDisplay();\n });\n}", "function displaySearchHistory() {\n $(\"#search-history\").empty();\n search_history.forEach(function (city) {\n var history_item = $(\"<li>\");\n history_item.addClass(\"list-group-item btn btn-light\");\n history_item.text(city);\n $(\"#search-history\").prepend(history_item);\n });\n\n $(\".btn\").click(getWeather);\n $(\".btn\").click(Forecast);\n }", "onSearch() {\n try {\n const searchText = this.getSearchHash();\n if (searchText === this.priorSearchText)\n return;\n this.engine.search(searchText);\n this.priorSearchText = searchText;\n }\n catch (ex) {\n this.publish(\"error\", ex.message);\n }\n }", "function addEvents() {\n if (solr.options.call == 2 && Boolean($('#keyword_default').val())) {\n $('#keyword').val($('#keyword_default').val());\n solr.onSearchEvent();\n }\n}", "function initiateSearch(str) {\n //if (str.slice(-1) == ' ') {\n //the following line may cause errors once the backend is fixxed\n //you can comment out the .then() part to make any errors stop\n CallSearch(str).then(updateBookmarkTable);\n //}\n }", "function autocomplete() {\nnew Ajax.Autocompleter ('autoCompleteTextField','menufield',\n'list.html',{});\n}", "function autosearch(event, asObj) {\r\n var input = $(event.target).val();\r\n var suggList = asObj.children().filter(\".suggestion-list\");\r\n\r\n // If the text-box has no characters, hide the suggestion list.\r\n if (input.length == 0) {\r\n suggList.css(\"display\", \"none\");\r\n autosearch.prevLen = 0;\r\n autosearch.suggestions = [];\r\n return;\r\n }\r\n\r\n if (autosearch.prevLen > input.length || autosearch.prevLen == 0 || autosearch.suggestions.length == 0) {\r\n var rqstData = { \"input\": input };\r\n\r\n // Run full query (AJAX data request to server).\r\n $.ajax({\r\n method: \"POST\",\r\n url: \"index.aspx/getSuggestedResults\",\r\n data: JSON.stringify(rqstData),\r\n contentType: \"application/json; charset=utf-8\",\r\n dataType: \"json\",\r\n success: function (data) {\r\n\r\n autosearch.suggestions = $.parseJSON(data.d);\r\n \r\n // Empty and hide the suggestions list.\r\n suggList.empty().css(\"display\", \"none\");\r\n\r\n // Update suggestions list.\r\n if (autosearch.suggestions.length > 0) {\r\n $.each(autosearch.suggestions, function (metakey, metavalue) {\r\n $.each(metavalue, function (key, value) {\r\n suggList.html(\r\n suggList.html() + \"<li class=\\\"suggestion-item\\\">\" + value + \"</li>\"\r\n );\r\n });\r\n });\r\n }\r\n\r\n // Display the updated suggestions list.\r\n suggList.css(\"display\", \"table\");\r\n }\r\n });\r\n }\r\n else {\r\n var metaTemp = [];\r\n // Filter existing list of values.\r\n $.each(autosearch.suggestions, function (metakey, metavalue) {\r\n var temp = [];\r\n $.each(metavalue, function (key, value) {\r\n if (value.toLowerCase().indexOf(input.toLowerCase()) != -1) { temp.push(value); }\r\n });\r\n if(temp.length != 0){metaTemp.push(temp);}\r\n });\r\n\r\n autosearch.suggestions = metaTemp;\r\n\r\n // Empty and hide the suggestions list.\r\n suggList.empty().css(\"display\", \"none\");\r\n\r\n // Update suggestions list.\r\n if (autosearch.suggestions.length > 0) {\r\n $.each(autosearch.suggestions, function (metakey, metavalue) {\r\n $.each(metavalue, function (key, value) {\r\n suggList.html(\r\n suggList.html() + \"<li class=\\\"suggestion-item\\\">\" + value + \"</li>\"\r\n );\r\n });\r\n });\r\n }\r\n\r\n // Display the updated suggestions list.\r\n suggList.css(\"display\", \"table\");\r\n }\r\n\r\n // Update static counter variable.\r\n autosearch.prevLen = input.length;\r\n }", "function _triggerSearch() {\n Mediator.pub(\n CFG.CNL.DICTIONARY_SEARCH,\n (_searchIsActive ? _$search.val() : \"\")\n );\n }", "function triggerRepresentationByHistory(startDate,endDate,blacklist) {\n chrome.history.search({text: '', startTime:startDate, endTime:endDate}, function (data) {\n if(localStorage[\"hostname\"] == \"\"){\n var list = {};\n data.forEach(function(page) {\n if(!isBlackListed(blacklist,page.url) && (extractHostname(page.url) != extractHostname(chrome.extension.getURL(\"\")))){\n var string = extractHostname(page.url);\n if(list[string] == null){\n httpGetAsync(extractHostname(page.url));\n list[string] = 1;\n }\n }\n });\n }else{\n var contor = 0;\n data.forEach(function(page) {\n if(!isBlackListed(blacklist,page.url) && (extractHostname(page.url) == localStorage[\"hostname\"]) && contor < results && !containCharacter(page.url,\";\")){\n contor = contor + 1;\n httpGetAsync(page.url);\n }\n });\n\n }\n localStorage[\"hostname\"] = \"\";\n });\n\n document.getElementById(\"dateSubmit\").disabled = false;\n}", "function setupUtenteSearch() {\r\n setupUserSearch();\r\n setupSNSSearch();\r\n}", "function searchProducts() {\n // get products via autocomplete - THIS IS FOR THE LOCATION GRAPH SECTION\n $(document).on('keyup.autocomplete','input[name=\"product\"]', function(event){\n if (event.keyCode === $.ui.keyCode.TAB && $( this ).data( \"autocomplete\" ).menu.active ) {\n event.preventDefault();\n }\n\n if(event.keyCode === $.ui.keyCode.COMMA) {\n this.value = this.value+\" \";\n }\n\n $(this).autocomplete({\n source: function( request, response ) {\n $.getJSON( \"/productsearch/\" + extractLast( request.term.toLowerCase() ) + \".json\", response );\n },\n search: function() {\n // custom minLength\n },\n focus: function() {\n // prevent value inserted on focus\n return false;\n },\n select: function( event, ui ) {\n this.value = ui.item.value;\n $(\"#productNodeId\").val(ui.item.id);\n return false;\n }\n });\n });\n}", "function handleSearch() {\n triggerSearch({}); // need empty braces here\n }", "function AutoComplete_KeyDown(id) {\r\n \r\n \r\n var searchField = document.getElementById(id);\r\n if (searchField != null && searchField.value != '') \r\n {\r\n\r\n // Mozilla\r\n if (arguments[1] != null) {\r\n event = arguments[1];\r\n }\r\n\r\n var keyCode = event.keyCode;\r\n \r\n switch (keyCode) {\r\n\r\n // Return/Enter\r\n case 13:\r\n if (__AutoComplete[id]['highlighted'] != null) {\r\n AutoComplete_SetValue(id);\r\n AutoComplete_HideDropdown(id);\r\n }\r\n \r\n event.returnValue = false;\r\n event.cancelBubble = true;\r\n submit_form(id);\r\n break;\r\n\r\n // Escape\r\n case 27:\r\n if (__AutoComplete[id]['isVisible']) {\r\n __AutoComplete[id]['element'].value = user_typed_query;\r\n }\r\n AutoComplete_HideDropdown(id);\r\n event.returnValue = false;\r\n event.cancelBubble = true;\r\n break;\r\n \r\n // Up arrow\r\n case 38:\r\n if (!__AutoComplete[id]['isVisible']) {\r\n user_typed_query = __AutoComplete[id]['element'].value;\r\n if (__AutoComplete[id]['term_at_close'] != \"\") {\r\n __AutoComplete[id]['term_at_close']=\"\";\r\n AutoComplete_ShowDropdown(id);\r\n return;\r\n }\r\n else {\r\n AutoComplete_ShowDropdown(id);\r\n } \r\n }\r\n AutoComplete_Highlight(id, -1);\r\n AutoComplete_SetValue(id);\r\n AutoComplete_ScrollCheck(id, -1);\r\n return false;\r\n break;\r\n \r\n // Tab\r\n case 9:\r\n if (__AutoComplete[id]['isVisible']) {\r\n AutoComplete_HideDropdown(id);\r\n }\r\n return;\r\n \r\n // Down arrow\r\n case 40:\r\n if (!__AutoComplete[id]['isVisible']) {\r\n user_typed_query = __AutoComplete[id]['element'].value;\r\n if (__AutoComplete[id]['term_at_close'] != \"\") {\r\n __AutoComplete[id]['term_at_close']=\"\";\r\n AutoComplete_ShowDropdown(id);\r\n return;\r\n }\r\n else {\r\n AutoComplete_ShowDropdown(id);\r\n }\r\n }\r\n AutoComplete_Highlight(id, 1);\r\n AutoComplete_SetValue(id);\r\n AutoComplete_ScrollCheck(id, 1);\r\n return false;\r\n break;\r\n }\r\n } \r\n \r\n }", "function navigateToBillerSearch(clearScreen) {\n\tremoveMessageFromDivId();\n\tremoveSuccessOrFailureStrip();\n\thashChangedCalled = true;\n\tmakeActiveTab('footerHomeTab');\n\tbookmarks.sethash('#searchBiller', loadFindBill, clearScreen);\n}", "function emitSearch(event){ if (event.which == 13) {addSearch();}}", "function _mod_search() {\n\t\"use strict\";\n\t// private section - following fields and functions are private and need to be accessed by methods provided in the public section\n\tvar _inputId;\n\tvar autoComplete = {};\n\n\tautoComplete.suggestion = {};\n\tautoComplete.suggestion.tags = [];\n\tautoComplete.suggestion.id = [];\n\tautoComplete.dictionaryTags = [];\n\n\t/****\n\t * create a completely new tag\n\t * @param id of the corresponding html list element\n\t * @param tag to be linked to the id\n\t * @return {Object}\n\t */\n\tfunction newIdTagPair(id, tag) {\n\t\tvar liElem = {};\n\t\tliElem.id = id;\n\t\tliElem.tags = [];\n\t\tliElem.tags.push(tag);\n\t\treturn liElem;\n\t}\n\n\t/****\n\t * filters a list while typing text into an input field and hides all\n\t * list items that don't match to the search string.\n\t * @param searchStr string that is currently in the search field (others would be possible to, but mostly senseless)\n\t * @param listRootId list to be filterd\n\t */\n\tfunction searchFilter(searchStr, listRootId) {\n\t\tvar match;\n\t\tvar searchIndex;\n\t\tvar i, j;\n\t\tvar nodeJQ;\n\t\tvar visibleNodes = [];\n\n\t\t// show all\n\t\tif (!searchStr || searchStr === \"\") {\n\t\t\tjQuery(\"#\" + listRootId).find(\"li\").andSelf().show();\n\t\t}\n\n\t\tsearchStr = searchStr.toLowerCase();\n\n\n\t\t// hide all nodes while traversing\n\t\t// not to nice implemented ;)\n\t\tfor (i = autoComplete.dictionaryTags.length - 1; i >= 0; i--) {\n\t\t\tnodeJQ = jQuery(\"#\" + autoComplete.dictionaryTags[i].id);\n\t\t\t//console.log(autoComplete.dictionaryTags[i].tags[0])\n\t\t\tmatch = null;\n\t\t\tfor (j = 0; j < autoComplete.dictionaryTags[i].tags.length; j++) {\n\t\t\t\tsearchIndex = autoComplete.dictionaryTags[i].tags[j].toLowerCase().match(searchStr);\n\t\t\t\tif (searchIndex) {\n\t\t\t\t\tmatch = nodeJQ;\n\t\t\t\t\t//select node in tree to highlight\n\t\t\t\t\tif (searchIndex === 0 && autoComplete.dictionaryTags[i].tags[j].length === searchStr.length) {\n\t\t\t\t\t\tMYAPP.tree.select_node(jQuery(\"#\" + autoComplete.dictionaryTags[i].id));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnodeJQ.hide();\n\n\t\t\tif (match) {\n\t\t\t\tvisibleNodes.push(match);\n\t\t\t}\n\t\t}\n\n\t\t// show matching nodes and all their parents\n\t\t// !!! todo: the method parents gos up to the html root but it should stop at the top of the list\n\t\tfor (i = visibleNodes.length - 1; i >= 0; i--) {\n\t\t\tvisibleNodes[i].parents(\"#treeList li\").andSelf().show();\n\t\t}\n\t}\n\n\t// private section END\n\n\n\t// public section\n\t// all methods that give access to the private fields and allow to process the menu\n\treturn {\n\t\t/****\n\t\t * @param treeRootId\n\t\t * id of the root of the list that should be filtered\n\t\t * @param inputId\n\t\t * id of the input field in witch should get the autocompleate function\n\t\t * @param dictionaryTags\n\t\t * an array that looks as followed:\n\t\t * [ { id: ... , tags: [..., ...]}, { id: ... , tags: [..., ...]} ]\n\t\t * the id is the id of the li element that should be processed,\n\t\t * the tag is an array with corresponding strings (if the search string matches\n\t\t * any of the tag string or tag substring in any position the li element is displayed.\n\t\t * if there is no match at all the li element will be hidden.\n\t\t *\n\t\t */\n\t\tinitSearch : function (treeRootId, inputId, dictionaryTags) {\n\t\t\tvar i, j;\n\n\t\t\tdictionaryTags = dictionaryTags || [];\n\t\t\t_inputId = inputId;\n\t\t\tautoComplete.dictionaryTags = dictionaryTags;\n\n\t\t\tfor (i = 0; i < dictionaryTags.length; i++) {\n\t\t\t\tfor (j = 0; j < dictionaryTags[i].tags.length; j++) {\n\t\t\t\t\tautoComplete.suggestion.tags.push(dictionaryTags[i].tags[j]);\n\t\t\t\t\tautoComplete.suggestion.id.push(dictionaryTags[i].id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjQuery(\"#\" + inputId).autocomplete({\n\t\t\t\tsource : autoComplete.suggestion.tags,\n\t\t\t\tselect : function (event, ui) {\n\t\t\t\t\tif (ui.item) {\n\t\t\t\t\t\tvar i = jQuery.inArray(ui.item.value, autoComplete.suggestion.tags);\n\t\t\t\t\t\tvar node = jQuery(\"#\" + autoComplete.suggestion.id[i]);\n\t\t\t\t\t\tMYAPP.tree.select_node(node);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Dieses Element ist im Objekt nicht enthalten.\");\n\t\t\t\t\t}\n\t\t\t\t\t//alert(ui.item ? ui.item.value: \"Nothing selected, input was \" + this.value );\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tjQuery(\"#\" + inputId).keyup(function () {\n\t\t\t\t//alert(\"\")\n\t\t\t\tsearchFilter(jQuery(\"#\" + inputId).val(), treeRootId);\n\t\t\t});\n\t\t\t// filter when x is pressed\n\t\t\tjQuery(\"#\" + inputId).parent().children(\".ui-input-clear\").mouseup(function () {\n\t\t\t\tsearchFilter(\"\", treeRootId);\n\t\t\t});\n\n\t\t},\n\t\t/****\n\t\t * push a new tag to the data set that is used to filter the html list\n\t\t * and to the data set that is the base for the autoComplete suggestions\n\t\t * @param id of the corresponding list element\n\t\t * @param tag that is being linked to the tag\n\t\t */\n\t\tpushTag : function (id, tag) {\n\t\t\tvar i;\n\t\t\tvar index = -1;\n\n\t\t\t//console.log(\" id \" + id + \" tag \" + tag + \" _inputId \" + _inputId)\n\t\t\tif (typeof id !== \"string\" || typeof tag !== \"string\") {\n\t\t\t\tconsole.error(\"data to push are not valid (mod_search->method pushTag(id, tag)\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (i = 0; i < autoComplete.dictionaryTags.length; i++) {\n\t\t\t\tif (autoComplete.dictionaryTags[i].id.match(id)) {\n\t\t\t\t\tindex = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (-1 < index) { // element with the submitted id already exists\n\t\t\t\tautoComplete.dictionaryTags[index].tags.push(tag);\n\t\t\t\t/*\n\t\t\t\t console.log(\n\t\t\t\t autoComplete.dictionaryTags[index].id[0] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].tags[0] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].id[1] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].tags[1]\n\t\t\t\t )\n\t\t\t\t */\n\t\t\t}\n\t\t\telse { // create new entry\n\t\t\t\tautoComplete.dictionaryTags.push(newIdTagPair(id, tag));\n\t\t\t\t//console.log(newIdTagPair(id, tag).id + \" --- \" + autoComplete.dictionaryTags[testI].id + \" --- \" + autoComplete.dictionaryTags[testI].tags[0] )\n\t\t\t}\n\n\t\t\tautoComplete.suggestion.tags.push(tag);\n\t\t\tautoComplete.suggestion.id.push(id);\n\n\t\t\t//console.log( autoComplete.suggestion.id[testI] + \" --- \" + autoComplete.suggestion.tags[testI] ) ;\n\t\t\t//console.log( id + \" --- \" + tag ) ;\n\n\t\t\tjQuery(\"#\" + _inputId).autocomplete('option', 'source', autoComplete.suggestion.tags);\n\t\t}\n\t};\n\t// public section END (return end)\n}", "function expandHistory(searchCity) {\n let duplicate = false;\n for (let i = 0; i < searchHistory.length; i++) {\n if (searchCity == searchHistory[i]) {\n duplicate = true;\n }\n }\n if (!duplicate) {\n searchHistory.push(searchCity);\n localStorage.setItem('cities', JSON.stringify(searchHistory));\n initializeButtons();\n }\n}", "function search(config) {\n var settings = config.settings,\n filters = config.filters;\n\n historyView.displayThrobber();\n\n EHistory.search({\n text: settings.text || '',\n startTime: new Date(settings.startTime || 0).getTime() ,\n endTime: new Date(settings.endTime || Date.now()).getTime(),\n maxResults: historyModel.pageSize\n }, filters, function(results){\n historyModel.append(results);\n });\n }", "requestNewSuggestions () {\n let delay = atom.config.get('autocomplete-plus.autoActivationDelay')\n\n if (this.delayTimeout != null) {\n clearTimeout(this.delayTimeout)\n }\n\n if (delay) {\n this.delayTimeout = setTimeout(this.findSuggestions, delay)\n } else {\n this.findSuggestions()\n }\n\n this.shouldDisplaySuggestions = true\n }", "function loadLatestSearch() {\n\n var latestTerms = pullLatestSearches();\n\n var recentlySearched = latestTerms[0];\n\n searchHandler(recentlySearched);\n}", "autocomplete () {\n const input = $('input[data-role=fork-search-field][data-autocomplete=enabled]')\n const searchEngine = this.getSuggestionEngine('Autocomplete')\n\n // autocomplete (based on saved search terms) on results page\n // Init the typeahead search\n input.typeahead(null, {\n name: 'search',\n display: 'value',\n hint: false,\n limit: 5,\n source: searchEngine,\n templates: {\n suggestion (data) {\n return '<a><strong>' + data.value + '</strong></a>'\n }\n }\n }).bind('typeahead:select', function (ev, suggestion) {\n window.location.href = suggestion.url\n })\n\n // when we have been typing in the search textfield and we blur out of it, we're ready to save it\n input.on('blur', (e) => {\n if ($(e.currentTarget).val() !== '') {\n // ajax call!\n $.ajax({\n data: {\n fork: {module: 'Search', action: 'Save'},\n term: $(e.currentTarget).val()\n }\n })\n }\n })\n }", "function autocompleteSearch(searchString) {\n rawString = convertToRawString(searchString);\n autoOptions = trie.getWords(rawString, 5);\n var options = '';\n for(var i = 0; i < autoOptions.length; i++) {\n option = tagsDict[autoOptions[i]]\n options += '<option value=\"'+option+'\" />';\n }\n \n document.getElementById('search-autocomplete').innerHTML = options;\n}", "function searchSuggest() {\n if ($('.search-results').length < 1) return;\n\n var delay = (function () {\n var timer = 0;\n return function (callback, ms) {\n window.clearTimeout(timer);\n timer = window.setTimeout(callback, ms);\n };\n }());\n\n // append the view all button\n $('<a class=\"view-all\">Bekijk alle <span></span> resultaten</a>').insertAfter('#synoniemenlijst');\n $('a.view-all').click(function (e)\n { $('header .search input[type=\"submit\"]').trigger('click'); });\n\n var controlkeys = [16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 91, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 144, 145];\n\n var currentSearchField = null;\n\n var search_success = function (data) {\n results = currentSearchField.closest(\"div\").siblings(\".search-results\");\n\n var synonyms = results.find(\"#synoniemenlijst\"),\n elsToToggle = $('.search-results, #synoniemenlijst, a.view-all');\n synonyms.empty().removeAttr('style');\n\n if (data && data.Hits.length > 0) {\n $($.map(data.Hits, function (el) {\n return $('<a />', { href: el.Url[0].replace(/~/g, '') + '?bron=autosuggest&searchtext=' + $('.searchinput').val(), text: el.Fields.Title }).get(0);\n })).appendTo(synonyms);\n elsToToggle.show();\n\n // hide the mega drop down menu\n $('ul.courses').removeClass('toggled');\n\n // update total count in the btn\n $('a.view-all span').html(data.Total);\n\n // enable navigation by keyboard\n var numLinks = $('#synoniemenlijst a').length,\n curLink = -1;\n\n $(document).keydown(function (e) {\n // arrow down\n if (e.keyCode == 40) {\n e.preventDefault();\n curLink++;\n if (curLink == numLinks) curLink = 0;\n $('#synoniemenlijst a').eq(curLink).focus();\n\n }\n // arrow up\n if (e.keyCode == 38) {\n e.preventDefault();\n if (curLink == 0) curLink = numLinks;\n curLink--;\n $('#synoniemenlijst a').eq(curLink).focus();\n\n }\n });\n }\n else {\n elsToToggle.hide();\n }\n };\n\n var search_fail = function (error) {\n if (console && console.error) {\n console.error(error.get_message());\n }\n };\n\n $(\".searchinput, .elasticSearchInput\").keyup(function (e) {\n currentSearchField = $(this);\n var input = this;\n if (e.keyCode === 13) {\n //execute search\n }\n else if (input.value && $.inArray(e.keyCode, controlkeys) === -1) {\n delay(function () {\n WebService.ElasticSearch(input.value, 1, '', 5, 'NCOI', 'opleidingen', search_success, search_fail);\n }, 0);\n }\n });\n\n // if user clicks within search suggestions, prevent close function from being triggered\n $('.search-results').click(function (e) { e.stopPropagation(); })\n // user has pressed escape\n $(document).keydown(function (e) { if (e.keyCode == 27) $('.search-results').fadeOut('fast'); });\n // user has clicked outside of search suggestions or on close btn\n $('.search-results a.close, body').click(function (e) { $('.search-results').fadeOut('fast'); });\n}", "onFocus() {\n this.biasAutocompleteLocation();\n this.$emit('focus');\n }", "function addToSearchHistory() {\n searchedCities.empty();\n for (let i = 0; i < previousCities.length; i++) {\n let cityNames = previousCities[i];\n\n let liElement = $(\"<li>\");\n liElement.text(cityNames);\n liElement.attr(\"class\", \"previous-city\");\n\n searchedCities.append(liElement);\n }\n}", "function bindSearchBoxKeyupEvents() {\n searchBox.keyup(function(e) {\n var highlightedLink = $('.search-results .is-opened li span.highlight'),\n url, trigger, searchType, linkURL,\n searchWindow, searchBoxValueFromSuggestions,\n suggestionLinkSpanSelector = $('.search-results span'),\n suggestionOpenSpansSelector = $('.search-results .is-opened li span');\n\n if (e.keyCode == 13) {\n /*Search changes*/\n searchBoxValueFromSuggestions = highlightedLink.text();\n trigger = (searchBoxValueFromSuggestions === searchBox.val()) ? SN.Constant.GTM_SEARCH_EVENT_SUGGESTIONS :\n\n SN.Constant.GTM_SEARCH_EVENT__KEYPRESS;\n searchType = $(\".search-options .is-opened a\").attr('href').split('-')[1];\n linkURL = $('.search-results .is-opened li span.highlight').closest('ul').attr('id');\n search(searchBox.val(), trigger, searchType, linkURL);\n\n }\n /*Search changes*/\n if (e.keyCode == '40') {\n if (highlightedLink.length === 1 && highlightedLink.parents('li').next().length > 0) {\n suggestionLinkSpanSelector.removeClass('highlight');\n highlightedLink.parents('li').next().find('span').addClass('highlight');\n } else if (highlightedLink.length === 1 && highlightedLink.parents('ul').next('ul.is-opened').length ===\n\n 1) {\n suggestionLinkSpanSelector.removeClass('highlight');\n highlightedLink.parents('ul').next('ul.is-opened').find('span').first().addClass('highlight');\n } else {\n suggestionLinkSpanSelector.removeClass('highlight');\n suggestionOpenSpansSelector.first().addClass('highlight');\n }\n } else if (e.keyCode == '38') {\n if (highlightedLink.length === 1 && highlightedLink.parents('li').prev('li').length > 0) {\n suggestionLinkSpanSelector.removeClass('highlight');\n highlightedLink.parents('li').prev().find('span').addClass('highlight');\n } else if (highlightedLink.length === 1 && highlightedLink.parents('ul').prev('ul.is-opened').length ===\n\n 1) {\n suggestionLinkSpanSelector.removeClass('highlight');\n highlightedLink.parents('ul').prev('ul.is-opened').find('span').last().addClass('highlight');\n } else {\n suggestionLinkSpanSelector.removeClass('highlight');\n suggestionOpenSpansSelector.last().addClass('highlight');\n }\n } else {\n if (searchBox.val().length < SN.Global.Settings.suggestionsMinChar) {\n $('.search-results ul').html('').removeClass('is-opened');\n } else {\n clearTimeout(timeoutId); // doesn't matter if it's 0\n timeoutId = setTimeout(bindSearchSuggestions, 200);\n }\n }\n if (e.keyCode == '40' || e.keyCode == '38') {\n highlightedLink = $('.search-results .is-opened li span.highlight');\n if (highlightedLink.length === 1) {\n searchBox.val(highlightedLink.text());\n }\n }\n });\n }", "function searchthis(e){\n $.search.value = \"keyword to search\";\n $.search.blur();\n focused = false;\n needclear = true;\n}", "autoComplete () {\n var that = this;\n var autocompleteOn = true;\n GEPPETTO.CommandController.availableTags();\n\n var commandInputAreaEl = $(\"#\" + this.props.id + \"_component #commandInputArea\");\n // bind console input area to autocomplete event\n commandInputAreaEl.bind(\"keydown\", function (event) {\n if (event.keyCode === $.ui.keyCode.TAB\n && $(this).data(\"ui-autocomplete\").menu.active) {\n event.preventDefault();\n }\n if (event.keyCode === $.ui.keyCode.BACKSPACE) {\n autocompleteOn = false;\n }\n })\n .autocomplete({\n minLength: 0,\n delay: 0,\n source: that.matches.bind(that),\n focus: function () {\n // prevent value inserted on focus\n return false;\n },\n open: function (event, ui) {\n if (autocompleteOn) {\n var suggestions = $(this).data(\"uiAutocomplete\").menu.element[0].children\n , firstElement = suggestions[0]\n , inpt = commandInputAreaEl\n , original = inpt.val()\n , firstElementText = $(firstElement).text()\n , suggestionsSize = suggestions.length;\n /*\n * here we want to make sure that we're not matching something that doesn't start\n * with what was typed in\n */\n if (firstElementText.toLowerCase().indexOf(original.toLowerCase()) === 0) {\n\n // only one suggestion\n if (suggestionsSize == 1) {\n if (inpt.val() !== firstElementText) {\n inpt.val(firstElementText); // change the input to the first match\n\n inpt[0].selectionStart = original.length; // highlight from beginning of input\n inpt[0].selectionEnd = firstElementText.length;// highlight to the end\n }\n } else {\n // match multiple suggestions\n if (inpt.val() !== \"\") {\n let mostCommon;\n var elementsText = [];\n for (var i = 0; i < suggestionsSize; i++) {\n elementsText[i] = $(suggestions[i]).text();\n }\n var A = elementsText.slice(0).sort(),\n word1 = A[0], word2 = A[A.length - 1],\n i = 0;\n if (word1 != word2) {\n while (word1.charAt(i) == word2.charAt(i)){\n ++i;\n }\n // match up most common part\n mostCommon = word1.substring(0, i);\n } else {\n mostCommon = word1;\n }\n\n if (inpt.val().indexOf(mostCommon) == -1) {\n inpt.val(mostCommon);// change the input to the first match\n\n inpt[0].selectionStart = original.length; // highlight from end of input\n inpt[0].selectionEnd = mostCommon.length;// highlight to the end\n }\n }\n }\n }\n } else {\n autocompleteOn = true;\n }\n }\n });\n }", "function liveSearchBar(str)\n{\n ajax.process('GET', 'Models/livesearch.php?q=' + str, handleResponse);\n console.log(ajax);\n previousSearchQuery = str;\n}", "function bindKeydownSearches() {\n\n var $search,\n searchTerm,\n searchLength,\n predictiveSearchTerms,\n predictiveSearchLinks,\n appendedTerms,\n appendedLinks,\n searchType,\n predictiveListCount = 0,\n prevSearchHadResults,\n currentIndex = -1,\n touch = $('html').hasClass('touch');\n\n //Do not allow the cursor to move to the front of the search on\n //up arrow key\n $('.search').on('keydown', function(e) {\n if (e.keyCode === 38) {\n return false;\n }\n });\n\n $('.search').on('keyup', function(e) {\n\n e.preventDefault();\n\n $search = $(this);\n searchTerm = $search.val().toLowerCase();\n searchLength = searchTerm.length;\n\n /**\n * Type of search situations\n * Large\n * Small\n * Large but on touch device (force mobile)\n * Search page (mobile)\n */\n searchType = $search.attr(\"id\") === \"search-page-search\" ? \"search\" :\n touch ? 'small' : window.innerWidth >= 960 ? \"large\" : \"small\";\n\n if (searchLength < 2) {\n predictiveContainer[searchType].hide();\n return true;\n }\n\n if (searchLength === 2 && Search.models.indexOf(searchTerm) === -1) {\n predictiveContainer[searchType].hide();\n return true;\n }\n\n //If last search yielded results AND up/down key pressed:\n if (/(large|search)/.test(searchType) && prevSearchHadResults && (e.keyCode === 38 || e.keyCode === 40)) {\n\n //We made it into the scrolling of predictive terms, is this our first time?\n predictiveListCount = predictiveListCount === 0 ? document.querySelectorAll(\"#predictive-terms-\" + searchType + \" li\").length : predictiveListCount;\n\n //We know our index and how many items we have now, let's move\n switch (e.keyCode) {\n case 38:\n currentIndex = arrowKeyPressed(currentIndex, predictiveListCount, -1, searchType);\n break;\n case 40:\n currentIndex = arrowKeyPressed(currentIndex, predictiveListCount, 1, searchType);\n break;\n default:\n console.log(\"Funky-ness.\");\n }\n\n return true;\n }\n\n //If we get to this point we can make an ajax call, because of scope i should have\n //variables available\n hydrateObjectFromJSON('terms', '/rest/suggest?q=' + searchTerm, function() {\n\n hydrateObjectFromJSON('links', '/rest/shortcuts?q=' + searchTerm, function() {\n currentIndex = -1;\n predictiveListCount = 0;\n\n html = '';\n\n predictiveSearchTerms = getPredictiveSearchTerms();\n predictiveSearchLinks = Search.links[0] || null;\n\n appendedTerms = appendTermsToList(predictiveSearchTerms, searchTerm, searchType);\n appendedLinks = appendDestinationToList(predictiveSearchLinks, searchType);\n\n if (appendedTerms || appendedLinks) {\n //Show the dropdown\n prevSearchHadResults = true; //This lets us know if we need to listen to up and down arrows in the future\n predictiveTermsContainer[searchType].html(html); //The html variable is a high level variable that is injected once instead of being passed around\n predictiveContainer[searchType].show();\n } else {\n //Hide the dropdown\n prevSearchHadResults = false;\n predictiveContainer[searchType].hide();\n }\n });\n });\n });\n }", "function autocomplete(that,searchBar) {\n\tid_autocomplete = that.id;\n\tfocusedBar.value = id_autocomplete;\n}", "updateRecents() {\n if (this['searchTerm']) {\n const enabledIds = this.searchManager.getEnabledSearches().map(osSearch.getSearchId).sort();\n\n const recentIndex = olArray.findIndex(this['recentSearches'], function(recent) {\n return recent.term == this['searchTerm'];\n }.bind(this));\n\n if (recentIndex > -1) {\n // already in the array, so move it to the top\n googArray.moveItem(this['recentSearches'], recentIndex, 0);\n } else {\n const recent = /** @type {!osx.search.RecentSearch} */ ({\n ids: enabledIds,\n term: this['searchTerm']\n });\n\n this['recentSearches'].unshift(recent);\n\n if (this['recentSearches'].length > Controller.MAX_RECENT_) {\n this['recentSearches'].length = Controller.MAX_RECENT_;\n }\n }\n\n this.saveRecent_();\n }\n }", "function searchUpdated(term) {\n setsearch(term);\n }", "function oneSearchResult() {\n\toFocus = true;\n\t$.cookie('last_tab', '#account');\n}", "renderSearch() {\n return <Autocomplete\n onPlaceSelected={ (place) => {\n this.props.receiveSearch(place.formatted_address);\n hashHistory.push(`/restaurants/index/${place.formatted_address}`);\n }}\n placeholder={'Enter a Location'}\n types={['address']}\n id='nav-auto' />;\n }", "function autocomplete(inp, arr) {\n var currentFocus;\n inp.addEventListener(\"input\", function(e) {\n var a, b, i, val = this.value;\n closeAllLists();\n if (!val) { return false;}\n currentFocus = -1;\n a = document.createElement(\"DIV\");\n a.setAttribute(\"id\", this.id + \"autocomplete-list\");\n a.setAttribute(\"class\", \"autocomplete-items\");\n this.parentNode.appendChild(a);\n for (i = 0; i < arr.length; i++) {\n if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {\n b = document.createElement(\"DIV\");\n b.innerHTML = \"<strong>\" + arr[i].substr(0, val.length) + \"</strong>\";\n b.innerHTML += arr[i].substr(val.length);\n b.innerHTML += \"<input type='hidden' value='\" + arr[i] + \"'>\";\n b.addEventListener(\"click\", function(e) {\n inp.value = this.getElementsByTagName(\"input\")[0].value;\n closeAllLists();\n });\n a.appendChild(b);\n }\n }\n });\n inp.addEventListener(\"keydown\", function(e) {\n var x = document.getElementById(this.id + \"autocomplete-list\");\n if (x) x = x.getElementsByTagName(\"div\");\n if (e.keyCode == 40) {\n currentFocus++;\n addActive(x);\n } else if (e.keyCode == 38) {\n currentFocus--;\n addActive(x);\n } else if (e.keyCode == 13) {\n e.preventDefault();\n if (currentFocus > -1) {\n if (x) x[currentFocus].click();\n }\n }\n });\n function addActive(x) {\n if (!x) return false;\n removeActive(x);\n if (currentFocus >= x.length) currentFocus = 0;\n if (currentFocus < 0) currentFocus = (x.length - 1);\n x[currentFocus].classList.add(\"autocomplete-active\");\n }\n function removeActive(x) {\n for (var i = 0; i < x.length; i++) {\n x[i].classList.remove(\"autocomplete-active\");\n }\n }\n function closeAllLists(elmnt) {\n var x = document.getElementsByClassName(\"autocomplete-items\");\n for (var i = 0; i < x.length; i++) {\n if (elmnt != x[i] && elmnt != inp) {\n x[i].parentNode.removeChild(x[i]);\n }\n }\n }\n document.addEventListener(\"click\", function (e) {\n closeAllLists(e.target);\n });\n }", "function redirectSearches(){\r\n\t\r\n\tvar searchList = getUrlParameter(\"search\");\r\n\tvar eventAddress = getUrlParameter(\"event\");\r\n\tvar isManual = getUrlParameter(\"manual\");\r\n\t\r\n\t\r\n\t//Nearby Search\r\n\tif (searchList != undefined && eventAddress == undefined){\r\n\t\tsearchMap(searchList,false);\r\n\t}\r\n\t\r\n\t//Address Search\r\n\tif (searchList != undefined && searchList != \"None Given\" && eventAddress == \"true\"){\r\n\t\tsearchMap(searchList,true);\r\n\t}\r\n\t\r\n\t//Manual Lists\r\n\tif (searchList != undefined && eventAddress == undefined && isManual ==\"true\"){\r\n\t\tgetList(searchList);\r\n\t}\r\n\t\r\n\t//Load Address Book\r\n\t//loadAddressList(); Thynote: on click for tab now \r\n}", "function setQuery(evt) {\n if (evt.keyCode == 13) {\n getResults(searchBox.value);\n }\n}", "function init() {\n\n loadLatestSearch();\n\n displayLatestSearches();\n\n searchHandler();\n\n $('#submitBtn').on(\"click\", () => {\n saveSearchTerm($('#search').val().toUpperCase()); \n searchHandler($('#search').val());\n })\n}", "function searchEventListener() {\n\t$(\"#searchbtn\").click(function() {\n\t\tif ($(\"#searchbox\").val() != '') {\n\t\t\tsearchNewspapers($(\"#searchbox\").val());\n\t\t}\n\t});\n}", "function setQuery() {\n getSearch(search.value);\n}", "function updateSearch () {\n // Triggered by timeout (or Enter key), so now clear the id\n inputTimeout = null;\n\n // Get search string\n let value = SearchTextInput.value;\n\n // Do not trigger any search if the input box is empty\n // Can happen in rare cases where we would hit the cancel button, and updateSearch() is dispatched\n // before the event dispatch to manageSearchTextHandler() and so before it could clear the timeout.\n if (value.length > 0) { // Launch search only if there is something to search for\n\t// Activate search mode and Cancel search button if not already\n\tif (sboxState != SBoxExecuted) {\n\t enableCancelSearch();\n\t}\n\t// Update search history list\n\tupdateSearchList(value);\n\n\t// Discard previous results table if there is one\n\tif (resultsTable != null) {\n\t SearchResult.removeChild(resultsTable);\n\t resultsTable = null;\n\t curResultRowList = {};\n//\t resultsFragment = null;\n\n\t // If a row cell was highlighted, do not highlight it anymore\n//\t clearCellHighlight(rcursor, rlastSelOp, rselection.selectIds);\n\t cancelCursorSelection(rcursor, rselection);\n\t}\n\n\t// Display waiting for results icon\n\tWaitingSearch.hidden = false;\n\n\t// Look for bookmarks matching the search text in their contents (title, url .. etc ..)\n\tlet searching;\n\tif (!options.noffapisearch\n\t\t&& (options.searchField == \"both\") && (options.searchScope == \"all\") && (options.searchMatch == \"words\")) {\n//console.log(\"Using FF Search API\");\n\t // It seems that parameters can make the search API fail and return 0 results sometimes, so strip them out,\n\t // there will be too much result maybe, but at least some results !\n\t let simpleUrl;\n\t let paramsPos = value.indexOf(\"?\");\n\t if (paramsPos >= 0) {\n\t\tsimpleUrl = value.slice(0, paramsPos);\n\t }\n\t else {\n\t\tsimpleUrl = value;\n\t }\n\t searching = browser.bookmarks.search(decodeURI(simpleUrl));\n\t}\n\telse {\n//console.log(\"Using BSP2 internal search algorithm\");\n\t searching = new Promise ( // Do it asynchronously as that can take time ...\n\t\t(resolve) => {\n\t\t let a_matchStr;\n\t\t let matchRegExp;\n\t\t let isRegExp, isTitleSearch, isUrlSearch;\n\t\t let a_BN;\n\n\t\t if (options.searchField == \"both\") {\n\t\t\tisTitleSearch = isUrlSearch = true;\n\t\t }\n\t\t else if (options.searchField == \"title\") {\n\t\t\tisTitleSearch = true;\n\t\t\tisUrlSearch = false;\n\t\t }\n\t\t else {\n\t\t\tisTitleSearch = false; \n\t\t\tisUrlSearch = true;\n\t\t }\n\n\t\t if (options.searchMatch == \"words\") { // Build array of words to match\n\t\t\tisRegExp = false;\n\t\t\ta_matchStr = strLowerNormalize(value).split(\" \"); // Ignore case and diacritics\n\t\t }\n\t\t else {\n\t\t\tisRegExp = true;\n\t\t\ttry {\n\t\t\t matchRegExp = new RegExp (strNormalize(value), \"i\"); // Ignore case and diacritics\n\t\t\t}\n\t\t\tcatch (e) { // If malformed regexp, do not continue, match nothing\n\t\t\t a_BN = [];\n\t\t\t}\n\t\t }\n\n\t\t if (a_BN == undefined) { // No error detected, execute search\n\t\t\tif (options.searchScope == \"all\") { // Use the List form\n\t\t\t a_BN = searchCurBNList(a_matchStr, matchRegExp, isRegExp, isTitleSearch, isUrlSearch);\n\t\t\t}\n\t\t\telse { // Use the recursive form\n\t\t\t let BN;\n\t\t\t if (cursor.cell == null) { // Start from Root\n\t\t\t\tBN = rootBN;\n\t\t\t }\n\t\t\t else { // Retrieve BN of cell in cursor\n\t\t\t\tBN = curBNList[cursor.bnId];\n\t\t\t\t// Protection\n\t\t\t\tif (BN == undefined) {\n\t\t\t\t BN = rootBN;\n\t\t\t\t}\n\t\t\t }\n\t\t\t a_BN = searchBNRecur(BN, a_matchStr, matchRegExp, isRegExp, isTitleSearch, isUrlSearch,\n\t\t\t\t\t\t\t\t (options.searchScope == \"subfolder\") // Go down to subfolders, or only current folder ?\n\t\t\t\t\t\t\t\t );\n\t\t\t}\n\t\t }\n\n\t\t resolve(a_BN);\n\t\t}\n\t );\n\t}\n\tsearching.then(\n\t function (a_BTN) { // An array of BookmarkTreeNode or of BookmarkNode (a poor man's kind of \"polymorphism\" in Javascript ..)\n\t\t// Create the search results table only if a search is still active.\n\t\t// Can happen when browser.bookmarks.search() is very long, like higher than InputKeyDelay,\n\t\t// and we have cleared the input box / cancelled the search in between.\n\t\tif (SearchTextInput.value.length > 0) { // Display results only if there is something to search for\n\t\t displayResults(a_BTN);\n\t\t}\n\t }\n\t);\n }\n}", "function addSearchListeners() {\n searchInput.addEventListener(\"keyup\", function(event) {\n const k = event.keyCode; // ignore arrow keys\n if (k > 36 && k < 41) return;\n suggestionModule.displayMatches();\n });\n\n searchInput.addEventListener(\"focus\", suggestionModule.displayMatches);\n\n document.addEventListener(\n \"click\",\n function() {\n if (\n !(event.target === searchInput || suggestions.contains(event.target))\n )\n removeChildren(suggestions);\n },\n true\n );\n }", "function setDropdown() {\n\n searchBar.autocomplete({\n source: availableTags, \n response: function(_, ui) {\n dropdownResponse = ui.content;\n }\n\n });\n searchBar.on(\"autocompletesearch\", function(_, ui){\n\n })\n }", "function AutoComplete_Create (id, url) {\r\n if (document.getElementById(id) == null) { return; }\r\n //this will remove the onchange of the search textbox because the form was causing a postback\r\n document.getElementById(id).onchange = function(e) { return false; }\r\n __AutoComplete[id] = { 'url': url,\r\n 'isVisible': false,\r\n 'element': document.getElementById(id),\r\n 'dropdown': null,\r\n 'highlighted': null,\r\n 'close': null,\r\n 'term_at_close': \"\"\r\n };\r\n\r\n __AutoComplete[id]['element'].setAttribute('autocomplete', 'off');\r\n __AutoComplete[id]['element'].onkeydown = function(e) { return AutoComplete_KeyDown(this.getAttribute('id'), e); }\r\n __AutoComplete[id]['element'].onkeyup = function(e) { return AutoComplete_KeyUp(this.getAttribute('id'), e); }\r\n __AutoComplete[id]['element'].onkeypress = function(e) { if (!e) e = window.event; if (e.keyCode == 13 || isOpera) return false; }\r\n __AutoComplete[id]['element'].ondblclick = function(e) { return AutoComplete_DoubleClick(this.getAttribute('id'), e); }\r\n __AutoComplete[id]['element'].onclick = function(e) { if (!e) e = window.event; e.cancelBubble = true; e.returnValue = false; }\r\n\r\n if (document.addEventListener) {\r\n document.addEventListener('click', CloseSearchPanel, false);\r\n } else if (document.attachEvent) {\r\n document.attachEvent('onclick', CloseSearchPanel, false);\r\n }\r\n\r\n // Max number of items shown at once\r\n if (arguments[2] != null) {\r\n __AutoComplete[id]['maxitems'] = arguments[2];\r\n __AutoComplete[id]['firstItemShowing'] = 1;\r\n __AutoComplete[id]['lastItemShowing'] = arguments[2];\r\n }\r\n\r\n AutoComplete_CreateDropdown(id);\r\n \r\n }", "function searchCocktail() {\n //set searchTerm to what a user typed in\n console.log(searchValue.current.value);\n setSearchTerm(searchValue.current.value);\n }", "function endSearch() {\n MicroModal.show(\"addresses-modal\");\n\n // Remove \"Searching...\" message\n $(\".find-address\").text(\"Find Address\");\n\n $(\".find-address\").prop(\"disabled\", false);\n }", "function setUpAutocomplete() {\n $('#classInput')\n .addClass('ui-autocomplete-input')\n .attr('autocomplete', 'off')\n .autocomplete({\n source: abbrTags\n });\n}", "function onSearchKeyPress(e) {\n switch (e.keyCode) {\n case 38:\n // up arrow\n updateSuggestion(currentSuggestion - 1)\n break\n case 40:\n // down arrow\n updateSuggestion(currentSuggestion + 1)\n break\n case 13:\n // enter. it'll submit the form, but let's unfocus the text box first.\n inputElmt.focus()\n break\n default:\n nextSearch = searchBox.value\n var searchResults = viewer.runSearch(nextSearch, true)\n searchSuggestions.innerHTML = \"\"\n currentSuggestion = -1\n suggestionsCount = 0\n addWordWheelResults(searchResults.front)\n addWordWheelResults(searchResults.rest)\n }\n }", "function runLastSearch() {\n var search = localStorage.getItem(\"lastSearch\")\n\n if (search != \"\" && search != null) {\n beerSearchBar.val(search)\n fetchUrl(search)\n }\n}", "function updateSearchList (text) {\n let options = SearchDatalist.options;\n let len = options.length;\n // Find if text is already in history\n let i;\n let option;\n let value;\n for (i=0 ; i<len ; i++) {\n\tif (text.includes(value = (option = options[i]).value)\n\t\t|| value.includes(text))\n\t break;\n }\n if (i >= len) { // Not found, add it\n\tif (len < SearchListMax) { // Simply append at front\n\t option = document.createElement(\"option\");\n\t option.value = text;\n\t SearchDatalist.prepend(option);\n\t}\n\telse { // Shift values down to make room at top\n\t option = options[SearchListMax-1];\n\t let prev;\n\t for (i=SearchListMax-2 ; i>=0 ; i--) {\n\t\toption.value = (prev = options[i]).value;\n\t\toption = prev;\n\t }\n\t option.value = text;\n\t}\n }\n else { // Found, keep the most specific one\n\tif (text.length > value.length) {\n\t option.value = text;\n\t}\n }\n searchlistTimeoutId = setTimeout(closeSearchList, 3000);\n}", "function recentQuickSearchBackButton_click() {\n var quickSearch = new helm.QuickSearch();\n var restoreSearch = quickSearch.recentSearches.getPrevious.call(quickSearch);\n if (restoreSearch != null) {\n var $QuickSearchTextBox_helm = $(\"#QuickSearchTextBox_helm\");\n\n //Infragistics igniteUI igTextEditor text box displays the recent Quick Search text as faded gray - italic. Fix This here.\n $QuickSearchTextBox_helm.toggleClass(\"ui-igedit-nullvalue\", false); \n \n\n $QuickSearchTextBox_helm.igTextEditor(\"text\", restoreSearch.searchText);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchStateCombo_helm\"), restoreSearch.stateAbbreviation);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchSubStatusCombo_helm\"), restoreSearch.subStatusTypeSkey);\n Compass.Utils.igCombo_SetByValue($(\"#QuickSearchOrgCombo_helm\"), restoreSearch.searchAllOrgs);\n }\n\n \n }", "function searchVisitHistoryAft( responseText ) {\r\n\t//console.log( responseText );\r\n\tif( responseText != NOT_EXIST_DATA ) {\r\n\t\t// Fill searched data.\r\n\t\tviewMetaInfo\t( JSON.parse(responseText).chVisitMeta \t);\r\n\t\tviewVisitHistory( JSON.parse(responseText).chVisit \t\t)\r\n\t} else {\r\n\t\t// There's no data. \r\n\t\tshowComModal( {msg:mLang.get(\"nosearchdata\")} );\r\n\t \treturn false;\t\t\t\t\t\r\n\t}\r\n}", "function displaySearchHistory(){\n $(\"#searchHistory\").empty();\n $.each(cityList, function (index, item){\n \n var listItem = $(\"<li class='list-group-item'>\");\n\n listItem.text(item);\n listItem.attr(\"data-cityname\",item);\n \n $(\"#searchHistory\").prepend(listItem);\n });\n }", "function setupTracking() {\n\t\t\t$('#txt1').focus(function() {\n\t\t\t\tif (this.value == 'keyword'){\n\t\t\t\t\tvar urlresource = window.location.pathname;\n\t\t\t\t\tvar title = $(document).attr(\"title\");\n\t\t\t\t\tvar findchar1 = title.indexOf(\":\");\n\t\t\t\t\tvar findchar2 = title.indexOf(\" - \");\n \n\t\t\t\t\tif (findchar1 != -1) {\n\t\t\t\t\t\tvar category = title.split(': ');\n\t\t\t\t\t\tvar categoryname = category[0];\n\t\t\t\t\t} else if (findchar2 != -1) {\n\t\t\t\t\t\tvar category = title.split(' - ');\n\t\t\t\t\t\tvar categoryname = category[0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar categoryname = title;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ($('body').hasClass('home')) {\n\t\t\t\t\t\tvar labelname = \"Homepage\"; \n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar labelname = categoryname;\n\t\t\t\t\t}\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Search Start\", labelname);\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t$(\"#search-form input[value='Search']\").each(function() {\n\t\t\t\t$(this).click(function() {\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Search Go\", value);\n\t\t\t\t\tsetTimeout($(this).closest(\"form\").submit(), 800);\n\t\t\t\t\t\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t $(\"#searchresults\").each(function() {\n\t\t\t\t$(\"#googleresults a\").live(\"click\", function(){\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Results Click\", value);\n\t\t\t\t\tsetTimeout('document.location = \"' + $(this).attr(\"href\") + '\"', 400);\n\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\n\t\t\t\t$(\"#ldapresults a\").live(\"click\", function(){\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Directory Click\", value);\n\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t$(\"#content div input[type='submit']\").each(function() {\n\t\t\t\t$(this).click(function() {\n\t\t \t\turlresource = window.location.pathname;\n\t\t\t\t\tformval = $(\"input[name='success-redirect']\").attr(\"value\");\n\t\t\t\t\temailval = $(\"input[name='email-recipients']\").attr(\"value\");\n\t\t\t\t\t\n\t\t\t\t\tif (emailval) {\n\t\t\t\t\t\tif (formval) {\n\t\t\t\t\t\t\tcurrentpage = urlresource+'?type=submit&success-redirect='+formval;\n\t \t} else {\n\t\t\t\t\t\t\tcurrentpage = urlresource+'?type=submit&success-redirect=';\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpageTracker._trackPageview(currentpage);\n\t\t\t\t\t\tsetTimeout($(this).closest(\"form\").submit(), 600);\n\n \t return false;\n\t\t\t\t\t} \n\t \t });\n \t });\n\n\t\t\t$(\"#col1 a\").each(function() {\n\t\t\t\t\t\t href = $(this).attr(\"href\");\n\n\t\t\t\t\t\t if (href != null && href != \"\") {\n\t\t\t\t\t\t \n\t\t\t\t\t\t patternhttp = /^https?:\\/\\//i;\n\t\t\t\t\t\t patternwpi = /^https?:\\/\\/.*\\.wpi\\.edu/;\n\t\t\t\t\t\t patternpdf = /pdf$/i;\n\n\t\t\t\t\t\t if (href.match(patternhttp) && !href.match(patternwpi)) {\n\t\t\t\t\t\t\t //click offsite\n\t\t\t\t\t\t\t $(this).click(function() {\n\t\t\t\t\t\t\t\t\t title = $(document).attr(\"title\");\n findchar1 = title.indexOf(\":\");\n findchar2 = title.indexOf(\" - \");\n \n if (findchar1 != -1) {\n category = title.split(': ');\n categoryname = category[0];\n } else if (findchar2 != -1) {\n category = title.split(' - ');\n categoryname = category[0];\n } else {\n categoryname = title;\n }\n\n\t\t\t\t\t\t\t\t\t track_event_to_google(categoryname, \"Offsite Link\", $(this).attr(\"href\"));\n\t\t\t\t\t\t\t\t\t setTimeout('document.location = \"' + $(this).attr(\"href\") + '\"', 400);\n\n\t\t\t\t\t\t\t\t\t return false;\n\t\t\t\t\t\t\t\t });\n\t\t\t\t\t\t } else if (href.match(patternpdf) && href.match(patternwpi)) {\n\t\t\t\t\t\t\t //pdf\n\t\t\t\t\t\t\t $(this).click(function() {\n\t\t\t\t\t\t\t\t\t fullurl = $(this).attr(\"href\");\n\n\t\t\t\t\t\t\t\t\t urlvalue = fullurl.split('/');\n\t\t\t\t\t\t\t\t\t urlvalue1 = urlvalue[0];\n\t\t\t\t\t\t\t\t\t urlvalue2 = '//';\n\t\t\t\t\t\t\t\t\t urlvalue3 = urlvalue[2];\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t url1 = urlvalue1 + urlvalue2 + urlvalue3;\n\t\t\t\t\t\t\t\t\t url2 = fullurl.replace(url1,'')\n\n\t\t\t\t\t\t\t\t\t pageTracker._trackPageview(url2);\n\t\t\t\t\t\t\t\t\t setTimeout('document.location = \"' + fullurl + '\"', 75);\n\n\t\t\t\t\t\t\t\t\t return false;\n\t\t\t\t\t\t\t });\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t});\n\t\t}", "function populateSearch() {\n \n \n var endpoint = localStorage.getItem(\"endpoint\");\n var term = $('#searchProdText').val(); \n if (term.length > 0) {\n \n if (term.startsWith(\"//\")){\n runCommand(term);\n }else{\n var url = \n endpoint + '/search.ashx?q=contains&c=' + term; \n \n $('#prodSearch ul').empty();\n \n $.getJSON(url, function (results) {\n for (i = 0; i < results.length; i++) {\n console.log(JSON.stringify(results[i]));\n addToProdList(results[i]);\n }\n }\n ).fail(function (jqXHR) {\n setStatLabel(\"danger\", \"Un error ocurrió\");\n });\n }\n \n }else{\n setStatLabel(\"warning\", 'Escribe un articulo para buscar');\n }\n \n}", "initAutoComplete() {\n if ($(\"#banner-search-bar\").length) {\n this.initAutoCompleteOn($('#banner-search-bar'));\n }\n this.initAutoCompleteOn($('#header-search-bar'));\n }", "prev(){\n // if is something in search input use search items array\n if (this.searchInput.select) {\n this.page.curSearch--\n this.searchItems()\n // else use discover items array\n } else {\n this.page.cur--\n this.discoverItems()\n }\n // scroll to top\n this.scrollToTop(300)\n }", "function prevResultSet(searchTerm)\n{\n const settings = {\n url: BOOKS_SEARCH_URL,\n data: {\n q: `${searchTerm}`,\n maxResults: 6,\n startIndex: startIndex\n },\n dataType: 'json',\n type: 'GET',\n success: displayData\n };\n $.get(settings);\n}", "function search() {\n\turl = \"search.php?term=\" +document.getElementById('term').value;\n\turl+= \"&scope=\" + document.getElementById('scope').value;\n\tdocument.getElementById('search').innerHTML = \"\";\n\tdoAjaxCall(url, \"updateMain\", \"GET\", true);\n}", "function main() {\r\n loadBooks(\"\");\r\n id(\"home\").addEventListener(\"click\", function() {\r\n loadBooks(\"\");\r\n id(\"search-term\").value = \"\";\r\n id(\"home\").disabled = true;\r\n });\r\n id(\"search-btn\").addEventListener(\"click\", search);\r\n id(\"back\").addEventListener(\"click\", returnToList);\r\n }", "function init() {\n updateResults();\n bind.typeaheadKeys();\n bind.searchFocus();\n bind.searchChange();\n bind.searchSubmit();\n bind.historyState();\n}", "afterSearch(result, params) {\n console.log(\"Hereeeeeeeeeee 12\");\n }", "function search( event, searchTerms ){\n //console.debug( this, 'searching', searchTerms );\n $( this ).trigger( 'search:searchInput', searchTerms );\n if( typeof options.onfirstsearch === 'function' && firstSearch ){\n firstSearch = false;\n options.onfirstsearch( searchTerms );\n } else {\n options.onsearch( searchTerms );\n }\n }", "function search( event, searchTerms ){\n //console.debug( this, 'searching', searchTerms );\n $( this ).trigger( 'search:searchInput', searchTerms );\n if( typeof options.onfirstsearch === 'function' && firstSearch ){\n firstSearch = false;\n options.onfirstsearch( searchTerms );\n } else {\n options.onsearch( searchTerms );\n }\n }", "function phraseBoxKeypress(e) { // run on each keystroke inside text box - onkeydown=\"navHistory(event.keyCode) - from index.html\r\n\tvar phrPos, pBox\r\n\tphr = sVal() // get phrase from SearchField\r\n\tpBox = document.getElementById(\"phraseBox\")\r\n\r\n\tphrPos = sHistory.indexOf(phr) // position of phrase in History array\r\n\tswitch (e) { // keypress event\r\n\t\tcase 13: // Enter\r\n\t\t\taddPhraseToHistory(phr, true) // enter as single phrase\r\n\t\t\tpBox.value = \"\" // clear textbox on Enter\r\n\t\t\tbreak\r\n\t\tcase 38: // Up Arrow\r\n\t\t\tif (phrPos > 0) {\r\n\t\t\t\tphr = sHistory[phrPos - 1]\r\n\t\t\t}\r\n\t\t\tif (phr !== \"\") {pBox.value = phr; updateWordBreakdown(); updateTables()}\r\n\t\t\tbreak\r\n\t\tcase 40: // Down Arrow\r\n\t\t\tif (phrPos > -1) {\r\n\t\t\t\tif (sHistory.length > (phrPos + 1)) {phr = sHistory[phrPos + 1]}\r\n\t\t\t} else {\r\n\t\t\t\tif (sHistory.length > 0) {phr = sHistory[0]}\r\n\t\t\t}\r\n\t\t\tif (phr !== \"\") {pBox.value = phr; updateWordBreakdown(); updateTables()}\r\n\t\t\tbreak\r\n\t\tcase 46: // Delete - remove entries from history\r\n\t\t\tif (sHistory.length == 1 && phrPos > -1) { // if one entry and matches box contents\r\n\t\t\t\tsHistory = [] // reinit\r\n\t\t\t\ttArea = document.getElementById(\"HistoryTableArea\")\r\n\t\t\t\ttArea.innerHTML = \"\" // clear table\r\n\t\t\t}\r\n\t\t\tif (phrPos > -1) {\r\n\t\t\t\tsHistory.splice(phrPos, 1) // if a match is found, delete entry\r\n\t\t\t}\r\n\t\t\tpBox.value = \"\" // empty text box, so the old value is not added again\r\n\t\t\tupdateWordBreakdown() // update breakdown\r\n\t\t\tupdateTables() // update enabled cipher and history table\r\n\t\t\tbreak\r\n\t\tcase 36: // Home - clear all history\r\n\t\t\tsHistory = [] // reinitialize\r\n\t\t\tdocument.getElementById(\"HistoryTableArea\").innerHTML = \"\" // clear history table\r\n\t\t\tbreak\r\n\t\tcase 35: // End - parse sentence as separate words and phrases\r\n\t\t\tphr = phr.replace(/\\t/g, \" \") // replace tab with spaces\r\n\t\t\tphr = phr.replace(/ +/g, \" \") // remove double spaces\r\n\t\t\t// phr = phr.replace(/(\\.|,|:|;|\\\\|)/g, \"\") // remove special characters, last one is \"|\"\r\n\r\n\t\t\twordArr = phr.split(\" \") // split string to array, space delimiter\r\n\t\t\tphrLimit = optPhraseLimit // max phrase length\r\n\t\t\tvar phrase = \"\"; var k = 1;\r\n\t\t\t// for (i = 0; i < wordArr.length; i++) { // phrases in normal order\r\n\t\t\t\t// k = 1 // init variable\r\n\t\t\t\t// phrase = wordArr[i]\r\n\t\t\t\t// addPhraseToHistory(phrase, false)\r\n\t\t\t\t// while (k < phrLimit && i+k < wordArr.length) { // add words to a phrase, check it is within array size\r\n\t\t\t\t\t// phrase += \" \"+wordArr[i+k]\r\n\t\t\t\t\t// addPhraseToHistory(phrase, false)\r\n\t\t\t\t\t// k++\r\n\t\t\t\t// }\r\n\t\t\t// }\r\n\t\t\tfor (i = wordArr.length-1; i > -1; i--) { // add phrases in reverse order, so you don't have to read backwards\r\n\t\t\t\tk = 1 // word count\r\n\t\t\t\tphrase = wordArr[i]\r\n\t\t\t\taddPhraseToHistory(phrase, false) // don't recalculate table yet\r\n\t\t\t\twhile (k < phrLimit && i-k > -1) { // add words to a phrase, check it is within wordArr size\r\n\t\t\t\t\tphrase = wordArr[i-k]+\" \"+phrase\r\n\t\t\t\t\taddPhraseToHistory(phrase, false)\r\n\t\t\t\t\tk++\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tupdateHistoryTable() // update table only once after all phrases are added\r\n\t\t\tbreak\r\n\t}\r\n}", "AddSearchProvider() {}", "function linkSource(){\n //link to source\n $('#field_div_id_'+(fieldSet-1)+'_subject').autocomplete({\n source: searchIndex,\n autoFocus:true\n });\n $('#field_div_id_'+(fieldSet-1)+'_year').autocomplete({\n source: years,\n autoFocus:true\n });\n\n\n $('#add-fav-field').autocomplete({\n source: searchIndex,\n autoFocus:true\n });\n\n $('#from-year').autocomplete({\n source: years,\n autoFocus:true\n });\n\n $('#to-year').autocomplete({\n source: years,\n autoFocus:true\n });\n\n\n $('#bulk_year').focusin(function(e){\n $('#quick_year_selector').slideDown();\n });\n\n\n $('#field_div_id_' + (fieldSet-1) + '_year').on('keydown',function(e){\n var keyCode = e.keyCode || e.which;\n if (keyCode == 9){\n //Tab pressed\n addField();\n }\n });\n\n\n\n}", "handleAutocompleteInput(e) {\n const self = this;\n\n if (self.isLoading()) {\n e.preventDefault();\n return false;\n }\n\n // Makes a new AJAX call every time a key is pressed.\n const waitForSource = this.getDataFromSource();\n waitForSource.done((term, response) => {\n self.currentDataSet = response;\n self.openList(term, response);\n });\n\n return null;\n }", "function _focusSearch() {\n setTimeout(function() {\n _$search.focus();\n }, CFG.TIME.DELAY);\n }", "autoCompleteFocus() {\n if (!this.receivedUserInput_) {\n this.activateFocus();\n }\n }", "autoCompleteFocus() {\n if (!this.receivedUserInput_) {\n this.activateFocus();\n }\n }", "autoCompleteFocus() {\n if (!this.receivedUserInput_) {\n this.activateFocus();\n }\n }", "autoCompleteFocus() {\n if (!this.receivedUserInput_) {\n this.activateFocus();\n }\n }", "function manualSearch(e) {\n let term = document.querySelector(\"#searchTerm\").value;\n term = term.trim();\n if (term.length < 1) return;\n manualSearchData(term.toLowerCase());\n}", "globalSearchAutoSuggest(newValue) {\n let requestedData = {\n votingElection_code: constants.votingElectionCode,\n search_key: ''\n }\n\n items('POST', requestedData, constants.filterGlobalSearch)\n .then(response => {\n if (response.status === \"Success\") {\n let val = [];\n if (response.data.election.length !== 0) {\n for (let i of response.data.election) {\n let temp = { label: i.election_name, id: i.election_id, type: 'election' }\n val.push(temp);\n }\n }\n if (response.data.political_party.length !== 0) {\n for (let i of response.data.political_party) {\n let temp = { label: i.party_name, id: i.party_id, type: 'party' }\n val.push(temp);\n }\n }\n if (response.data.candidate.length !== 0) {\n for (let i of response.data.candidate) {\n let temp = { label: i.candidate_name, id: i.candidate_id, type: 'candidate' }\n val.push(temp);\n }\n }\n localStorage.setItem(btoa('search_data'), JSON.stringify(val));\n this.returnValue();\n }\n else if (response.status === \"Failure\") {\n\n }\n else {\n\n }\n });\n }", "function _triggerRefresh() {\n gAutoComplete.trigger( \"apexrefresh\" );\n } // _triggerRefresh", "function initializeSearch() {\n fb.child('vpc/features').on('child_added', function (snapshot) {\n DATA.push(snapshot.val());\n var names = dataUtilities.getAutoCompleteNames([DATA]);\n $(\".search\").autocomplete({ source: names });\n });\n $(\".search\").on(\"autocompleteselect\", function (event, ui) {\n var landmark = dataUtilities.findData(DATA, ui.item.value);\n map.setView(landmark.properties.center, 8 /* LOL IGNORE ZOOM */, { animate: true });\n });\n}", "function setupSearch() {\n $(\".search-btn\").click(submitSearch);\n $(\".date-search-bar\").keypress(submitSearch);\n $(\".search-bar\").keypress(submitSearch);\n\n var filter = getURLParameter(\"filter\");\n\n var searchTip;\n\n if (filter !== null) {\n searchTip = sprintf(\"Search with the %s filter\", filter);\n } else if (endsWith(window.location.pathname, \"visualizations\")) {\n searchTip = sprintf(\"Filter %s's visualizations\", profileUsername);\n } else {\n searchTip = sprintf(\"Search %s's history\", profileUsername);\n }\n\n makeTip(\".search-bar\", searchTip, \"right\", \"hover\");\n makeTip(\".date-search-bar\", \"Limit search by date.\", \"bottom\", \"hover\");\n}" ]
[ "0.6669009", "0.59735817", "0.5961815", "0.5942989", "0.59123796", "0.5908308", "0.58546704", "0.5798347", "0.5795196", "0.5791119", "0.5772822", "0.5768325", "0.5755815", "0.5730849", "0.5723562", "0.5704032", "0.568863", "0.5663023", "0.5654623", "0.5634164", "0.5633087", "0.56103176", "0.5609429", "0.5587588", "0.5587426", "0.5580455", "0.5577554", "0.55566674", "0.5556322", "0.5554437", "0.5536405", "0.5534354", "0.55265135", "0.552519", "0.5522566", "0.5506685", "0.55051285", "0.5504734", "0.5492396", "0.5490528", "0.54905266", "0.54738307", "0.54713535", "0.54636115", "0.5460917", "0.54569185", "0.54542726", "0.5451562", "0.5444024", "0.5430298", "0.5428522", "0.5426134", "0.54245394", "0.5424462", "0.5422974", "0.5420074", "0.5416724", "0.54125804", "0.5402855", "0.5400625", "0.53993744", "0.5397649", "0.5382855", "0.5379681", "0.5377831", "0.5376543", "0.53753525", "0.5367482", "0.53575283", "0.53573835", "0.53554296", "0.5353821", "0.5353756", "0.535313", "0.5350912", "0.534754", "0.5335853", "0.53339285", "0.5333905", "0.5333577", "0.53263044", "0.53247803", "0.53234446", "0.53230965", "0.5319011", "0.5319011", "0.53101534", "0.53091633", "0.5306816", "0.53002846", "0.5299156", "0.5289082", "0.5289082", "0.5289082", "0.5289082", "0.5287811", "0.5286749", "0.52866954", "0.5286097", "0.52859217" ]
0.620808
1
Setup the hooks to main search addon
function extendSearchWithAutoComplete(cm) { function addToSearchHistory(cm, query) { getSearchHistory(cm).add(query); } // function addToSearchHistory() // tracks search history cm.on("searchEntered", addToSearchHistory); cm.on("replaceEntered", addToSearchHistory); // add auto complete by search history to search dialog cm.on("searchDialog", setupDialogAutoComplete); } // function extendSearchWithAutoComplete(..)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setupUtenteSearch() {\r\n setupUserSearch();\r\n setupSNSSearch();\r\n}", "function initSearch() {\r\n\tconsole.log(\"searchReady\");\r\n}", "function SearchWrapper () {}", "function init() {\n updateResults();\n bind.typeaheadKeys();\n bind.searchFocus();\n bind.searchChange();\n bind.searchSubmit();\n bind.historyState();\n}", "function setupSearch() {\n $(\".search-btn\").click(submitSearch);\n $(\".date-search-bar\").keypress(submitSearch);\n $(\".search-bar\").keypress(submitSearch);\n\n var filter = getURLParameter(\"filter\");\n\n var searchTip;\n\n if (filter !== null) {\n searchTip = sprintf(\"Search with the %s filter\", filter);\n } else if (endsWith(window.location.pathname, \"visualizations\")) {\n searchTip = sprintf(\"Filter %s's visualizations\", profileUsername);\n } else {\n searchTip = sprintf(\"Search %s's history\", profileUsername);\n }\n\n makeTip(\".search-bar\", searchTip, \"right\", \"hover\");\n makeTip(\".date-search-bar\", \"Limit search by date.\", \"bottom\", \"hover\");\n}", "AddSearchProvider() {}", "function main() {\n\tif (isSearchPage()) {\n\t\tsaveLinks();\n\t} else {\n\t\taddNextItemLink();\n\t}\n}", "initSearch() {\n this.search.init();\n\n if (this.visible) {\n this.closeSearch();\n } else {\n this.openSearch();\n }\n }", "function main() {\n\n\t$(\"#nav-search-btn\").on(\"click\", function(e) {\n\t\te.preventDefault();\n\t\tif ($(\"#ex1\").val()) {\n\t\t\t$(\".search\").empty();\n\t\t\t$(\".search\").show();\n\t\t\t$(\".notSearch\").hide();\n\t\t\tlet userQuery = $(\"#ex1\").val().toLowerCase();\n\t\t\tsearchEndPoint(userQuery);\n\t\t}\n\t});\n\n\t$(\"#reportSearch\").on(\"click\", function(e) {\n\t\tconsole.log(\"Reportar\");\n\t\tlet reported = $('.rightSearch').attr('id');\n\t\tgetReported(reported);\n\t});\n\n\t$(\".searches-container\").on(\"click\", function(e) {\t\t\n\t\twindow.scroll({\n\t\t\ttop: 0, \n\t\t\tleft: 0, \n\t\t\tbehavior: 'smooth'\n\t\t});\n\t\tdisplaySearch(e.target.id);\n\t});\n}", "function initEvents() {\n\t// Launch search on the click on the search button\n\t$(\"#search\").click(function(){\n \trefreshResults();\n });\n \n // Listen to the checkbox state change to launch search everytime\n $(\"input[type='checkbox']\").change(function () {\n \trefreshResults();\n });\n \n // Launch the search when hitting Enter in the keywords field\n $(\"#keywords\").keydown(function(event) {\n \tif ( event.which == 13 ) {\n \t\trefreshResults();\n \t}\n });\n}", "function bindSearchResultHandlers() {\n bindAddHandlers();\n enableSorting();\n }", "function searchUIImporting() { savedSearchUI = extSearchUI; gSetSearchUI(null); }", "function setup() {\n $('#search-box').on('input', handleSearch);\n $('#search-box').trigger('focus');\n\n accountSummaries.get().then(function(summaries) {\n let urlHash = getMapFromHash();\n let validIds = returnValidIds(summaries, urlHash);\n let allIds = getAllIds(summaries, validIds);\n\n setViewSelector(allIds.viewId);\n site.setReadyState();\n });\n}", "function startUp() {\n let search = document.getElementById(\"search\");\n search.onclick = searchAll;\n }", "function main() {\r\n loadBooks(\"\");\r\n id(\"home\").addEventListener(\"click\", function() {\r\n loadBooks(\"\");\r\n id(\"search-term\").value = \"\";\r\n id(\"home\").disabled = true;\r\n });\r\n id(\"search-btn\").addEventListener(\"click\", search);\r\n id(\"back\").addEventListener(\"click\", returnToList);\r\n }", "function search_init(){\n\n // DOM contact points.\n var form_elt = '#search_form';\n var search_elt = '#search';\n\n // Helper lifted from bbop-js: bbop.core.first_split\n // For documentation, see:\n // http://cdn.berkeleybop.org/jsapi/bbop-js/docs/files/core-js.html\n var first_split = function(character, string){\n\tvar retlist = null;\n\n\tvar eq_loc = string.indexOf(character);\n\tif( eq_loc == 0 ){\n retlist = ['', string.substr(eq_loc +1, string.length)];\n\t}else if( eq_loc > 0 ){\n var before = string.substr(0, eq_loc);\n var after = string.substr(eq_loc +1, string.length);\n retlist = [before, after];\n\t}else{\n retlist = ['', ''];\n\t}\n\t\n\treturn retlist;\n };\n\n // Override form submission and bump to search page.\n jQuery(form_elt).submit(\n\tfunction(event){\n\t event.preventDefault();\n\t \n\t var val = jQuery(search_elt).val();\n\t var newurl = \"http://\"+window.location.host+\"/search/\"\n\t\t+encodeURIComponent(val);\n\t window.location.replace(newurl);\n\t});\n\n // Arguments for autocomplete box.\n var ac_args = {\n\tposition : {\n \t my: \"right top\",\n at: \"right bottom\",\n\t collision: \"none\"\n\t},\n\tsource: function(request, response) {\n\t console.log(\"trying autocomplete on \"+request.term);\n\n\t // Argument response from source gets map as argument.\n\t var _parse_data_item = function(item){\n\t\t\n\t\t// If has a category, append that; if not try to use\n\t\t// namespace; otherwise, nothing.\n\t\tvar appendee = '';\n\t\tif( item ){\n\t\t if( item['category'] ){\n\t\t\tappendee = item['category'];\n\t\t }else if( item['id'] ){\n\t\t\t// Get first split on '_'.\n\t\t\tvar fspl = first_split('_', item['id']);\n\t\t\tif( fspl[0] ){\n\t\t\t appendee = fspl[0];\n\t\t\t}\n\t\t }\n\t\t}\n\n\t\treturn {\n\t\t label: item.term,\n\t\t tag: appendee,\n\t\t name: item.id\n\t\t};\n\t };\n\t var _on_success = function(data) {\n\n\t\t// Pare out duplicates. Assume existance of 'id'\n\t\t// field. Would really be nice to have bbop.core in\n\t\t// here...\n\t\tvar pared_data = [];\n\t\tvar seen_ids = {};\n\t\tfor( var di = 0; di < data.length; di++ ){\n\t\t var datum = data[di];\n\t\t var datum_id = datum['id'];\n\t\t if( ! seen_ids[datum_id] ){\n\t\t\t// Only add new ids to pared data list.\n\t\t\tpared_data.push(datum);\n\t\t\t\n\t\t\t// Block them in the future.\n\t\t\tseen_ids[datum_id] = true;\n\t\t }\n\t\t}\n\n\t\tvar map = jQuery.map(pared_data, _parse_data_item);\n\t\tresponse(map);\n\t };\n\n\t var query = \"/autocomplete/\"+request.term+\".json\";\n\t jQuery.ajax({\n\t\t\t url: query,\n\t\t\t dataType:\"json\",\n\t\t\t /*data: {\n\t\t\t prefix: request.term,\n\t\t\t },*/\n\t\t\t success: _on_success\n\t\t\t});\n\t},\n\tmessages: {\n noResults: '',\n\t results: function() {}\n },\n\tselect: function(event,ui) {\n\t if (ui.item !== null) { \n\t\tvar newurl = \"http://\"+window.location.host+\"/search/\"\n\t \t +encodeURIComponent(ui.item.label);\n\t\twindow.location.replace(newurl);\n\t }\n\t}\t\n };\n\n // Create our own custom rendering to make the categories a little\n // nicer to look at (as minor data).\n // http://jqueryui.com/autocomplete/#custom-data\n var jac = jQuery(search_elt).autocomplete(ac_args);\n jac.data('ui-autocomplete')._renderItem = function(ul, item){\n\tvar li = jQuery('<li>');\n\tli.append('<a alt=\"'+ item.name +'\" title=\"'+ item.name +'\">' +\n\t\t '<span class=\"autocomplete-main-item\">' +\n\t\t item.label +\n\t\t '</span>' + \n\t\t '&nbsp;' + \n\t\t '<span class=\"autocomplete-tag-item\">' +\n\t\t item.tag +\n\t\t '</span>' + \n\t\t '</a>');\n\tli.appendTo(ul);\n\treturn li;\n };\n}", "function loadHook() {\n targetBlank();\n bindEnqueue();\n bindIndexButtons();\n}", "function init() {\n\n loadLatestSearch();\n\n displayLatestSearches();\n\n searchHandler();\n\n $('#submitBtn').on(\"click\", () => {\n saveSearchTerm($('#search').val().toUpperCase()); \n searchHandler($('#search').val());\n })\n}", "function init() {\n\t// TMDB search button click handler\n\tdocument.querySelector('.btn-tmdb-search').addEventListener('click', e => {\n\t\tconst pageNr = 1;\n\t\tsearchTMDB(pageNr);\n\t});\n\n}", "function init_search() {\n\tif(Info.browser.isIEpre6) return;\n\t\n\t// get selectbox when clicking change on active filters\n\t\n\tif ($(\"search-filter-zone\")) {\n\t\t$(\"search-filter-zone\").setStyle({ left: '0'}); // show filter\n\t\t$(\"search-filter-zone\").select('div.active-filter').each(function(element) {\n\t\t\tvar name = element.id.replace(/^active-filter-/, '');\n\t\t\tvar filter = new ActiveSearchFilter(name);\n\t\t\t$(element).observe(\"click\",\n\t\t\t\tfunction(e) {\n\t\t\t\t\tfilter.load();\n\t\t\t\t\tEvent.stop(e);\n\t\t\t\t}\n\t\t\t);\n\t\t});\n\t\t\n\t\t// 1st element after last gui.select hides layer\n\t\tvar resetButton = $$(\"fieldset.reset\")[0].down('a.generic-button');\n\t\tresetButton.observe(\"focus\", function() { Layer.closeCurrent(); });\n\t}\n\t\n\t// init auto complete layer\n\tnew AutoCompleteLayer($('query'));\n\n\t// correct minor IE6 layout issues\n\n\tif (Info.browser.isIEpre7) {\n\t\tvar suggestion = $$('div.search-suggestion').first();\n\t\tif (suggestion && suggestion.next().hasClassName('recommendations')) {\n\t\t\tsuggestion.next().style.marginTop = '-3px';\n\t\t}\n\t}\n\n}", "function setUpSearch() {\n const $search = jQuery(\".users-search\");\n const usersSearch = new UsersSearch($search);\n}", "function addSearchEngine() {\n window.external.AddSearchProvider(URL_BASE + \"/api/websearch.lua?\" + gxdomain)\n}", "function initSearch(event) {\n var searchPageDoc = event.target;\n var searchField = searchPageDoc.getElementByTagName(\"searchField\");\n if (!searchField) { return; }\n \n var keyboard = searchField.getFeature(\"Keyboard\");\n keyboard.onTextChange = function () {\n doSearch(keyboard.text, searchPageDoc);\n }\n}", "function onLoadExtended()\n{\n // Load the base media search.\n onLoadMediaSearch();\n\t\n\t// Setup Google media search.\n\tsearchObject = new GoogleMediaSearch('HiddenElement', 'ResultsPane', test);\n\t\n\t// Bind enter key to search input.\n\t$(\"#SearchInput\").keypress(\n\t\tfunction (e)\n\t\t{\n\t\t\tif (e.which == 13)\n\t\t\t{\n\t\t\t\tsearch($('#SearchInput')[0].value)\n\t\t\t}\n\t\t});\n}", "function initUI() {\n showDataIsLoaded();\n showExplorePage();\n bindSearchHandler();\n}", "function bindSearchBoxEvents() {\n var trigger, searchType, searchBoxValueFromSuggestions;\n bindSearchWidgetEvents();\n\n $('.search-close').click(function() {\n\n resetSearchBox();\n });\n\n $('.search-options a').click(function() {\n\n var type = (type = $(this).attr('href')) ? type.trim().toLowerCase() : '',\n input = searchBox.val();\n input = input ? input.trim() : '';\n $('.search-results ul').html('');\n if (input !== '') {\n bindSearchSuggestions(type);\n } else {\n $('.search-results ul').html('');\n }\n });\n bindSearchBoxKeyupEvents();\n bindSearchSuggestionEvents();\n $(function() {\n $(\"form\").submit(function() {\n return false;\n });\n });\n }", "function initMageSearch() {\n console.log('initializing search');\n jQuery('#search_mini_form').submit(function(e){\n\n if (seachbarIsActive()){\n if (searchHasInput()){\n //submitSearch();\n } else {\n e.preventDefault();\n // CANCEL SEARCH\n }\n } else {\n // ACTIVATE SEARCH\n e.preventDefault();\n jQuery('.form-search .input-text, .search-wrapper button').addClass('active');\n jQuery('.form-search .input-text').focus();\n }\n });\n\n\n jQuery('.form-search .input-text').focusout(function(){\n handleSearchFocusOut()\n });\n\n jQuery('.form-search .input-text, .search-wrapper button').focus(function(){\n handleSearchFocusIn();\n });\n\n // jQuery('search_mini_form .search.submit').click(function(){\n // });\n}", "function attachHandlers() {\n addDataGtmIgnore();\n behavior.attach( 'submit-search', 'submit', handleSubmit );\n behavior.attach( 'change-filter', 'change', handleFilter );\n behavior.attach( 'clear-filter', 'click', clearFilter );\n behavior.attach( 'clear-all', 'click', clearFilters );\n behavior.attach( 'clear-search', 'clear', clearSearch );\n cfExpandables.init();\n expandableFacets.init();\n const inputContainsLabel = document.querySelector( '.tdp-activity-search .input-contains-label' );\n if ( inputContainsLabel ) {\n const clearableInput = new ClearableInput( inputContainsLabel );\n clearableInput.init();\n }\n}", "function qodeOnWindowLoad() {\r\n qodeInitelementorListingSimpleSearch();\r\n }", "function handleSearch() {\n triggerSearch({}); // need empty braces here\n }", "function addSearchListeners() {\n searchInput.addEventListener(\"keyup\", function(event) {\n const k = event.keyCode; // ignore arrow keys\n if (k > 36 && k < 41) return;\n suggestionModule.displayMatches();\n });\n\n searchInput.addEventListener(\"focus\", suggestionModule.displayMatches);\n\n document.addEventListener(\n \"click\",\n function() {\n if (\n !(event.target === searchInput || suggestions.contains(event.target))\n )\n removeChildren(suggestions);\n },\n true\n );\n }", "function firstLoadForTab_Search()\n{\n //console.log('first load for search tab');\n \n tryPopulateDB();\n \n global_pagesLoaded.search = true;\n}", "function initSearch() {\n var searchInput=$(\"#search-input\");\n var magnifier=$(\"#magnifier\");\n var filmWrapper=$(\".film-wrapper\");\n var seriesWrapper=$(\".series-wrapper\");\n var myQuery;\n\n searchInput.on('keydown',function(e) {\n if (e.which == 13) {\n myQuery=searchInput.val();\n searchApi(myQuery);\n searchInput.val(\"\");\n }\n });\n\n magnifier.click(function() {\n myQuery=searchInput.val();\n searchApi(myQuery);\n searchInput.val(\"\");\n });\n}", "onSearch() {\n try {\n const searchText = this.getSearchHash();\n if (searchText === this.priorSearchText)\n return;\n this.engine.search(searchText);\n this.priorSearchText = searchText;\n }\n catch (ex) {\n this.publish(\"error\", ex.message);\n }\n }", "function bindSearchHandler() {\n document.getElementById(\"search\").addEventListener(\"input\", searchHander);\n}", "function setupSearchBar(){\n\t//set up search bar button\n\t//search is declared within utilities.js\n\t\n\t//document.getElementById('search_button').onclick=search;\n\t//document.getElementById('clear_search_button').onclick=clearSearch;\n\t\n\n\t//document.getElementById('search_text_bar').placeholder = search_placeholder_string;\n\tdocument.getElementById('myInput').placeholder = search_placeholder_string;\n\n\t//make it so when you hit the enter button after typing text, it will act as a click\n\tdocument.getElementById(\"myInput\").addEventListener(\"keyup\", function(event) {\n\t\t//console.log(\"typing!\");\n\t\tif(document.getElementById(\"closeSearch\").style.display == \"none\"){\n\t\t\tdocument.getElementById(\"closeSearch\").style.display = \"block\";\n\t\t}\n\n\t//document.getElementById(\"search_text_bar\").addEventListener(\"keyup\", function(event) {\n\t\t// Cancel the default action, if needed\n\t\tevent.preventDefault();\n\t\t// Number 13 is the \"Enter\" key on the keyboard\n\t\tif (event.keyCode === 13) {\n\t\t\t// Trigger the button element with a click\n\t\t\t//document.getElementById(\"search_button\").click();\n\t\t\tsearch();\n\t\t}\n\t});\n}", "function addEvents() {\n if (solr.options.call == 2 && Boolean($('#keyword_default').val())) {\n $('#keyword').val($('#keyword_default').val());\n solr.onSearchEvent();\n }\n}", "function searchWine(){\n setSearchFor();\n whatToSearch();\n watchSubmit();\n}", "function menu_do_search() {\n\t// directly use the search page if it is active\n if (current === \"Special::Search\") {\n\t\td$('string_to_search').value = d$('menu_string_to_search').value;\n }\n woas.do_search(d$('menu_string_to_search').value);\n}", "function applySearchInventoryHandler() {\n debug && console.log( \"VanInventory.applySearchInventoryHandler: Binding the custom inventory search bar handlers\" );\n\n // Bind the search handler\n $(\"#inventorySearch\").bind( \"change\", searchInventoryHandler );\n }", "beforeSearch(params, populate) {\n console.log(\"Hereeeeeeeeeee 11\");\n }", "function init() {\r\n\tfavorites = getFavorites();\r\n\r\n\telementInit();\r\n\tsettingsInit();\r\n\tuiInit();\r\n\tkeyboardInit();\r\n\t\r\n\t//editorShow();\r\n\t//settingsShow();\r\n\t\r\n\t// The reason I'm doing is this is because it'd be laggier to append a click event to each button element.\r\n\twindow.onclick = handleToolbar;\r\n\tfieldSearch.onfocus = uiCreateTooltip;\r\n\tfieldSearch.onblur = function() { setTimeout(\"addClass(fieldSearch.tooltip, 'hidden');\", 200); };\r\n}", "function handleSearch(e) {\n setSearchRes([]);\t \n const idx = lunr(function() {\nthis.ref('id');\nthis.field('text');\nthis.metadataWhitelist = ['position'];\n//console.log('hook: ',mdPaths)\nmdRaws.forEach(function(raw) {\nthis.add(raw);\n}, this);\t\n});\nlet results = e.target.value !== \"\" ? idx.search(e.target.value) : [];\n//console.log(idx.search(e.target.value));\n//console.log('search result: ', searchResult);\n// let resultRaw = document.querySelector('.result-raw');\n//\t\tresultRaw.remove();\t\t\n\nsetBar(true);\nsetSearchRes(results);\t \n\nlet expanded = document.querySelector('.search-bar-expanded');\nlet dropdown = document.querySelector('.dropdown');\nlet navSearch = document.querySelector('.navbar__search');\n if (expanded !== null) {\ndropdown.style.display = 'block';\nnavSearch.style.position = 'relative';\t \n\t \n//\t console.log(mdRaws);\n }\n//console.log(expanded);\t\ndropdown.style.display = 'hide';\n}", "function init() {\n // Hide notifications after fade out, so we can't focus on links via keyboard.\n $(IDS.NOTIFICATION).addEventListener('transitionend', hideNotification);\n\n $(IDS.NOTIFICATION_MESSAGE).textContent =\n configData.translatedStrings.thumbnailRemovedNotification;\n\n var undoLink = $(IDS.UNDO_LINK);\n undoLink.addEventListener('click', onUndo);\n registerKeyHandler(undoLink, KEYCODE.ENTER, onUndo);\n undoLink.textContent = configData.translatedStrings.undoThumbnailRemove;\n\n var restoreAllLink = $(IDS.RESTORE_ALL_LINK);\n restoreAllLink.addEventListener('click', onRestoreAll);\n registerKeyHandler(restoreAllLink, KEYCODE.ENTER, onRestoreAll);\n restoreAllLink.textContent =\n configData.translatedStrings.restoreThumbnailsShort;\n\n $(IDS.ATTRIBUTION_TEXT).textContent =\n configData.translatedStrings.attributionIntro;\n\n $(IDS.NOTIFICATION_CLOSE_BUTTON).addEventListener('click', hideNotification);\n\n var embeddedSearchApiHandle = window.chrome.embeddedSearch;\n\n ntpApiHandle = embeddedSearchApiHandle.newTabPage;\n ntpApiHandle.onthemechange = onThemeChange;\n ntpApiHandle.onmostvisitedchange = onMostVisitedChange;\n\n var searchboxApiHandle = embeddedSearchApiHandle.searchBox;\n\n if (configData.isGooglePage) {\n // Set up the fakebox (which only exists on the Google NTP).\n ntpApiHandle.oninputstart = onInputStart;\n ntpApiHandle.oninputcancel = onInputCancel;\n\n if (ntpApiHandle.isInputInProgress) {\n onInputStart();\n }\n\n $(IDS.FAKEBOX_TEXT).textContent =\n configData.translatedStrings.searchboxPlaceholder;\n\n if (configData.isVoiceSearchEnabled) {\n speech.init(\n configData.googleBaseUrl, configData.translatedStrings,\n $(IDS.FAKEBOX_SPEECH), searchboxApiHandle);\n }\n\n // Listener for updating the key capture state.\n document.body.onmousedown = function(event) {\n if (isFakeboxClick(event))\n searchboxApiHandle.startCapturingKeyStrokes();\n else if (isFakeboxFocused())\n searchboxApiHandle.stopCapturingKeyStrokes();\n };\n searchboxApiHandle.onkeycapturechange = function() {\n setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);\n };\n var inputbox = $(IDS.FAKEBOX_INPUT);\n inputbox.onpaste = function(event) {\n event.preventDefault();\n // Send pasted text to Omnibox.\n var text = event.clipboardData.getData('text/plain');\n if (text)\n searchboxApiHandle.paste(text);\n };\n inputbox.ondrop = function(event) {\n event.preventDefault();\n var text = event.dataTransfer.getData('text/plain');\n if (text) {\n searchboxApiHandle.paste(text);\n }\n setFakeboxDragFocus(false);\n };\n inputbox.ondragenter = function() {\n setFakeboxDragFocus(true);\n };\n inputbox.ondragleave = function() {\n setFakeboxDragFocus(false);\n };\n\n // Update the fakebox style to match the current key capturing state.\n setFakeboxFocus(searchboxApiHandle.isKeyCaptureEnabled);\n\n // Load the OneGoogleBar script. It'll create a global variable name \"og\"\n // which is a dict corresponding to the native OneGoogleBarData type.\n var ogScript = document.createElement('script');\n ogScript.src = 'chrome-search://local-ntp/one-google.js';\n document.body.appendChild(ogScript);\n ogScript.onload = function() {\n injectOneGoogleBar(og);\n };\n } else {\n document.body.classList.add(CLASSES.NON_GOOGLE_PAGE);\n }\n\n if (searchboxApiHandle.rtl) {\n $(IDS.NOTIFICATION).dir = 'rtl';\n // Grabbing the root HTML element.\n document.documentElement.setAttribute('dir', 'rtl');\n // Add class for setting alignments based on language directionality.\n document.documentElement.classList.add(CLASSES.RTL);\n }\n\n // Collect arguments for the most visited iframe.\n var args = [];\n\n if (searchboxApiHandle.rtl)\n args.push('rtl=1');\n if (NTP_DESIGN.numTitleLines > 1)\n args.push('ntl=' + NTP_DESIGN.numTitleLines);\n\n args.push('removeTooltip=' +\n encodeURIComponent(configData.translatedStrings.removeThumbnailTooltip));\n\n // Create the most visited iframe.\n var iframe = document.createElement('iframe');\n iframe.id = IDS.TILES_IFRAME;\n iframe.tabIndex = 1;\n iframe.src = 'chrome-search://most-visited/single.html?' + args.join('&');\n $(IDS.TILES).appendChild(iframe);\n\n iframe.onload = function() {\n reloadTiles();\n renderTheme();\n };\n\n window.addEventListener('message', handlePostMessage);\n}", "function initSearch(e) {\n e.preventDefault();\n\n const searchType = determineSearch();\n if (searchType.invalid) return;\n\n const deptKey = dept.value.toUpperCase().replace(/\\s+/g, '');\n const courseKey = course.value.toUpperCase().replace(/\\s+/g, '');\n const sectionKey = section.value.toUpperCase().replace(/\\s+/g, '');\n resetInputs();\n\n searchFunc = searchType.searchFunc;\n searchFunc(deptKey, courseKey, sectionKey);\n}", "function configureSearchInput()\n{\n document.getElementById('search-query').\n addEventListener('keypress', onkeyForSearchInput, false);\n}", "function initAddons()\r\n{\r\n\t// Initialize code wrapping\r\n\tinitWrapToggle();\r\n\r\n\t// Initialize the code editor\r\n\tinitEditor();\r\n\r\n\t// Initialize tab persistence\r\n\tinitTabPersistence();\r\n\r\n\t// Initialize line reference\r\n\tinitLineReference();\r\n\r\n\t// Initialize bootstrap components\r\n\tinitBootstrap();\r\n}", "init() {\n if (!this.isInit) {\n return this.loadSearch();\n }\n }", "function setQuery() {\n getSearch(search.value);\n}", "_initAddons() {\n //\tInvoke \"before\" hook.\n this.trigger('initAddons:before');\n for (let addon in Mmenu.addons) {\n Mmenu.addons[addon].call(this);\n }\n //\tInvoke \"after\" hook.\n this.trigger('initAddons:after');\n }", "function _triggerSearch() {\n Mediator.pub(\n CFG.CNL.DICTIONARY_SEARCH,\n (_searchIsActive ? _$search.val() : \"\")\n );\n }", "function setupFunctions() {\n getAreas();\n document.querySelector(\"#searchButton button\").addEventListener('click', manualSearch);\n document.querySelector(\"#teamDisplay button\").addEventListener('click', releaseTeam);\n loadSavedData();\n\n}", "function onPageInit(e){\n\t\t\t\t\n\t\t\t\t//initBtnSearch\n\t\t\t\tinitBtnSearch();\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t}", "function set_search() {\n\t\n\t$find_archives_form = $('#find_archives_form');\n\t$findable_form = $('#findable_form');\n\t$findable_form.children('.archive').click(function() {\n\t\tswitch_to('archives');\n\t\tvar $this = $(this);\n\t\t$this.parent().find('.archive').removeClass('clicked');\n\t\t$this.addClass('clicked');\n\t\tvar index = $this.data('index');\n\t\tsearch_ui(index); \n\t});\n\t// Find archives \n\t$find_archives_form.submit(function() { // Submit find archives\n\t\tvar val = $find_archives_form.find('input[name=\"search\"]').val().toLowerCase();\n\t\tif (!val.length) {\n\t\t\t$findable_form.children().show();\n\t\t} else {\n\t\t\t$findable_form.children().hide();\n\t\t\t$findable_form.children().each(function() {\n\t\t\t\tif (-1!=$(this).attr('title').toLowerCase().indexOf(val)) $(this).show();\n\t\t\t});\n\t\t}\n\t\treturn false;\n\t});\n\t$find_archives_form.find('a').click(function() {\n\t\t$(this).closest('form').submit();\n\t});\n\t$find_archives_form.find('input[name=\"search\"]').on('keyup focusout', function() {\n\t\t$(this).closest('form').submit();\n\t});\n\t$search_form = $('#search_form');\n\t$search_form.submit(function() {\n\t\tsearch(1);\n\t\treturn false;\n\t});\n\t$search_form.find('a').click(function() {\n\t\t$(this).closest('form').submit();\n\t});\n\tvar $search_bar = $('#search_bar');\n\t$search_bar.find('.view-buttons').find('button').click(function() {\n\t\tvar $clicked = $(this);\n\t\t$clicked.blur();\n\t\t$clicked.siblings(':not(.page)').addClass('btn-default').removeClass('btn-primary');\n\t\t$clicked.addClass('btn-primary').removeClass('btn-default');\n\t\tsearch_results_ui($clicked.attr('id'));\n\t});\t\t\n\t$search_bar.find('.page').click(function() {\n\t\tvar $this = $(this);\n\t\tvar dir = null;\n\t\tvar page = null;\n\t\tif ($this.hasClass('prev-page')) dir = 'prev';\n\t\tif ($this.hasClass('next-page')) dir = 'next';\n\t\tswitch (dir) {\n\t\t\tcase 'prev':\n\t\t\t\tpage = do_search.page - 1;\n\t\t\t\tbreak;\n\t\t\tcase 'next':\n\t\t\t\tpage = do_search.page + 1;\n\t\t\t\tbreak;\n\t\t};\n\t\tif (null!=page) search(page);\n\t});\t\n\t\n}", "addGlobals(tabId, settingEl) {\n this.globalsAdded = true;\n\n // Add a search filter to shrink plugin list\n const containerEl = settingEl.parentElement;\n let searchEl;\n if (tabId !== \"plugins\" || this.searchInput) {\n // Replace the built-in search handler\n (searchEl = this.searchInput)?.onChange(changeHandler);\n } else {\n const tmp = new obsidian.Setting(containerEl).addSearch(s => {\n searchEl = s;\n s.setPlaceholder(\"Filter plugins...\").onChange(changeHandler);\n });\n searchEl.containerEl.style.margin = 0;\n containerEl.createDiv(\"hotkey-search-container\").append(searchEl.containerEl);\n tmp.settingEl.detach();\n }\n if (tabId === \"community-plugins\") {\n searchEl.inputEl.addEventListener(\"keyup\", e => {\n if (e.keyCode === 13 && !obsidian.Keymap.getModifiers(e)) {\n this.gotoPlugin();\n return false;\n }\n });\n }\n const plugin = this;\n function changeHandler(seek){\n const find = (plugin.lastSearch[tabId] = seek).toLowerCase();\n function matchAndHighlight(el) {\n const text = el.textContent = el.textContent; // clear previous highlighting, if any\n const index = text.toLowerCase().indexOf(find);\n if (!~index) return false;\n el.textContent = text.substr(0, index);\n el.createSpan(\"suggestion-highlight\").textContent = text.substr(index, find.length);\n el.insertAdjacentText(\"beforeend\", text.substr(index+find.length));\n return true;\n }\n containerEl.findAll(\".setting-item\").forEach(e => {\n const nameMatches = matchAndHighlight(e.find(\".setting-item-name\"));\n const descMatches = matchAndHighlight(\n e.find(\".setting-item-description > div:last-child\") ??\n e.find(\".setting-item-description\")\n );\n e.toggle(nameMatches || descMatches);\n });\n }\n setImmediate(() => {\n if (!searchEl) return\n if (searchEl && typeof plugin.lastSearch[tabId] === \"string\") {\n searchEl.setValue(plugin.lastSearch[tabId]);\n searchEl.onChanged();\n }\n if (!obsidian.Platform.isMobile) searchEl.inputEl.select();\n });\n containerEl.append(settingEl);\n\n if (tabId === \"plugins\") {\n const editorName = this.getSettingsTab(\"editor\")?.name || \"Editor\";\n const workspaceName = this.getSettingsTab(\"file\")?.name || \"Files & Links\";\n this.createExtraButtons(\n new obsidian.Setting(settingEl.parentElement)\n .setName(\"App\").setDesc(\"Miscellaneous application commands (always enabled)\"),\n {id: \"app\", name: \"App\"}, true\n );\n this.createExtraButtons(\n new obsidian.Setting(settingEl.parentElement)\n .setName(editorName).setDesc(\"Core editing commands (always enabled)\"),\n {id: \"editor\", name: editorName}, true\n );\n this.createExtraButtons(\n new obsidian.Setting(settingEl.parentElement)\n .setName(workspaceName).setDesc(\"Core file and pane management commands (always enabled)\"),\n {id: \"workspace\", name: workspaceName}, true\n );\n settingEl.parentElement.append(settingEl);\n }\n }", "function bindSearchSuggestionEvents() {\n var highlightedLink, trigger, searchType, parentUL;\n $('.search-results').on('mouseenter', 'li', function() {\n $('.search-results span').removeClass('highlight');\n $(this).find('span').addClass('highlight');\n });\n\n $('.search-results').on('mouseleave', 'li', function() {\n $(this).find('span').removeClass('highlight');\n });\n $(\".search-results\").on('click', '.is-opened li a', function(event) {\n trigger = SN.Constant.GTM_SEARCH_EVENT_SUGGESTIONS;\n searchType = getSearchType();\n highlightedLink = $('.search-results .is-opened li span.highlight');\n parentUL = $('.search-results .is-opened li span.highlight').closest('ul').attr('id');\n\n if (highlightedLink.length === 1) {\n searchBox.val(highlightedLink.text());\n $(\".search-wrapper\").hide();\n $(\".searchfn\").show();\n search(searchBox.val(), trigger, searchType, parentUL);\n\n }\n });\n }", "function initSearchBox(options) {\n // Invoke auto complete for search box\n var searchOptions = {\n data: options,\n list: {\n maxNumberOfElments: 0,\n match: {enabled: true},\n onChooseEvent: function () {\n searchChooseItem();\n }\n }\n };\n searchInput.easyAutocomplete(searchOptions);\n\n // Start searching when typing in search box\n searchInput.on(\"input\", function (e) {\n e.preventDefault();\n searchChooseItem();\n });\n }", "function init(){\r\n getDataFromNyt();\r\n resetForm();\r\n newSearch();\r\n}", "function initAutoComplete(){\n // jQuery(\"#contact_sphinx_search\")\n // jQuery(\"#account_sphinx_search\")\n // jQuery(\"#campaign_sphinx_search\")\n // jQuery(\"#opportunity_sphinx_search\")\n // jQuery(\"#matter_sphinx_search\")\n jQuery(\"#search_string\").keypress(function(e){\n if(e.which == 13){\n searchInCommon();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n\n jQuery(\"#lawyer_search_query\").keypress(function(e){\n if(e.which == 13){\n searchLawyer();\n return jQuery(\".ac_results\").fadeOut();\n }\n });\n}", "function setupNav() {\n setupPageSelector();\n setupRecipeSelector();\n}", "function setSearchFor(){\n $(`.js-wineries`).on('click',function(){\n STATE.searchFor = 'Wineries';\n console.log(STATE.searchFor);\n\n });\n $(`.js-tasteRooms`).on('click',function(){\n STATE.searchFor = 'Tasting Rooms';\n console.log(STATE.searchFor);\n });\n\n}", "function navigationSearchInit() {\r\n\t\t\t\t\t\r\n\t\t\t\t\tvar $placeholder = ($('#search-outer #search input[type=text][data-placeholder]').length > 0) ? $('#search-outer #search input[type=text]').attr('data-placeholder') : '';\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Material skin add search BG markup.\r\n\t\t\t\t\tif ($body.hasClass('material') && $('#header-outer .bg-color-stripe').length == 0) {\r\n\t\t\t\t\t\t$headerOuterEl.append('<div class=\"bg-color-stripe\" />');\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Prevent jumping on click.\r\n\t\t\t\t\t$body.on('click', '#search-btn a', function () {\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Open search on mouseup.\r\n\t\t\t\t\t$body.on('click', '#search-btn a:not(.inactive), #header-outer .mobile-search', function () {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($(this).hasClass('open-search')) {\r\n\t\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Close menu on original skin.\r\n\t\t\t\t\t\tif( $body.hasClass('original') &&\t$('.slide-out-widget-area-toggle.mobile-icon a.open').length > 0 ) {\r\n\t\t\t\t\t\t\t$('.slide-out-widget-area-toggle.mobile-icon a')\r\n\t\t\t\t\t\t\t\t.addClass('non-human-allowed')\r\n\t\t\t\t\t\t\t\t.trigger('click');\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\t\t\t\t$('.slide-out-widget-area-toggle.mobile-icon a').removeClass('non-human-allowed');\r\n\t\t\t\t\t\t\t\t}, 100);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($body.hasClass('ascend') || \r\n\t\t\t\t\t\t$('body[data-header-format=\"left-header\"]').length > 0 && $('body.material').length == 0) {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t// Ascend theme skin.\r\n\t\t\t\t\t\t\t$('#search-outer > #search form, #search-outer #search .span_12 span, #search-outer #search #close').css('opacity', 0);\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search-outer > #search form').css('transform', 'translateY(-30px)');\r\n\t\t\t\t\t\t\t$('#search-outer #search .span_12 span').css('transform', 'translateY(20px)');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search-outer').show();\r\n\t\t\t\t\t\t\t$('#search-outer').stop().transition({\r\n\t\t\t\t\t\t\t\tscale: '1,0',\r\n\t\t\t\t\t\t\t\t'opacity': 1\r\n\t\t\t\t\t\t\t}, 0).transition({\r\n\t\t\t\t\t\t\t\tscale: '1,1'\r\n\t\t\t\t\t\t\t}, 700, 'cubic-bezier(0.2, 1, 0.3, 1)');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search-outer > #search form').delay(350).transition({\r\n\t\t\t\t\t\t\t\t'opacity': 1,\r\n\t\t\t\t\t\t\t\t'transform': 'translateY(0)'\r\n\t\t\t\t\t\t\t}, 700, 'cubic-bezier(0.2, 1, 0.3, 1)');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search-outer #search #close').delay(500).transition({\r\n\t\t\t\t\t\t\t\t'opacity': 1\r\n\t\t\t\t\t\t\t}, 700, 'cubic-bezier(0.2, 1, 0.3, 1)');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search-outer #search .span_12 span').delay(450).transition({\r\n\t\t\t\t\t\t\t\t'opacity': 1,\r\n\t\t\t\t\t\t\t\t'transform': 'translateY(0)'\r\n\t\t\t\t\t\t\t}, 700, 'cubic-bezier(0.2, 1, 0.3, 1)');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t} \r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\telse if (!$body.hasClass('material')) {\r\n\t\t\t\t\t\t\t// Original theme skin.\r\n\t\t\t\t\t\t\t$('#search-outer').stop(true).fadeIn(600, 'easeOutExpo');\r\n\t\t\t\t\t\t} \r\n\t\t\t\t\t\telse {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t// Material theme skin.\r\n\t\t\t\t\t\t\t$('#header-outer[data-transparent-header=\"true\"] .bg-color-stripe').css('transition', '');\r\n\t\t\t\t\t\t\t$('#search-outer, #ajax-content-wrap').addClass('material-open');\r\n\t\t\t\t\t\t\t$headerOuterEl.addClass('material-search-open');\r\n\t\t\t\t\t\t\t$('#fp-nav').addClass('material-ocm-open');\r\n\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t$('#search input[type=text]').trigger('focus');\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif ($('#search input[type=text]').attr('value') == $placeholder) {\r\n\t\t\t\t\t\t\t\t$('#search input[type=text]').setCursorPosition(0);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t}, 300);\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t$(this).toggleClass('open-search');\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t// Close slide out widget area.\r\n\t\t\t\t\t\t$('.slide-out-widget-area-toggle a:not(#toggle-nav).open:not(.animating)').trigger('click');\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Handle the placeholder value.\r\n\t\t\t\t\t$('body:not(.material)').on('keydown', '#search input[type=text]', function () {\r\n\t\t\t\t\t\tif ($(this).attr('value') == $placeholder) {\r\n\t\t\t\t\t\t\t$(this).attr('value', '');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t$('body:not(.material)').on('keyup', '#search input[type=text]', function () {\r\n\t\t\t\t\t\tif ($(this).attr('value') == '') {\r\n\t\t\t\t\t\t\t$(this).attr('value', $placeholder);\r\n\t\t\t\t\t\t\t$(this).setCursorPosition(0);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Close search btn event.\r\n\t\t\t\t\t$body.on('click', '#close', function () {\r\n\t\t\t\t\t\tcloseSearch();\r\n\t\t\t\t\t\t$searchButtonEl.removeClass('open-search');\r\n\t\t\t\t\t\t$('#header-outer .mobile-search').removeClass('open-search');\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Original and Ascend skin close search when clicking off.\r\n\t\t\t\t\t$('body:not(.material)').on('blur', '#search-box input[type=text]', function () {\r\n\t\t\t\t\t\tcloseSearch();\r\n\t\t\t\t\t\t$searchButtonEl.removeClass('open-search');\r\n\t\t\t\t\t\t$('#header-outer .mobile-search').removeClass('open-search');\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Material skin close when clicking off the search.\r\n\t\t\t\t\t$('body.material').on('click', '#ajax-content-wrap', function (e) {\r\n\t\t\t\t\t\tif (e.originalEvent !== undefined) {\r\n\t\t\t\t\t\t\tcloseSearch();\r\n\t\t\t\t\t\t\t$searchButtonEl.removeClass('open-search');\r\n\t\t\t\t\t\t\t$('#header-outer .mobile-search').removeClass('open-search');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t});\r\n\t\t\t\t\t\r\n\t\t\t\t\t// Material skin close on esc button event.\r\n\t\t\t\t\tif ($('body.material').length > 0) {\r\n\t\t\t\t\t\t$(document).on('keyup', function (e) {\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\tif (e.keyCode == 27) {\r\n\t\t\t\t\t\t\t\tcloseSearch();\r\n\t\t\t\t\t\t\t\t$searchButtonEl.removeClass('open-search');\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\t// Close ocm material\r\n\t\t\t\t\t\t\t\tif ($('.ocm-effect-wrap.material-ocm-open').length > 0) {\r\n\t\t\t\t\t\t\t\t\t$('.slide-out-widget-area-toggle.material-open a').trigger('click');\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\r\n\t\t\t\t\r\n\t\t\t\t\t// Called to hide the search bar.\r\n\t\t\t\t\tfunction closeSearch() {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($body.hasClass('ascend') || $('body[data-header-format=\"left-header\"]').length > 0 && $('body.material').length == 0) {\r\n\t\t\t\t\t\t\t$('#search-outer').stop().transition({\r\n\t\t\t\t\t\t\t\t'opacity': 0\r\n\t\t\t\t\t\t\t}, 300, 'cubic-bezier(0.2, 1, 0.3, 1)');\r\n\t\t\t\t\t\t\t$searchButtonEl.addClass('inactive');\r\n\t\t\t\t\t\t\tsetTimeout(function () {\r\n\t\t\t\t\t\t\t\t$('#search-outer').hide();\r\n\t\t\t\t\t\t\t\t$searchButtonEl.removeClass('inactive');\r\n\t\t\t\t\t\t\t}, 300);\r\n\t\t\t\t\t\t} else if ($('body.material').length == 0) {\r\n\t\t\t\t\t\t\t$('#search-outer').stop(true).fadeOut(450, 'easeOutExpo');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\tif ($body.hasClass('material')) {\r\n\t\t\t\t\t\t\t$('#ajax-content-wrap').removeClass('material-open');\r\n\t\t\t\t\t\t\t$headerOuterEl.removeClass('material-search-open');\r\n\t\t\t\t\t\t\t$('#search-outer').removeClass('material-open');\r\n\t\t\t\t\t\t\t$('#fp-nav').removeClass('material-ocm-open');\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t}", "function init(settings) {\n\n SN.Global.Settings = settings;\n searchBox = $('#search-box');\n bindTemplate();\n bindSearchBoxEvents();\n }", "function searchEventListener() {\n\t$(\"#searchbtn\").click(function() {\n\t\tif ($(\"#searchbox\").val() != '') {\n\t\t\tsearchNewspapers($(\"#searchbox\").val());\n\t\t}\n\t});\n}", "function setup() {\n initializeDatabase(renderBookmarks);\n document.querySelector('input#url').addEventListener('keyup', validateURL);\n document.querySelector('.submit-link-form > form').addEventListener('submit', addLink);\n document.querySelector('.pages').addEventListener('click', handlePageNavClick);\n document.querySelector('.bookmark-list > ul').addEventListener('click', handleBookmarkAction);\n}", "function addEventListeners(){\n document.querySelectorAll(\"[data-action='filter']\").forEach(button => {\n button.addEventListener(\"click\", selectFilter);\n })\n document.querySelectorAll(\"[data-action='sort']\").forEach(button => {\n button.addEventListener(\"click\", selectSorting);\n })\n document.querySelector(\"#searchfunction\").addEventListener(\"input\", search);\n document.querySelector(\".hogwarts\").addEventListener(\"click\", hackTheSystem);\n}", "function gLyphsTrackSearchScripts(trackID, cmd) {\n var glyphTrack = gLyphTrack_array[trackID];\n if(glyphTrack == null) { return; }\n \n var scriptsDiv = document.getElementById(trackID + \"_script_search_div\");\n if(scriptsDiv == null) { return; }\n \n glyphTrack.predef_scripts = new Array();\n\n if(cmd == \"clear\") {\n scriptsDiv.innerHTML = \"please enter search term\";\n return;\n }\n \n if(cmd == \"search\") {\n var seachInput = document.getElementById(trackID + \"_script_search_inputID\");\n var filter = \"\";\n if(seachInput) { filter = seachInput.value; }\n gLyphsFetchPredefinedScripts(trackID, filter);\n }\n\n if(cmd == \"all\") {\n gLyphsFetchPredefinedScripts(trackID, \"\");\n } \n}", "static register() {\n __WEBPACK_IMPORTED_MODULE_2__common_plugin__[\"a\" /* PLUGINS */][\"FullTextSearch\"] = FullTextSearch;\n }", "function init(){\n\t/* white characters detection */\n\taddHandler(tagIn, 'keydown', tagInHandler);\n\taddHandler(favBtn, 'click', favClickHandler);\n\taddLabelHandlers(favs);\n\taddLabelHandlers(tags);\n}", "function startSearchMode ( ) {\r\n searchMode = true;\r\n newOrSubmitButton.innerHTML = searchModeButtonText;\r\n primaryButtonHelp.innerHTML = searchModePrimaryButtonHelp;\r\n secondaryButtonHelp.innerHTML = searchModeSecondaryButtonHelp;\r\n tertiaryButtonHelp.innerHTML = onlyTertiaryButtonHelp;\r\n titleHelp.innerHTML = searchModeTitleHelp;\r\n}", "function initialize() {\n let generateBtn = qs(\"button\");\n generateBtn.addEventListener(\"click\", artistSearch);\n }", "bindHooks() {\n //\n }", "function setupTracking() {\n\t\t\t$('#txt1').focus(function() {\n\t\t\t\tif (this.value == 'keyword'){\n\t\t\t\t\tvar urlresource = window.location.pathname;\n\t\t\t\t\tvar title = $(document).attr(\"title\");\n\t\t\t\t\tvar findchar1 = title.indexOf(\":\");\n\t\t\t\t\tvar findchar2 = title.indexOf(\" - \");\n \n\t\t\t\t\tif (findchar1 != -1) {\n\t\t\t\t\t\tvar category = title.split(': ');\n\t\t\t\t\t\tvar categoryname = category[0];\n\t\t\t\t\t} else if (findchar2 != -1) {\n\t\t\t\t\t\tvar category = title.split(' - ');\n\t\t\t\t\t\tvar categoryname = category[0];\n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar categoryname = title;\n\t\t\t\t\t}\n\n\t\t\t\t\tif ($('body').hasClass('home')) {\n\t\t\t\t\t\tvar labelname = \"Homepage\"; \n\t\t\t\t\t} else {\n\t\t\t\t\t\tvar labelname = categoryname;\n\t\t\t\t\t}\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Search Start\", labelname);\n\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t});\n\n\t\t\t$(\"#search-form input[value='Search']\").each(function() {\n\t\t\t\t$(this).click(function() {\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Search Go\", value);\n\t\t\t\t\tsetTimeout($(this).closest(\"form\").submit(), 800);\n\t\t\t\t\t\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t $(\"#searchresults\").each(function() {\n\t\t\t\t$(\"#googleresults a\").live(\"click\", function(){\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Results Click\", value);\n\t\t\t\t\tsetTimeout('document.location = \"' + $(this).attr(\"href\") + '\"', 400);\n\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\n\t\t\t\t$(\"#ldapresults a\").live(\"click\", function(){\n\t\t\t\t\tvar value = $('#txt1').attr('value');\n\n\t\t\t\t\ttrack_event_to_google(\"Dropdown Search\", \"Directory Click\", value);\n\n\t\t\t\t\treturn false;\n\t\t\t\t});\n\t\t\t});\n\n\t\t\t$(\"#content div input[type='submit']\").each(function() {\n\t\t\t\t$(this).click(function() {\n\t\t \t\turlresource = window.location.pathname;\n\t\t\t\t\tformval = $(\"input[name='success-redirect']\").attr(\"value\");\n\t\t\t\t\temailval = $(\"input[name='email-recipients']\").attr(\"value\");\n\t\t\t\t\t\n\t\t\t\t\tif (emailval) {\n\t\t\t\t\t\tif (formval) {\n\t\t\t\t\t\t\tcurrentpage = urlresource+'?type=submit&success-redirect='+formval;\n\t \t} else {\n\t\t\t\t\t\t\tcurrentpage = urlresource+'?type=submit&success-redirect=';\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tpageTracker._trackPageview(currentpage);\n\t\t\t\t\t\tsetTimeout($(this).closest(\"form\").submit(), 600);\n\n \t return false;\n\t\t\t\t\t} \n\t \t });\n \t });\n\n\t\t\t$(\"#col1 a\").each(function() {\n\t\t\t\t\t\t href = $(this).attr(\"href\");\n\n\t\t\t\t\t\t if (href != null && href != \"\") {\n\t\t\t\t\t\t \n\t\t\t\t\t\t patternhttp = /^https?:\\/\\//i;\n\t\t\t\t\t\t patternwpi = /^https?:\\/\\/.*\\.wpi\\.edu/;\n\t\t\t\t\t\t patternpdf = /pdf$/i;\n\n\t\t\t\t\t\t if (href.match(patternhttp) && !href.match(patternwpi)) {\n\t\t\t\t\t\t\t //click offsite\n\t\t\t\t\t\t\t $(this).click(function() {\n\t\t\t\t\t\t\t\t\t title = $(document).attr(\"title\");\n findchar1 = title.indexOf(\":\");\n findchar2 = title.indexOf(\" - \");\n \n if (findchar1 != -1) {\n category = title.split(': ');\n categoryname = category[0];\n } else if (findchar2 != -1) {\n category = title.split(' - ');\n categoryname = category[0];\n } else {\n categoryname = title;\n }\n\n\t\t\t\t\t\t\t\t\t track_event_to_google(categoryname, \"Offsite Link\", $(this).attr(\"href\"));\n\t\t\t\t\t\t\t\t\t setTimeout('document.location = \"' + $(this).attr(\"href\") + '\"', 400);\n\n\t\t\t\t\t\t\t\t\t return false;\n\t\t\t\t\t\t\t\t });\n\t\t\t\t\t\t } else if (href.match(patternpdf) && href.match(patternwpi)) {\n\t\t\t\t\t\t\t //pdf\n\t\t\t\t\t\t\t $(this).click(function() {\n\t\t\t\t\t\t\t\t\t fullurl = $(this).attr(\"href\");\n\n\t\t\t\t\t\t\t\t\t urlvalue = fullurl.split('/');\n\t\t\t\t\t\t\t\t\t urlvalue1 = urlvalue[0];\n\t\t\t\t\t\t\t\t\t urlvalue2 = '//';\n\t\t\t\t\t\t\t\t\t urlvalue3 = urlvalue[2];\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t url1 = urlvalue1 + urlvalue2 + urlvalue3;\n\t\t\t\t\t\t\t\t\t url2 = fullurl.replace(url1,'')\n\n\t\t\t\t\t\t\t\t\t pageTracker._trackPageview(url2);\n\t\t\t\t\t\t\t\t\t setTimeout('document.location = \"' + fullurl + '\"', 75);\n\n\t\t\t\t\t\t\t\t\t return false;\n\t\t\t\t\t\t\t });\n\t\t\t\t\t\t }\n\t\t\t\t\t\t }\n\t\t\t});\n\t\t}", "function redirectSearches(){\r\n\t\r\n\tvar searchList = getUrlParameter(\"search\");\r\n\tvar eventAddress = getUrlParameter(\"event\");\r\n\tvar isManual = getUrlParameter(\"manual\");\r\n\t\r\n\t\r\n\t//Nearby Search\r\n\tif (searchList != undefined && eventAddress == undefined){\r\n\t\tsearchMap(searchList,false);\r\n\t}\r\n\t\r\n\t//Address Search\r\n\tif (searchList != undefined && searchList != \"None Given\" && eventAddress == \"true\"){\r\n\t\tsearchMap(searchList,true);\r\n\t}\r\n\t\r\n\t//Manual Lists\r\n\tif (searchList != undefined && eventAddress == undefined && isManual ==\"true\"){\r\n\t\tgetList(searchList);\r\n\t}\r\n\t\r\n\t//Load Address Book\r\n\t//loadAddressList(); Thynote: on click for tab now \r\n}", "componentDidMount() {\n this.useSearchEngine();\n \n }", "function gLyphsTrackSearchScripts(trackID, cmd) {\n var glyphTrack = glyphsTrack_global_track_hash[trackID];\n if(glyphTrack == null) { return; }\n \n var scriptsDiv = document.getElementById(trackID + \"_script_search_div\");\n if(scriptsDiv == null) { return; }\n \n glyphTrack.predef_scripts = new Array();\n\n if(cmd == \"clear\") {\n scriptsDiv.innerHTML = \"please enter search term\";\n return;\n }\n \n if(cmd == \"search\") {\n var seachInput = document.getElementById(trackID + \"_script_search_inputID\");\n var filter = \"\";\n if(seachInput) { filter = seachInput.value; }\n gLyphsFetchPredefinedScripts(trackID, filter);\n }\n\n if(cmd == \"all\") {\n gLyphsFetchPredefinedScripts(trackID, \"\");\n } \n}", "function setSearch()\n {\n let busqueda = $j('#checkPersonalizada')\n busqueda.on('change', (e) =>\n {\n if (this.customSearch == false)\n {\n this.customSearch = true\n }\n else\n {\n this.customSearch = false\n }\n $j('#personalizada').toggleClass('invisible')\n })\n }", "function onPageCreate(e){\n\t\t\t\t\t\t\t\t\n\t\t\t\t//getSearchOpts\n\t\t\t\tApp.data.getSearchOpts();\n\t\t\t\t\t\t\t\t\t\t\n\t\t\t}", "function initialize_poolTool_search(){\n // get url params\n var listing_id = getUrlParameter('listing_id');\n if (typeof listing_id !== \"undefined\"){\n $('#poolTool_search').val(\"LID=\" + listing_id);\n search(\"LID=\" + listing_id);\n $('#addNewBooking').click();\n }\n\n var booking_id = getUrlParameter('booking_id');\n if (typeof booking_id !== \"undefined\"){\n $('#poolTool_search').val(\"BID=\" + booking_id);\n search(\"BID=\" + booking_id);\n }\n\n\n // if user searches\n $('#poolTool_search').keyup(function(){\n var value = $('#poolTool_search').val();\n\n clearTimeout(searchTimeout);\n\n searchTimeout = setTimeout(function(){\n search(value);\n }, 700);\n });\n\n // remove search text\n $('#remove_search').click(function(){\n $('#poolTool_search').val(\"\");\n search(\"\");\n });\n }", "function initializeListeners(){\n $('.createGame').on('click', launchGameCreation);\n $('.search').on('input', function(){\n showSearchResults($(this).val());\n });\n\n}", "function setupListeners() {\n setupAppHomeOpenedListener();\n setupClearGoalsButtonListener();\n}", "function setSearch() {\r\n\tconst btn=document.querySelector('#searchbtn');\r\n\tbtn.addEventListener('click', searchCraft);\r\n\tconst bar = document.querySelector('#searchbar');\r\n\tbar.addEventListener(\"keyup\", function(event) {\r\n if (event.key === \"Enter\"|event.keyCode === 13) {\r\n searchCraft(event);\r\n\t }\r\n\t});\r\n}", "function _mod_search() {\n\t\"use strict\";\n\t// private section - following fields and functions are private and need to be accessed by methods provided in the public section\n\tvar _inputId;\n\tvar autoComplete = {};\n\n\tautoComplete.suggestion = {};\n\tautoComplete.suggestion.tags = [];\n\tautoComplete.suggestion.id = [];\n\tautoComplete.dictionaryTags = [];\n\n\t/****\n\t * create a completely new tag\n\t * @param id of the corresponding html list element\n\t * @param tag to be linked to the id\n\t * @return {Object}\n\t */\n\tfunction newIdTagPair(id, tag) {\n\t\tvar liElem = {};\n\t\tliElem.id = id;\n\t\tliElem.tags = [];\n\t\tliElem.tags.push(tag);\n\t\treturn liElem;\n\t}\n\n\t/****\n\t * filters a list while typing text into an input field and hides all\n\t * list items that don't match to the search string.\n\t * @param searchStr string that is currently in the search field (others would be possible to, but mostly senseless)\n\t * @param listRootId list to be filterd\n\t */\n\tfunction searchFilter(searchStr, listRootId) {\n\t\tvar match;\n\t\tvar searchIndex;\n\t\tvar i, j;\n\t\tvar nodeJQ;\n\t\tvar visibleNodes = [];\n\n\t\t// show all\n\t\tif (!searchStr || searchStr === \"\") {\n\t\t\tjQuery(\"#\" + listRootId).find(\"li\").andSelf().show();\n\t\t}\n\n\t\tsearchStr = searchStr.toLowerCase();\n\n\n\t\t// hide all nodes while traversing\n\t\t// not to nice implemented ;)\n\t\tfor (i = autoComplete.dictionaryTags.length - 1; i >= 0; i--) {\n\t\t\tnodeJQ = jQuery(\"#\" + autoComplete.dictionaryTags[i].id);\n\t\t\t//console.log(autoComplete.dictionaryTags[i].tags[0])\n\t\t\tmatch = null;\n\t\t\tfor (j = 0; j < autoComplete.dictionaryTags[i].tags.length; j++) {\n\t\t\t\tsearchIndex = autoComplete.dictionaryTags[i].tags[j].toLowerCase().match(searchStr);\n\t\t\t\tif (searchIndex) {\n\t\t\t\t\tmatch = nodeJQ;\n\t\t\t\t\t//select node in tree to highlight\n\t\t\t\t\tif (searchIndex === 0 && autoComplete.dictionaryTags[i].tags[j].length === searchStr.length) {\n\t\t\t\t\t\tMYAPP.tree.select_node(jQuery(\"#\" + autoComplete.dictionaryTags[i].id));\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnodeJQ.hide();\n\n\t\t\tif (match) {\n\t\t\t\tvisibleNodes.push(match);\n\t\t\t}\n\t\t}\n\n\t\t// show matching nodes and all their parents\n\t\t// !!! todo: the method parents gos up to the html root but it should stop at the top of the list\n\t\tfor (i = visibleNodes.length - 1; i >= 0; i--) {\n\t\t\tvisibleNodes[i].parents(\"#treeList li\").andSelf().show();\n\t\t}\n\t}\n\n\t// private section END\n\n\n\t// public section\n\t// all methods that give access to the private fields and allow to process the menu\n\treturn {\n\t\t/****\n\t\t * @param treeRootId\n\t\t * id of the root of the list that should be filtered\n\t\t * @param inputId\n\t\t * id of the input field in witch should get the autocompleate function\n\t\t * @param dictionaryTags\n\t\t * an array that looks as followed:\n\t\t * [ { id: ... , tags: [..., ...]}, { id: ... , tags: [..., ...]} ]\n\t\t * the id is the id of the li element that should be processed,\n\t\t * the tag is an array with corresponding strings (if the search string matches\n\t\t * any of the tag string or tag substring in any position the li element is displayed.\n\t\t * if there is no match at all the li element will be hidden.\n\t\t *\n\t\t */\n\t\tinitSearch : function (treeRootId, inputId, dictionaryTags) {\n\t\t\tvar i, j;\n\n\t\t\tdictionaryTags = dictionaryTags || [];\n\t\t\t_inputId = inputId;\n\t\t\tautoComplete.dictionaryTags = dictionaryTags;\n\n\t\t\tfor (i = 0; i < dictionaryTags.length; i++) {\n\t\t\t\tfor (j = 0; j < dictionaryTags[i].tags.length; j++) {\n\t\t\t\t\tautoComplete.suggestion.tags.push(dictionaryTags[i].tags[j]);\n\t\t\t\t\tautoComplete.suggestion.id.push(dictionaryTags[i].id);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tjQuery(\"#\" + inputId).autocomplete({\n\t\t\t\tsource : autoComplete.suggestion.tags,\n\t\t\t\tselect : function (event, ui) {\n\t\t\t\t\tif (ui.item) {\n\t\t\t\t\t\tvar i = jQuery.inArray(ui.item.value, autoComplete.suggestion.tags);\n\t\t\t\t\t\tvar node = jQuery(\"#\" + autoComplete.suggestion.id[i]);\n\t\t\t\t\t\tMYAPP.tree.select_node(node);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\talert(\"Dieses Element ist im Objekt nicht enthalten.\");\n\t\t\t\t\t}\n\t\t\t\t\t//alert(ui.item ? ui.item.value: \"Nothing selected, input was \" + this.value );\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tjQuery(\"#\" + inputId).keyup(function () {\n\t\t\t\t//alert(\"\")\n\t\t\t\tsearchFilter(jQuery(\"#\" + inputId).val(), treeRootId);\n\t\t\t});\n\t\t\t// filter when x is pressed\n\t\t\tjQuery(\"#\" + inputId).parent().children(\".ui-input-clear\").mouseup(function () {\n\t\t\t\tsearchFilter(\"\", treeRootId);\n\t\t\t});\n\n\t\t},\n\t\t/****\n\t\t * push a new tag to the data set that is used to filter the html list\n\t\t * and to the data set that is the base for the autoComplete suggestions\n\t\t * @param id of the corresponding list element\n\t\t * @param tag that is being linked to the tag\n\t\t */\n\t\tpushTag : function (id, tag) {\n\t\t\tvar i;\n\t\t\tvar index = -1;\n\n\t\t\t//console.log(\" id \" + id + \" tag \" + tag + \" _inputId \" + _inputId)\n\t\t\tif (typeof id !== \"string\" || typeof tag !== \"string\") {\n\t\t\t\tconsole.error(\"data to push are not valid (mod_search->method pushTag(id, tag)\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (i = 0; i < autoComplete.dictionaryTags.length; i++) {\n\t\t\t\tif (autoComplete.dictionaryTags[i].id.match(id)) {\n\t\t\t\t\tindex = i;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (-1 < index) { // element with the submitted id already exists\n\t\t\t\tautoComplete.dictionaryTags[index].tags.push(tag);\n\t\t\t\t/*\n\t\t\t\t console.log(\n\t\t\t\t autoComplete.dictionaryTags[index].id[0] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].tags[0] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].id[1] + \" --- \" +\n\t\t\t\t autoComplete.dictionaryTags[index].tags[1]\n\t\t\t\t )\n\t\t\t\t */\n\t\t\t}\n\t\t\telse { // create new entry\n\t\t\t\tautoComplete.dictionaryTags.push(newIdTagPair(id, tag));\n\t\t\t\t//console.log(newIdTagPair(id, tag).id + \" --- \" + autoComplete.dictionaryTags[testI].id + \" --- \" + autoComplete.dictionaryTags[testI].tags[0] )\n\t\t\t}\n\n\t\t\tautoComplete.suggestion.tags.push(tag);\n\t\t\tautoComplete.suggestion.id.push(id);\n\n\t\t\t//console.log( autoComplete.suggestion.id[testI] + \" --- \" + autoComplete.suggestion.tags[testI] ) ;\n\t\t\t//console.log( id + \" --- \" + tag ) ;\n\n\t\t\tjQuery(\"#\" + _inputId).autocomplete('option', 'source', autoComplete.suggestion.tags);\n\t\t}\n\t};\n\t// public section END (return end)\n}", "function initSearchButton(){\n\n\tif($j('.search_slides_from_window_top').length){\n\t\t$j('.search_slides_from_window_top').click(function(e){\n\t\t\te.preventDefault();\n\n\t\t\tif($j('html').hasClass('touch')){\n\t\t\t\tif ($j('.qode_search_form').height() == \"0\") {\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').onfocus = function () {\n\t\t\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t\t\t\tdocument.body.scrollTop = 0;\n\t\t\t\t\t};\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').onclick = function () {\n\t\t\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t\t\t\tdocument.body.scrollTop = 0;\n\t\t\t\t\t};\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','50px');\n\t\t\t\t\t$j('.qode_search_form').css('height','50px');\n\t\t\t\t\t$j('.content_inner').css('margin-top','50px');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top','0'); }\n\t\t\t\t} else {\n\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top',-$scroll);}\n\t\t\t\t}\n\n\t\t\t\t$j(window).scroll(function() {\n\t\t\t\t\tif ($j('.qode_search_form').height() != \"0\" && $scroll > 50) {\n\t\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t$j('.qode_search_close').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form').css('height','0');\n\t\t\t\t\t$j('.header_top_bottom_holder').css('top','0');\n\t\t\t\t\t$j('.content_inner').css('margin-top','0');\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').css('top',-$scroll);}\n\t\t\t\t});\n\n\t\t\t} else {\n\t\t\t\tif($j('.title').hasClass('has_fixed_background')){\n\t\t\t\t\tvar yPos = parseInt($j('.title.has_fixed_background').css('backgroundPosition').split(\" \")[1]);\n\t\t\t\t}else { \n\t\t\t\t\tvar yPos = 0;\n\t\t\t\t}\n\t\t\t\tif ($j('.qode_search_form').height() == \"0\") {\n\t\t\t\t\t$j('.qode_search_form input[type=\"text\"]').focus();\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"50px\"},150);\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"50px\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"50px\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:0},150); }\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos + 50)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t} else {\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:-$scroll},150);}\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos - 50)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t}\n\n\t\t\t\t$j(window).scroll(function() {\n\t\t\t\t\tif ($j('.qode_search_form').height() != \"0\" && $scroll > 50) {\n\t\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\t\t$j('.title.has_fixed_background').css('backgroundPosition', 'center '+(yPos)+'px');\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t\t$j('.qode_search_close').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form').stop().animate({height:\"0\"},150);\n\t\t\t\t\t$j('.content_inner').stop().animate({marginTop:\"0\"},150);\n\t\t\t\t\t$j('.header_top_bottom_holder').stop().animate({top:\"0px\"},150);\n\t\t\t\t\tif($scroll < 34){ $j('header.page_header').stop().animate({top:-$scroll},150);}\n\t\t\t\t\t$j('.title.has_fixed_background').animate({\n\t\t\t\t\t\t'background-position-y': (yPos)+'px'\n\t\t\t\t\t}, 150);\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t}\n\t\n\t//search type - search_slides_from_header_bottom\n if($j('.search_slides_from_header_bottom').length){\n\n $j('.search_slides_from_header_bottom').click(function(e){\n\n e.preventDefault();\n\n if($j('.qode_search_form_2').hasClass('animated')) {\n $j('.qode_search_form_2').removeClass('animated');\n $j('.qode_search_form_2').css('bottom','0');\n } else {\n $j('.qode_search_form input[type=\"text\"]').focus();\n $j('.qode_search_form_2').addClass('animated');\n var search_form_height = $j('.qode_search_form_2').height();\n $j('.qode_search_form_2').css('bottom',-search_form_height);\n\n }\n\n $j('.qode_search_form_2').addClass('disabled');\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n if(($j('.qode_search_form_2 .qode_search_field').val() !== '') && ($j('.qode_search_form_2 .qode_search_field').val() !== ' ')) {\n $j('.qode_search_form_2 input[type=\"submit\"]').removeAttr('disabled');\n $j('.qode_search_form_2').removeClass('disabled');\n }\n else {\n $j('.qode_search_form_2').addClass('disabled');\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n }\n\n $j('.qode_search_form_2 .qode_search_field').keyup(function() {\n if(($j(this).val() !== '') && ($j(this).val() != ' ')) {\n $j('.qode_search_form_2 input[type=\"submit\"]').removeAttr('disabled');\n $j('.qode_search_form_2').removeClass('disabled');\n }\n else {\n $j('.qode_search_form_2 input[type=\"submit\"]').attr('disabled','disabled');\n $j('.qode_search_form_2').addClass('disabled');\n }\n });\n\n\n $j('.content, footer').click(function(e){\n e.preventDefault();\n $j('.qode_search_form_2').removeClass('animated');\n $j('.qode_search_form_2').css('bottom','0');\n });\n\n });\n }\n\n //search type - search covers header\n if($j('.search_covers_header').length){\n\n $j('.search_covers_header').click(function(e){\n\n e.preventDefault();\n if($j(\".search_covers_only_bottom\").length){\n var headerHeight = $j('.header_bottom').height();\n }\n else{\n if($j(\".fixed_top_header\").length){\n var headerHeight = $j('.top_header').height();\n }else{\n var headerHeight = $j('.header_top_bottom_holder').height();\n }\n }\n\n\t\t\t$j('.qode_search_form_3 .form_holder_outer').height(headerHeight);\n\n if($j(\".search_covers_only_bottom\").length){\n $j('.qode_search_form_3').css('bottom',0);\n $j('.qode_search_form_3').css('top','auto');\n }\n\t\t\t$j('.qode_search_form_3').stop(true).fadeIn(600,'easeOutExpo');\n\t\t\t$j('.qode_search_form_3 input[type=\"text\"]').focus();\n\n\n\t\t\t$j(window).scroll(function() {\n if($j(\".search_covers_only_bottom\").length){\n var headerHeight = $j('.header_bottom').height();\n }\n else{\n if($j(\".fixed_top_header\").length){\n var headerHeight = $j('.top_header').height();\n }else{\n var headerHeight = $j('.header_top_bottom_holder').height();\n }\n }\n\t\t\t\t$j('.qode_search_form_3 .form_holder_outer').height(headerHeight);\n\t\t\t});\n\n\t\t\t$j('.qode_search_close, .content, footer').click(function(e){\n\t\t\t\t\te.preventDefault();\n\t\t\t\t\t$j('.qode_search_form_3').stop(true).fadeOut(450,'easeOutExpo');\n\t\t\t});\n\n\t\t\t$j('.qode_search_form_3').blur(function(e){\n\t\t\t\t\t$j('.qode_search_form_3').stop(true).fadeOut(450,'easeOutExpo');\n\t\t\t});\n });\n }\n\t\t\n//search type - fullscreen search\n if($j('.fullscreen_search').length){\n\t\t//search type Circle Appear\n\t\tif($j(\".fullscreen_search_holder.from_circle\").length){\n\t\t\t$j('.fullscreen_search').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tif($j('.fullscreen_search_overlay').hasClass('animate')){\n\t\t\t\t\t$j('.fullscreen_search_overlay').removeClass('animate');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('opacity','0');\n\t\t\t\t\t$j('.fullscreen_search_close').css('opacity','0');\n\t\t\t\t\t$j('.fullscreen_search_close').css('visibility','hidden');\n\t\t\t\t\t$j('.fullscreen_search').css('opacity','1');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('display','none');\n\t\t\t\t} else {\n\t\t\t\t\t$j('.fullscreen_search_overlay').addClass('animate');\n\t\t\t\t\t$j('.fullscreen_search_holder').css('display','block');\n\t\t\t\t\tsetTimeout(function(){\n\t\t\t\t\t\t$j('.fullscreen_search_holder').css('opacity','1');\n\t\t\t\t\t\t$j('.fullscreen_search_close').css('opacity','1');\n\t\t\t\t\t\t$j('.fullscreen_search_close').css('visibility','visible');\n\t\t\t\t\t\t$j('.fullscreen_search').css('opacity','0');\n\t\t\t\t\t},200);\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t\t$j('.fullscreen_search_close').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\t$j('.fullscreen_search_overlay').removeClass('animate');\n\t\t\t\t$j('.fullscreen_search_holder').css('opacity','0');\n\t\t\t\t$j('.fullscreen_search_close').css('opacity','0');\n\t\t\t\t$j('.fullscreen_search_close').css('visibility','hidden');\n\t\t\t\t$j('.fullscreen_search').css('opacity','1');\n\t\t\t\t$j('.fullscreen_search_holder').css('display','none');\n\t\t\t\t\n\t\t\t});\n\t\t}\n\t\t//search type Fade Appear\n\t\tif($j(\".fullscreen_search_holder.fade\").length){\n\t\t\t$j('.fullscreen_search').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\tif($j('.fullscreen_search_holder').hasClass('animate')) {\n\t\t\t\t\t$j('body').removeClass('fullscreen_search_opened');\n\t\t\t\t\t$j('.fullscreen_search_holder').removeClass('animate');\n\t\t\t\t\t$j('body').removeClass('search_fade_out');\n\t\t\t\t\t$j('body').removeClass('search_fade_in');\n\t\t\t\t\t\n\t\t\t\t} else {\n\t\t\t\t\t$j('body').addClass('fullscreen_search_opened');\n\t\t\t\t\t$j('body').removeClass('search_fade_out');\n\t\t\t\t\t$j('body').addClass('search_fade_in');\n\t\t\t\t\t$j('.fullscreen_search_holder').addClass('animate');\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\t});\n\t\t\t$j('.fullscreen_search_close').on('click',function(e){\n\t\t\t\te.preventDefault();\n\t\t\t\t$j('body').removeClass('fullscreen_search_opened');\n\t\t\t\t$j('.fullscreen_search_holder').removeClass('animate');\n\t\t\t\t$j('body').removeClass('search_fade_in');\n\t\t\t\t$j('body').addClass('search_fade_out');\n\t\t\t\t\n\t\t\t});\n\t\t}\n\t\t\n\t\t//Text input focus change\n\t\t$j('.fullscreen_search_holder .search_field').focus(function(){\n\t\t\t$j('.fullscreen_search_holder .field_holder .line').css(\"width\",\"100%\");\n\t\t});\n\t\t\n\t\t$j('.fullscreen_search_holder .search_field').blur(function(){\n\t\t\t$j('.fullscreen_search_holder .field_holder .line').css(\"width\",\"0\");\n\t\t});\n\t\t\n\t\t//search close button - setting its position vertically\n\t\t$j(window).scroll(function() {\n\t\t\tvar bottom_height = $j(\".page_header .header_bottom\").height();\n\t\t\tif($j(\".page_header\").hasClass(\"sticky\")){\n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",bottom_height);\n\t\t\t\t$j(\".fullscreen_search_holder .close_container\").css(\"top\",\"0\");\n\t\t\t} else if($j(\".page_header\").hasClass(\"fixed\")){ \n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",bottom_height);\n\t\t\t} else {\n\t\t\t\t$j(\".fullscreen_search_holder .side_menu_button\").css(\"height\",\"\");\n\t\t\t\t$j(\".fullscreen_search_holder .close_container\").css(\"top\",\"\");\n\t\t\t}\n\t\t});\n }\n\n if($j('.qode_search_submit').length) {\n $j('.qode_search_submit').click(function(e) {\n e.preventDefault();\n e.stopPropagation();\n\n var searchForm = $j(this).parents('form').first();\n\n searchForm.submit();\n });\n }\n\t\n}", "function configureSearchMouseScrolling()\n{\n //simulated touch (ie. mouse) dragging for results\n document.getElementById('search-results')\n .addEventListener('mousedown', mousedownForSearchResults, false);\n \n document.getElementById('search-results')\n .addEventListener('mousemove', mousemoveForSearchResults, false);\n \n document.getElementById('search-results')\n .addEventListener('mouseup', mouseupForSearchResults, false);\n}", "registerHooks() {\n this.addLocalHook('click', () => this.onClick());\n this.addLocalHook('keyup', event => this.onKeyup(event));\n }", "function setUpSearchEpisodesEventListener(data) {\n searchBar.addEventListener(\"keyup\", (event) => searchEpisodes(data, event));\n}", "function search() {\n\t\n}", "function searchButtonSwitchMode (e) {\n//console.log(\"searchButtonHandler event: \"+e.type+\" button: \"+e.button+\" phase: \"+e.eventPhase);\n if (e.button == 1) {\n\tswitch (options.searchFilter) {\n\t case \"all\":\n\t\tsetSFilterFldrOnlyHandler();\n\t break;\n\t case \"fldr\":\n\t\toptions.searchField = \"both\"; // Reset which parts a search is made on to title + url\n\t\tsetSFilterBkmkOnlyHandler();\n\t\tbreak;\n\t case \"bkmk\":\n\t\tsetSFilterAllHandler();\n\t\tbreak;\n\t}\n }\n}", "function init() {\n id(\"find-btn\").addEventListener(\"click\", getData);\n id(\"back-btn\").addEventListener(\"click\", goBack);\n fetch(URL_BASE)\n .then(checkStatus)\n .then(response => response.json())\n .then(addSelection)\n .catch(handleError);\n }", "function searchCall() {\n $('#searchButton').click(function () {\n var qString = $('#searchInput').val();\n bindSearchUrl(qString);\n });\n\n $('#searchInput').keypress(keypressHandler);\n }", "function searchPage_elementsExtraJS() {\n // screen (searchPage) extra code\n /* useProfileToggle */\n $(\"#searchPage_useProfileToggle\").parent().find(\".ui-flipswitch-on\").attr(\"tabindex\", \"1\");\n /* useLocationToggle */\n $(\"#searchPage_useLocationToggle\").parent().find(\".ui-flipswitch-on\").attr(\"tabindex\", \"4\");\n /* distanceSelect */\n $(\"#searchPage_distanceSelect\").parent().find(\"a.ui-btn\").attr(\"tabindex\", \"9\");\n /* ingredientPopup */\n $(\"#searchPage_ingredientPopup\").popup(\"option\", \"positionTo\", \"window\");\n /* distancePopup */\n $(\"#searchPage_distancePopup\").popup(\"option\", \"positionTo\", \"window\");\n /* ratingPopup */\n $(\"#searchPage_ratingPopup\").popup(\"option\", \"positionTo\", \"window\");\n /* cuisinePopup */\n $(\"#searchPage_cuisinePopup\").popup(\"option\", \"positionTo\", \"window\");\n /* pricePopup */\n $(\"#searchPage_pricePopup\").popup(\"option\", \"positionTo\", \"window\");\n /* dietaryPopup */\n $(\"#searchPage_dietaryPopup\").popup(\"option\", \"positionTo\", \"window\");\n /* loginPopup */\n $(\"#searchPage_loginPopup\").popup(\"option\", \"positionTo\", \"window\");\n }", "function basicsearch() {\n searchString = document.basicForm.basicText.value;\n searchTerms = searchString.split(/\\s/);\n\n putHeader();\n\n findResults();\n putResults();\n\n putFooter();\n\n writeResultsPage();\n}", "function Engange() {\n switch (p.Current) {\n case 'herbIndexPAGE':\n run(func.lazyLoad);\n run(func.searchAllHerbs, 'herbIndexPAGE');\n break;\n case 'herbShowPAGE':\n run(func.lazyLoad);\n run(func.searchAllHerbs, 'herbShowPAGE');\n run(func.showdownINIT);\n run(func.markdown);\n run(func.sectionTOGGLE);\n break;\n case 'aboutPAGE':\n run(func.lazyLoad);\n run(func.searchAllHerbs, 'aboutPAGE');\n break;\n }\n}", "function setup () {\n app.set('visitHome', visitHome)\n app.set('visitConnect', visitConnect)\n app.set('visitGame', visitGame)\n }", "function init() {\r\n id(\"color\").addEventListener(\"click\", changeColor);\r\n id(\"searchButton\").addEventListener(\"click\", fetchTheData);\r\n }", "function manageSearchTextHandler () {\n let value = SearchTextInput.value;\n\n // Clear input timeout if there was one active\n if (inputTimeout != null) {\n\tclearTimeout(inputTimeout);\n }\n\n /*\n * Set the cancel text image, and enable or disable it based on:\n * - 0 character = no image, disabled\n * - 1 or more character(s) = set the cancel image, enable the button\n */\n if (value.length > 0) {\n\tif (!options.searchOnEnter) { // Auto trigger search when no more key typed in\n\t // Set timeout before triggering / updating search mode\n\t inputTimeout = setTimeout(updateSearch, InputKeyDelay);\n\t}\n\tenableExecuteSearch();\n }\n else { // Clear search mode\n\tinputTimeout = null; // We just cleared any last timeout, so set to null\n\n\t// Remember search pane height if needed, before closing it\n\tlet sh = SearchResult.style.height; \n\tif (sh != \"\") { // The search result pane size is different\n\t \t\t\t\t// from its default value set in the CSS\n\t \t\t\t\t// which is 20% (as seen in Computed Style)\n\t if (options.rememberSizes) {\n\t\tif (options.searchHeight != sh) { // Save only if different from already saved\n\t\t options.searchHeight = sh;\n\t\t browser.storage.local.set({\n\t\t\tsearchheight_option: sh\n\t\t })\n\t\t .then(\n\t\t\tfunction () {\n\t\t\t // Signal change to all\n\t\t\t sendAddonMessage(\"savedOptions\");\n\t\t\t}\n\t\t );\n\t\t}\n\t }\n\t}\n\tdisableCancelSearch();\n\n\t// Discard the results table if any\n\tif (resultsTable != null) {\n\t SearchResult.removeChild(resultsTable);\n\t resultsTable = null;\n//\t resultsFragment = null;\n\t curResultRowList = {};\n\t}\n\n\t// If a row was highlighted, do not highlight it anymore\n//\tclearCellHighlight(rcursor, rlastSelOp, rselection.selectIds);\n\tcancelCursorSelection(rcursor, rselection);\n\n\t// Restore bookmarks tree to its initial visibility state\n\tresetTreeVisiblity();\n }\n}", "function appsSearch() {\n\n\n var _search_input = ga('#s_search');\n var _input_timeout;\n\n var _searchGetResult = function(_this) {\n\n if($.trim(_this.val())) {\n ga('#apps_search').removeClass('ui_search_field_empty').addClass('ui_search_loading');\n var _by_genre = _this.data('searcgcateg');\n var send = jAjax('/cmd.php', 'post', 'cmd=searchInApps&genre=' + escape(_by_genre) + '&key=' + _this.val());\n send.done(function(data) {\n ga('#apps_search').removeClass('ui_search_loading');\n if(data === '0') {\n\n return displayErr(lang.err_tehnic);\n\n } else {\n\n ga('.apps_list_content').hide();\n\n ga('#apps_search_res').remove();\n ga('.apps_list_content').after(data);\n\n }\n });\n\n } else {\n ga('#apps_search').addClass('ui_search_field_empty');\n ga('#apps_search_res').remove();\n ga('.apps_list_content').show();\n }\n\n }\n\n\n _search_input.off('keyup.appsSearch').on('keyup.appsSearch', function(e) {\n e.preventDefault();\n e.stopPropagation();\n var _this = ga(this);\n clearTimeout(_input_timeout);\n _input_timeout = setTimeout(function() {\n clearTimeout(_input_timeout);\n _searchGetResult(ga(_this));\n }, 500);\n\n });\n _search_input.off('keypress.appsSearch,keydown.appsSearch').on('keypress.appsSearch,keydown.appsSearch', function(e) {\n\n clearTimeout(_input_timeout);\n });\n}", "function gLyphsSearchInterface(glyphsGB) {\n if(zenbu_embedded_view) { return; }\n if(!glyphsGB) { return; }\n if(!glyphsGB.main_div) { return; }\n\n if(!glyphsGB.searchFrame) { \n glyphsGB.searchFrame = document.createElement('div');\n if(glyphsGB.main_div.firstChild) {\n glyphsGB.main_div.insertBefore(glyphsGB.searchFrame, glyphsGB.main_div.firstChild);\n } else {\n glyphsGB.main_div.appendChild(glyphsGB.searchFrame);\n }\n }\n if(!glyphsGB.searchInput) { \n var searchInput = document.createElement(\"input\");\n glyphsGB.searchInput = searchInput;\n searchInput.type = \"text\";\n searchInput.className = \"sliminput\";\n searchInput.autocomplete = \"off\";\n searchInput.default_message = \"search for annotations (eg EGR1 or kinase) or set location (eg: chr19:36373808-36403118)\";\n searchInput.onkeyup = function(evnt) { glyphsMainSearchInput(glyphsGB, this.value, evnt); } \n searchInput.onclick = function() { gLyphsClearDefaultSearchMessage(glyphsGB); }\n searchInput.onfocus = function() { gLyphsClearDefaultSearchMessage(glyphsGB); }\n searchInput.onblur = function() { gLyphsSearchUnfocus(glyphsGB); }\n //searchInput.onmouseout = function() { gLyphsSearchUnfocus(glyphsGB); } \n searchInput.value = searchInput.default_message; \n searchInput.style.color = \"lightgray\";\n searchInput.show_default_message = true;\n }\n if(!glyphsGB.searchResults) { \n glyphsGB.searchResults = document.createElement('div');\n glyphsGB.searchResults.glyphsGB = glyphsGB;\n glyphsGB.searchResults.default_message = \"search for annotations (eg EGR1 or kinase) or set location (eg: chr19:36373808-36403118)\";\n }\n if(!glyphsGB.searchMessage) {\n var msgDiv = document.createElement(\"div\");\n glyphsGB.searchMessage = msgDiv;\n }\n\n if(!glyphsGB.searchbox_enabled) { \n glyphsGB.searchFrame.style.display = \"none\";\n return; \n }\n\n glyphsGB.searchFrame.innerHTML = \"\";\n glyphsGB.searchFrame.style.display = \"block\";\n glyphsGB.searchResults.innerHTML = \"\";\n glyphsGB.searchResults.style.display = \"none\";\n\n var searchFrame = glyphsGB.searchFrame;\n \n var form = searchFrame.appendChild(document.createElement('form'));\n form.setAttribute(\"onsubmit\", \"return false;\");\n\n var span1 = form.appendChild(document.createElement('span'));\n \n var searchInput = glyphsGB.searchInput;\n form.appendChild(searchInput);\n\n var buttonSpan = form.appendChild(document.createElement('span'));\n var button1 = buttonSpan.appendChild(document.createElement('input'));\n button1.type = \"button\";\n button1.className = \"slimbutton\";\n button1.value = \"search\";\n button1.onclick = function(envt) { glyphsMainSearchInput(glyphsGB, '', envt); }\n\n var button2 = buttonSpan.appendChild(document.createElement('input'));\n button2.type = \"button\";\n button2.className = \"slimbutton\";\n button2.value = \"clear\";\n button2.onclick = function() { gLyphsClearSearchResults(glyphsGB); }\n \n searchFrame.appendChild(glyphsGB.searchResults); //moves to correct location\n searchFrame.appendChild(glyphsGB.searchMessage); //moves to correct location\n \n //set width\n var buttonsRect = buttonSpan.getBoundingClientRect();\n console.log(\"search buttons width: \"+buttonsRect.width);\n console.log(\"search_input width: \"+(glyphsGB.display_width - buttonsRect.width));\n searchInput.style.width = ((glyphsGB.display_width - buttonsRect.width)*0.80) +\"px\"; //glyphsGB.display_width;\n searchInput.style.margin = \"0px 0px 5px 0px\";\n \n //gLyphsClearSearchResults(glyphsGB);\n}", "function registerButtons() {\n document\n .querySelectorAll(`[data-action=\"filter\"]`)\n .forEach((button) => button.addEventListener(\"click\", selectFilter));\n document\n .querySelectorAll(`[data-action=\"sort\"]`)\n .forEach((button) => button.addEventListener(\"click\", selectSort));\n document.querySelector(\"#search\").addEventListener(\"keyup\", search);\n document.querySelector(\"header\").addEventListener(\"click\", hackTheSystem);\n}", "function setup() {\n wkof.Menu.insert_script_link({name:'doublecheck',submenu:'Settings',title:'Double-Check',on_click:open_settings});\n\n var defaults = {\n allow_retyping: true,\n allow_change_correct: false,\n show_corrected_answer: false,\n allow_change_incorrect: false,\n typo_action: 'ignore',\n wrong_answer_type_action: 'warn',\n wrong_number_n_action: 'warn',\n small_kana_action: 'warn',\n kanji_reading_for_vocab_action: 'warn',\n kanji_meaning_for_vocab_action: 'warn',\n delay_wrong: true,\n delay_multi_meaning: false,\n delay_slightly_off: false,\n delay_period: 1.5,\n warn_burn: 'never',\n burn_delay_period: 1.5,\n show_lightning_button: true,\n lightning_enabled: false,\n srs_msg_period: 1.2,\n autoinfo_correct: false,\n autoinfo_incorrect: false,\n autoinfo_multi_meaning: false,\n autoinfo_slightly_off: false\n }\n return wkof.Settings.load('doublecheck', defaults)\n .then(init_ui.bind(null, true /* first_time */));\n }" ]
[ "0.7365752", "0.6471374", "0.6415738", "0.6361888", "0.6314606", "0.63088644", "0.63020694", "0.6246487", "0.62399054", "0.62365574", "0.62300694", "0.6220702", "0.6215311", "0.6192951", "0.6147853", "0.6131752", "0.6122571", "0.6117456", "0.6100546", "0.6083763", "0.6060277", "0.60530037", "0.6048787", "0.59808195", "0.59525114", "0.5950494", "0.59465337", "0.59347165", "0.5928657", "0.5923194", "0.5920509", "0.591833", "0.59172845", "0.5913049", "0.59065044", "0.5904453", "0.59019643", "0.59010065", "0.5888216", "0.58859897", "0.5874955", "0.5847026", "0.5845206", "0.5841932", "0.58359176", "0.5802557", "0.5797894", "0.5781323", "0.57604253", "0.5748643", "0.57473147", "0.5746051", "0.5744358", "0.57381886", "0.5735258", "0.573441", "0.57277465", "0.57113576", "0.5706155", "0.5674102", "0.5667683", "0.56654114", "0.5664244", "0.56573623", "0.56440467", "0.56424093", "0.56389105", "0.56371456", "0.56215537", "0.5619417", "0.5619086", "0.56110895", "0.55996054", "0.55934656", "0.5592328", "0.5591925", "0.5585449", "0.55850005", "0.55815244", "0.55737156", "0.55726033", "0.5569678", "0.5566563", "0.55663806", "0.5557218", "0.5557077", "0.5551514", "0.55467546", "0.55451924", "0.5535761", "0.5535365", "0.55299693", "0.5528298", "0.5525776", "0.5523737", "0.5521289", "0.55170757", "0.5508567", "0.55036", "0.5502026", "0.5501776" ]
0.0
-1
Set following and non following users
setFollowUserList(state) { state.userList.forEach((user) => { let userF = state.currentUser.following.find( (following) => following._idUser === user._idUser ); if (userF) { state.followingUsers.push(user); } else { state.nonFollowingUsers.push(user); } }); state.loading.following = false; state.loading.follow = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function setFollowedUsers() {\n vm.followedUsers.forEach((user) => {\n for(var i = 0; i < vm.users.length; i++){\n if(user.username === vm.users[i].username){\n vm.users[i].follows = true;\n break;\n }\n }\n });\n }", "function setFollowingButton () {\n\tvar uid = new User(document.cookie).id();\n\tif (uid) {\n\t\tmyFtButton.setAttribute('href', '/users/' + uid + '/following/new');\n\t\tmyFtButton.textContent = 'Following';\n\t\tmyFtButton.insertAdjacentHTML('beforeend', ' <span class=\"notify-badge\"></span>');\n\t}\n}", "async handleFollowers (thing, op, options = {}) {\n\t\t// if this is a legacy codemark, created before codemark following was introduced per the \"sharing\" model,\n\t\t// we need to fill its followerIds array with the appropriate users\n\t\tif (thing.get('followerIds') === undefined) {\n\t\t\top.$set.followerIds = await new CodemarkHelper({ request: this.request }).handleFollowers(\n\t\t\t\tthing.attributes,\n\t\t\t\t{\n\t\t\t\t\tmentionedUserIds: this.parentPost.get('mentionedUserIds'),\n\t\t\t\t\tteam: this.team,\n\t\t\t\t\tstream: this.stream,\n\t\t\t\t\tparentPost: this.parentPost\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\t// also add this user as a follower if they have that preference, and are not a follower already\n\t\tconst userNotificationPreference = options.ignorePreferences ? 'involveMe' : \n\t\t\t((this.user.get('preferences') || {}).notifications || 'involveMe');\n\t\tconst followerIds = thing.get('followerIds') || [];\n\t\tif (userNotificationPreference === 'involveMe' && followerIds.indexOf(this.user.id) === -1) {\n\t\t\tif (op.$set.followerIds) {\n\t\t\t\t// here we're just adding the replying user to the followerIds array for the legacy codemark,\n\t\t\t\t// described above\n\t\t\t\tif (op.$set.followerIds.indexOf(this.user.id) === -1) {\n\t\t\t\t\top.$set.followerIds.push(this.user.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\top.$addToSet = { followerIds: [this.user.id] };\n\t\t\t}\n\t\t}\n\n\t\t// if a user is mentioned that is not following the thing, and they have the preference to\n\t\t// follow things they are mentioned in, or we're ignoring preferences,\n\t\t// then we'll presume to make them a follower\n\t\tconst mentionedUserIds = this.attributes.mentionedUserIds || [];\n\t\tlet newFollowerIds = ArrayUtilities.difference(mentionedUserIds, followerIds);\n\t\tif (newFollowerIds.length === 0) { return []; }\n\n\t\t// search for followers within the provided user array first\n\t\tlet newFollowers = [];\n\t\tif (this.users) {\n\t\t\tfor (let i = newFollowerIds.length-1; i >= 0; i--) {\n\t\t\t\tconst user = this.users.find(user => user.id === newFollowerIds[i]);\n\t\t\t\tif (user) {\n\t\t\t\t\tnewFollowers.push(user);\n\t\t\t\t\tnewFollowerIds.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// get any others from the database\n\t\tif (newFollowerIds.length > 0) {\n\t\t\tlet followersFromDb = await this.request.data.users.getByIds(\n\t\t\t\tnewFollowerIds,\n\t\t\t\t{\n\t\t\t\t\tfields: ['id', 'preferences'],\n\t\t\t\t\tnoCache: true,\n\t\t\t\t\tignoreCache: true\n\t\t\t\t}\n\t\t\t);\n\t\t\tnewFollowers = [...newFollowers, ...followersFromDb];\n\t\t}\n\n\t\tnewFollowers = newFollowers.filter(user => {\n\t\t\tconst preferences = user.get('preferences') || {};\n\t\t\tconst notificationPreference = preferences.notifications || 'involveMe';\n\t\t\treturn (\n\t\t\t\toptions.ignorePreferences || (\n\t\t\t\t\t!user.get('deactivated') && \n\t\t\t\t\t(\n\t\t\t\t\t\tnotificationPreference === 'all' ||\n\t\t\t\t\t\tnotificationPreference === 'involveMe'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\tnewFollowerIds = newFollowers.map(follower => follower.id);\n\t\tif (newFollowerIds.length > 0) {\n\t\t\tif (op.$set.followerIds) {\n\t\t\t\top.$set.followerIds = ArrayUtilities.union(op.$set.followerIds, newFollowerIds);\n\t\t\t}\n\t\t\telse {\n\t\t\t\top.$addToSet = op.$addToSet || { followerIds: [] };\n\t\t\t\top.$addToSet.followerIds = ArrayUtilities.union(op.$addToSet.followerIds, newFollowerIds);\n\t\t\t}\n\t\t}\n\t}", "function follow() {\n UserService.follow(vm.currentUser, vm.user)\n .then(res => {\n vm.user.followers.push(vm.currentUser._id);\n vm.isFollowed = true;\n\n // send notification to the server that user is followed\n socket.emit('notification', {'to': vm.user._id, 'from': vm.currentUser._id, 'author': vm.currentUser.username, 'type': 'follow'});\n });\n }", "followUser(state, userId) {\n state.loading.following = true;\n state.loading.follow = true;\n\n let user = state.userList.find((user) => user._idUser === userId);\n if (user) {\n state.followingUsers.push(user);\n state.nonFollowingUsers = state.nonFollowingUsers.filter(\n (user) => user._idUser !== userId\n );\n }\n state.loading.following = false;\n state.loading.follow = false;\n }", "function followUser() {\n if (LoginService.isLoggedIn()) {\n UserProfileService\n .followUser(vm.userInfo.id)\n .then(function () {\n vm.isFollowing = true;\n\n //reload details for the current user who has been followed/unfollowed\n getUserInfoForOtherUsers(vm.userInfo.userName);\n });\n }\n }", "updateTrackList(following) {\n // Add any new follows to the trackedUsers list\n for (let i = 0; i < following.length; i++) {\n let user = following[i];\n\n if (!(user in this.botStatus.trackedUsers)) {\n this.botStatus.trackedUsers[user] = 0;\n }\n }\n\n // Remove any trackedUsers that the bot is no longer following\n for (let userID in this.botStatus.trackedUsers) {\n if (!this.utils.isInArray(following, userID)) {\n delete this.botStatus.trackedUsers[userID];\n }\n }\n }", "followUser(name, followedName) {\n if (this.findUser(name)) {\n if (this.findUser(followedName)){\n this.findUser(name).addFollower(this.findUser(followedName));\n }\n }\n }", "function unfollow(){\n let users = document.querySelectorAll('div.r-1awozwy.r-18u37iz.r-1wtj0ep');\n for (let i = 0; i < users.length; i++){\n\t\tlet user = users[i]\n \tif( !user.children[0].children[0].children[0].children[1].children[1]) {\n\t\t\tif(user.children[1].children[0].children[0].children[0].children[0].innerHTML == 'Following'){\n\t\t\t\tuser.children[1].children[0].click();\n\t\t\t\tdocument.querySelectorAll('[data-testid=confirmationSheetConfirm]')[0].click();\n\t\t\t\tconsole.log('You just unfollow this user')\n }\n }\n }\n}", "can_follow() {\n return true\n }", "async function loadUsersFollowers() {\n const currentUsers = await getUsers(user);\n const currentFollows = await getFollows(user);\n\n // Sets users and follows states\n setUsers(currentUsers);\n setFollows(currentFollows);\n setIsLoading(false);\n }", "follow(entity) {\n this.following = entity;\n }", "function setButtons() {\n if ($routeParams.username != $rootScope.currentUser.username) {\n if ($rootScope.currentUser.friends.indexOf($routeParams.username) == -1) { // we aren't following them yet, show friend button\n $scope.friendbutton = true;\n $scope.unfriendbutton = false;\n } else {\n $scope.unfriendbutton = true;\n $scope.friendbutton = false;\n }\n }\n }", "async handleFollowers (attributes, options) {\n\t\t// get the stream, if this is a codemark for a CodeStream team\n\t\tlet stream;\n\t\tif (!attributes.providerType && attributes.streamId) {\n\t\t\tstream = options.stream || await this.request.data.streams.getById(attributes.streamId);\n\t\t}\n\n\t\t// get user preferences of all users who can see this codemark\n\t\tlet preferences;\n\t\tif (!options.ignorePreferences) {\n\t\t\tpreferences = await this.getUserFollowPreferences(stream, options.team, options.usersBeingAddedToTeam || []);\n\t\t} else {\n\t\t\tpreferences = { all: [], involveMe: [] };\n\t\t}\n\n\t\t// add as followers any users who choose to follow all codemarks\n\t\tlet followerIds = options.ignorePreferences ? [] : [...preferences.all];\n\n\t\t// ensure codemark creator is a follower if they want to be\n\t\tif (\n\t\t\tattributes.creatorId &&\n\t\t\tfollowerIds.indexOf(attributes.creatorId) === -1 &&\n\t\t\t(options.ignorePreferences || preferences.involveMe.indexOf(attributes.creatorId) !== -1)\n\t\t) {\n\t\t\tfollowerIds.push(attributes.creatorId);\n\t\t}\n\n\t\t/*\n\t\t// if the stream is a DM, everyone in the DM is a follower who wants to be\n\t\t// (deprecated)\n\t\tif (stream && stream.get('type') === 'direct') {\n\t\t\tconst membersWhoWantToFollow = ArrayUtilities.intersection(preferences.involveMe, stream.get('memberIds') || []);\n\t\t\tfollowerIds = ArrayUtilities.union(followerIds, membersWhoWantToFollow);\n\t\t}\n\t\t*/\n\n\t\t// must validate mentioned users and explicit followers, since these come directly from the request\n\t\tlet validateUserIds = ArrayUtilities.union(options.mentionedUserIds || [], attributes.followerIds || []);\n\t\tvalidateUserIds = ArrayUtilities.unique(validateUserIds);\n\t\tawait this.validateUsersOnTeam(validateUserIds, options.team, 'followers', options.usersBeingAddedToTeam, { foreignOk: true });\n\n\t\t// any mentioned users are followers if they want to be\n\t\tconst mentionedWhoWantToFollow = options.ignorePreferences ? \n\t\t\t(options.mentionedUserIds || []) : \n\t\t\tArrayUtilities.intersection(preferences.involveMe, options.mentionedUserIds || []);\n\t\tfollowerIds = ArrayUtilities.union(followerIds, mentionedWhoWantToFollow);\n\n\t\t// users who have replied to this codemark are followers, if they want to be\n\t\tif (options.parentPost && options.team) {\n\t\t\tconst repliers = await this.getPostRepliers(options.parentPost.id, options.team.id, stream.id);\n\t\t\tconst repliersWhoWantToFollow = options.ignorePreferences ?\n\t\t\t\trepliers :\n\t\t\t\tArrayUtilities.intersection(preferences.involveMe, repliers);\n\t\t\tfollowerIds = ArrayUtilities.union(followerIds, repliersWhoWantToFollow);\n\t\t}\n\n\t\t// users passed in are explicitly followers, overriding other rules\n\t\tfollowerIds = ArrayUtilities.union(followerIds, attributes.followerIds || []);\n\n\t\treturn followerIds;\n\t}", "function addFollows(follows) {\n var logo = \"https://www.gravatar.com/avatar/a2b6df699ae0cd59f5077a5cae4cf994/?s=80&r=pg&d=mm\";\n var status = \"\";\n var online = false;\n // Add a Twitch account that was closed\n if (follows.indexOf(\"brunofin\") === -1) { follows.push([\"brunofin\",status,logo,online]); }\n // Add a Twitch account that never existed\n if (follows.indexOf(\"comster404\") === -1) { follows.push([\"comster404\",status,logo,online]); }\n // Add some Twitch accounts that are usually active\n if (follows.indexOf(\"OgamingSC2\") === -1) { follows.push([\"OgamingSC2\",status,logo,online]); }\n if (follows.indexOf(\"ESL_SC2\") === -1) { follows.push([\"ESL_SC2\",status,logo,online]); }\n if (follows.indexOf(\"cretetion\") === -1) { follows.push([\"cretetion\",status,logo,online]); }\n if (follows.indexOf(\"freecodecamp\") === -1) { follows.push([\"freecodecamp\",status,\"https://static-cdn.jtvnw.net/jtv_user_pictures/freecodecamp-profile_image-d9514f2df0962329-300x300.png\",online]); }\n if (follows.indexOf(\"storbeck\") === -1) { follows.push([\"storbeck\",status,logo,online]); }\n if (follows.indexOf(\"habathcx\") === -1) { follows.push([\"habathcx\",status,logo,online]); }\n if (follows.indexOf(\"RobotCaleb\") === -1) { follows.push([\"RobotCaleb\",status,logo,online]); }\n if (follows.indexOf(\"noobs2ninjas\") === -1) { follows.push([\"noobs2ninjas\",status,logo,online]); }\n }", "function onToggleFollowingUserSuccess(data) {\n\tvar favicon = $(\".addfav\", \".user_\" + data.id);\n\tif(data.follow) {\n\t\tfavicon.addClass(\"active\");\n\t} else {\n\t\tfavicon.removeClass(\"active\");\n\t}\n}", "function enhanceFollowersFunctionality() {\n var followerWrappers = document.querySelectorAll(\"#followers [data-userid]\");\n followerWrappers.forEach(function(followerEl) {\n var timestamp = followerEl.querySelector(\".timestamp\");\n timestamp.innerText = formatServerDateTime(timestamp.innerText);\n var followerName = followerEl.dataset.username;\n var blockButton = followerEl.querySelector(\".block-follower-button\");\n if(!blockButton) return; // Buttons are rendered on the backend only for the owner of the follower listing page.\n blockButton.addEventListener(\"click\", function() {\n toggleBlock(blockButton, followerName);\n });\n });\n}", "async function followUser(current_id, user_id){\r\n console.log(current_id + \" Will Now Follow: \" + user_id)\r\n \r\n // Call API to make change\r\n fetch('/follow/' + current_id + '/' + user_id)\r\n\t.then(res => res.json())\r\n\t.then(data => {\r\n\t\t// Print data\r\n\t\tconsole.log(data);\r\n \r\n // after following, clear the current follow button and add unfollow button\r\n document.getElementById('follow_option').innerHTML = \"\"; \r\n\t\tloadFollowStatus(current_id, user_id, \"yes\") // will now display unfollow button\r\n\t\tincrementFollowerCount(current_id, user_id); // increments the follower count\r\n });\r\n}", "async function followRequestCall() {\n try {\n const response = await Axios.post(`/addFollow/${state.profileData.profileUsername}`, { token: appState.user.token }, { cancelToken: followRequest.token })\n setState(draft => {\n draft.profileData.isFollowing = true\n draft.profileData.counts.followerCount++\n draft.followActionRunning = false\n })\n } catch (error) {\n console.log(\"There was a problem following user or user cancelled\")\n }\n }", "checkIfFollowed(){\n if(global.user_id!==null&&global.user_id!==undefined){\n console.debug(\"followers\",this.state.followers);\n \n if(this.state.followers.map(follower => follower.user_id).includes(global.user_id)){\n\n this.setState({buttonText:'Unfollow'})\n }\n else if(global.user_id==this.state.userID)\n {\n this.setState({buttonText:'Edit Profile'})\n }\n else{\n this.setState({buttonText:'Follow'})\n }\n }\n else{\n this.setState({buttonText:'Follow'},this.setState({hasKey:false}))\n }\n \n }", "async userFollows(...ids) {\n return (await this.client.playlists.userFollows(this.id, ...ids))[0] || false;\n }", "function followUser(username) {\n if (!isLoggedIn()) return;\n\n //reset paging so we make sure our results start at the beginning\n fullActivityFeed.resetPaging();\n userFeed.resetPaging();\n\n var options = {\n method:'POST',\n endpoint:'users/me/following/users/' + username\n };\n client.request(options, function (err, data) {\n if (err) {\n $('#now-following-text').html('Aw Shucks! There was a problem trying to follow <strong>' + username + '</strong>');\n } else {\n $('#now-following-text').html('Congratulations! You are now following <strong>' + username + '</strong>');\n showMyFeed();\n }\n });\n }", "async following (req, res, next) {\n await User.getFollowing(req.params.username, (err, following) => {\n if (err) return next(err)\n\n res.send({ following })\n })\n }", "function follow(req, res) {\n Profile.findById(req.user.profile)\n .then(followerProfile => {\n followerProfile.following.push(req.params.id)\n followerProfile.save()\n .then(()=> {\n Profile.findById(req.params.id)\n .then(followingProfile=>{\n followingProfile.followers.push(req.user.profile)\n followingProfile.save()\n })\n res.redirect(`/profiles/${req.params.id}`)\n })\n })\n .catch((err) => {\n console.log(err)\n res.redirect('/')\n })\n}", "toggleFollowing() {\n this.setState({showTweets:false})\n this.setState({showFollowing:true})\n this.setState({showFollowers:false});\n }", "function unfollow() {\n UserService.unfollow(vm.currentUser, vm.user)\n .then(res => {\n vm.user.followers.splice(vm.user.followers.findIndex(x => x._id == vm.currentUser._id), 1);\n vm.isFollowed = false;\n });\n }", "function follow(username, loggedInUsername, toFollow, usernameKey, toFollowKey){\n\t//make an ajax call to ChangeFollowServlet\n\tvar xhttp = new XMLHttpRequest();\n\tconsole.log(\"/\"+window.location.pathname.split(\"/\")[1]);\n\txhttp.open(\"GET\", \"/\"+window.location.pathname.split(\"/\")[1]+\"/ChangeFollowServlet?\"+usernameKey+\"=\"+\n\t\t\tusername+\"&\"+toFollowKey+\"=\"+toFollow, false);\n\txhttp.send();\n\t\n\t//if the loggedInUser added the username to their following list\n\tif (toFollow){\n\t\t//create a new h2 element\n\t var h2 = document.createElement('h2');\n\t //set the id to loggedin_follower (so we know the exact element that references the loggedin user's username)\n\t h2.id = \"loggedin_follower\";\n\t //create and a element, and set the href to navigate to the user_profile jsp\n\t var a = document.createElement('a');\n\t a.href = \"/\"+window.location.pathname.split(\"/\")[1]+\"/jsp/user_profile.jsp?\"+usernameKey+\"=\"+loggedInUsername;\n\t //create a text node with the loggedInUsername and append it as a child to the a element\n\t var text = document.createTextNode(loggedInUsername);\n\t a.appendChild(text);\n\t //append the a element as a child of the h2 element\n\t h2.appendChild(a);\n\t //append the h2 element as a child of the followers div\n\t document.getElementById('followers').appendChild(h2);\n\t //switch visiblity of unfollow and follow buttons\n\t document.getElementById(\"follow_button\").style.display = \"none\";\n\t document.getElementById(\"unfollow_button\").style.display = \"block\";\n\t\t \n\t}\n\t//if the loggedIsUser removed the username from their following list\n\telse{\n\t\t//remove the loggedin_follower element from the followers div\n\t document.getElementById('loggedin_follower').remove();\n\t //switch visibility of unfollow and follow buttons\n\t document.getElementById(\"unfollow_button\").style.display = \"none\";\n document.getElementById(\"follow_button\").style.display = \"block\";\t\t\n\t}\n\t\n\treturn false;\n}", "function unFollowUser() {\n if (LoginService.isLoggedIn()) {\n UserProfileService\n .unFollowUser(vm.userInfo.id)\n .then(function () {\n vm.isFollowing = false;\n\n //reload details for the current user who has been followed/unfollowed\n getUserInfoForOtherUsers(vm.userInfo.userName);\n });\n }\n }", "function findUsersToFollow(user) {\n return travelyaarUserModel.find({_id: {$nin: user.following}});\n }", "function show_unfollow(response) {\n\n $('#follow-button-' + response.user_id).hide();\n $('#unfollow-button-' + response.user_id).show();\n }", "function unfollowUser() {\n if($rootScope.currentUser == null){\n vm.returnData = \"Log in to continue\";\n }else{\n NoteService\n .unfollowUser(vm.note.user.uid, $rootScope.currentUser._id)\n .then(function (response) {\n vm.userFollowed = 0;\n console.log(response);\n });}\n }", "function followUser(req ,res) {\n var userId1 = req.params.userId1;\n var userId2 = req.params.userId2;\n userModel\n .followUser(userId1 , userId2)\n .then(function (user) {\n userModel\n .followingUser(userId2 , userId1)\n .then(function (fake) {\n res.send(user);\n },function (err) {\n response.status=\"KO\";\n response.description=\"Unable to follow the given user\";\n res.json(response);\n });\n } , function (err) {\n response.status=\"KO\";\n response.description=\"Unable to follow the given user\";\n res.json(response);\n });\n }", "function addFollower() {\n followers = followers + 1;\n}", "function follow(actionIsFollow) {\n let button = $(\"#buttonFollow\");\n\n // Si disabilita il bottone finché non arriva una risposta.\n button.attr(\"disabled\", true);\n\n let target = actionIsFollow ? \"/follow\" : \"/unfollow\";\n\n $.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name=\"csrf-token\"]').attr('content')\n }\n });\n $.post(target,\n {\n targetId: parseInt($(\"#userID\").text())\n },\n function (data, status, xhr) {\n if (data.result) {\n // Modifica dell'aspetto del bottone\n button.toggleClass(\"btn-primary\");\n button.toggleClass(\"btn-outline-primary\");\n let newButtonText = actionIsFollow ? \"Seguito\" : \"Segui\";\n button.text(newButtonText);\n\n // Modifica del numero dei follower\n // NB: Questa operazione viene eseguita SOLO se il numero dei follower è inferiore a 1000!\n let followersSpan = button.parents(\".row\").prev().find(\"div:first-child > span:last-child\");\n if (!followersSpan.text().match(/[a-z]/i)) {\n let followersCount = parseInt(followersSpan.text());\n let delta = actionIsFollow ? +1 : -1;\n followersSpan.text(followersCount + delta);\n }\n\n // Modifica della funzione associata al bottone\n let newFunction = actionIsFollow ? \"executeUnfollow\" : \"executeFollow\";\n button.attr(\"onclick\", newFunction + \"()\");\n\n // Modifica dell'elenco dei followed\n if (actionIsFollow) $(\"#followedList ul\").append($(\"<li><a style='word-break: break-all' href='/user/\"+$(\"#userID\").text().trim()+\"'>\"+$(\"#username\").text()+\"</a></li>\"));\n else{\n let username = $(\"#username\").text().trim();\n $(\"#followedList li:contains(\"+username+\")\").remove();\n }\n }\n\n button.attr(\"disabled\", false);\n }, \"json\")\n .always(function () {\n // A prescindere dal tipo di risposta ricevuta, il bottone viene sempre riattivato\n button.attr(\"disabled\", false);\n });\n}", "function followUser() {\n if($rootScope.currentUser == null){\n vm.returnData = \"Log in to continue\";\n }else{\n NoteService\n .checkIfUserFollowed(vm.note.user.uid, $rootScope.currentUser._id)\n .then(function (response) {\n var followed = response.data;\n console.log(response.data);\n if(response.data == null || response.data == \"\"){\n NoteService\n .followUser(vm.note.user.uid)\n .then(function (response) {\n console.log(\"Successful\");\n vm.userFollowed = 1;\n });\n console.log(\"followed\" + vm.note.user.username);}\n else{\n for(i=0 ; i<followed.length ; i++){\n if(followed[i] == vm.note.user.uid){\n console.log(\"he has already followed him\");\n vm.userFollowed = 1;\n }\n }if(vm.userFollowed = 0){\n NoteService\n .followUser(vm.note.user.uid)\n .then(function (response) {\n console.log(\"Successful\");\n });\n }\n }\n }, function (error) {\n console.log(error);\n });\n }\n }", "toggleFollow(){\n if(this.state.buttonText=='Follow'){\n if(this.state.hasKey==true){\n this.setState({buttonText:'Unfollow'},()=>this.follow())\n }\n else{ //if user is not logged in\n alert(\"Cannot follow users unless logged in!\" )\n }\n }\n if(this.state.buttonText=='Unfollow'){\n if(this.state.hasKey==true){\n this.setState({buttonText:'Follow'},()=>this.unfollow())\n }\n else{}\n }\n if(this.state.buttonText=='Edit Profile'){\n this.props.navigation.navigate('Edit Profile');\n }\n \n }", "function setFollowers(followsApi, numOfFollows) {\n let html = \"\";\n if (numOfFollows === 0) { // if no followers, no need to fetch request for them\n document.getElementById(\"followersList\").innerHTML = `<p> No Followers</p>`;\n return;\n }\n // fetch the followers request\n fetchUrl(followsApi)\n .then(function(response) {\n const api = JSON.parse(JSON.stringify(response));\n for (i = 0; i < api.length; ++i)\n // set follower html url in the link, and the follower name as the name\n html += `<li><a href='${api[i].html_url}' target=\"blank\">${api[i].login}</a></li>`;\n document.getElementById(\"followersList\").innerHTML = html;\n\n }).catch(function(error) {\n console.log('Request failed', error);\n });\n }", "get followUp() {\n\t\treturn this.__followUp;\n\t}", "function followUser(username, current, follow, db, callback){\n if(follow){\n var follower = {$addToSet: {followers: current}};\n db.db(\"twitter\").collection(\"users\").updateOne({username: username}, follower, function(err, ret){\n if (err) throw err;\n if(ret.matchedCount <= 0){\n console.log(\"Cannot find the user you're trying to follow\");\n callback(err, false);\n }else{\n console.log(\"updated \" + username + \"'s followers\");\n var following = {$addToSet: {following: username}};\n db.db(\"twitter\").collection(\"users\").updateOne({username: current}, following, function(err, ret){\n if (err) throw err;\n if(ret.matchedCount <= 0){\n console.log(\"??\");\n callback(err, false);\n }else{\n console.log(\"updated following/follower lists of both users\")\n callback(err, true);\n }\n });\n }\n });\n }else{\n console.log(current + \" trying to unfollow \" + username);\n var follower = {$pull: {followers: current}};\n db.db(\"twitter\").collection(\"users\").updateOne({username: username}, follower, function(err, ret){\n if (err) throw err;\n if(ret.matchedCount <= 0){\n console.log(\"Cannot find the user you're trying to unfollow\");\n callback(err, false);\n }else{\n console.log(\"updated \" + username + \"'s followers\");\n var following = {$pull: {following: username}};\n db.db(\"twitter\").collection(\"users\").updateOne({username: current}, following, function(err, ret){\n if (err) throw err;\n if(ret.matchedCount <= 0){\n console.log(\"??\");\n callback(err, false);\n }else{\n console.log(\"updated following/follower lists of both users\")\n callback(err, true);\n }\n });\n }\n });\n }\n // mongoClient.connect(url, function(err, db) {\n // if (err) throw err;\n // //Can we assume that the current user is always a valid user? (from session)\n // if(follow){\n // console.log(current + \" trying to follow \" + username);\n // var follower = {$addToSet: {followers: current}};\n // db.db(\"twitter\").collection(\"users\").updateOne({username: username}, follower, function(err, ret){\n // if (err) throw err;\n // if(ret.matchedCount <= 0){\n // console.log(\"Cannot find the user you're trying to follow\");\n // callback(err, false);\n // }else{\n // console.log(\"updated \" + username + \"'s followers\");\n // var following = {$addToSet: {following: username}};\n // db.db(\"twitter\").collection(\"users\").updateOne({username: current}, following, function(err, ret){\n // if (err) throw err;\n // if(ret.matchedCount <= 0){\n // console.log(\"??\");\n // callback(err, false);\n // }else{\n // console.log(\"updated following/follower lists of both users\")\n // callback(err, true);\n // }\n // });\n // }\n // });\n // }else{\n // console.log(current + \" trying to unfollow \" + username);\n // var follower = {$pull: {followers: current}};\n // db.db(\"twitter\").collection(\"users\").updateOne({username: username}, follower, function(err, ret){\n // if (err) throw err;\n // if(ret.matchedCount <= 0){\n // console.log(\"Cannot find the user you're trying to unfollow\");\n // callback(err, false);\n // }else{\n // console.log(\"updated \" + username + \"'s followers\");\n // var following = {$pull: {following: username}};\n // db.db(\"twitter\").collection(\"users\").updateOne({username: current}, following, function(err, ret){\n // if (err) throw err;\n // if(ret.matchedCount <= 0){\n // console.log(\"??\");\n // callback(err, false);\n // }else{\n // console.log(\"updated following/follower lists of both users\")\n // callback(err, true);\n // }\n // });\n // }\n // });\n // }\n // });\n}", "function follow_user(id, follow) {\n fetch('/follow', {\n method: 'POST',\n body: JSON.stringify({\n \"id\": id,\n \"follow\": follow\n })\n })\n .then(response => response.json())\n .then(result => {\n load_profile(id);\n })\n}", "unfollowUser(state, userId) {\n state.loading.following = true;\n state.loading.follow = true;\n\n let user = state.userList.find((user) => user._idUser === userId);\n if (user) {\n state.nonFollowingUsers.push(user);\n state.followingUsers = state.followingUsers.filter(\n (user) => user._idUser !== userId\n );\n }\n state.loading.following = false;\n state.loading.follow = false;\n }", "function new_user_follow(user) {\n console.log(`new_user_follow: ${user.phone_number}`);\n PhoneNumber.findOne({_id: user.phone_number}, function (err, phone_number) {\n if (err)\n return logger.error(err.message);\n\n if (!phone_number) {\n PhoneNumber.create({\n _id: user.phone_number,\n owner: user._id,\n updated: Date.now(),\n contacts: []\n }, function (err) {\n if (err) console.log(err);\n //TODO: Suggests who to follow (All entities)\n });\n } else {\n //We have this number, make user follow the users who have his number\n async.each(phone_number.contacts, (contactX, callback) => {\n //this line is redundant but solved some bug we could not understand since contact.userId was undefined value\n const contact = JSON.parse(JSON.stringify(contactX));\n graphModel.follow_user_by_phone_number(user.phone_number, contact.userId, err => {\n if(err) return callback(err);\n activity_follow(user._id, {user: contact.userId});\n callback(null)\n });\n },(err) => {\n if(err) console.error(err);\n graphModel.owner_followers_follow_business(user._id);\n phone_number.owner = user._id;\n phone_number.save();\n\n });\n //We have this number, make user follow the users who have his number\n // phone_number.contacts.forEach( (contactX) => {\n // //this line is redundant but solved some bug we could not understand since contact.userId was undefined value\n // const contact = JSON.parse(JSON.stringify(contactX));\n // graphModel.follow_user_by_phone_number(user.phone_number, contact.userId);\n // activity_follow(user._id, {user: contact.userId});\n // });\n }\n });\n}", "function follow(targetBtn, display) {\n\tvar button = $(targetBtn);\n\tif (display){var name = display}else{\n\t\tvar name = button.attr('id')\n\t}\n\tvar state = button.attr('data-state');\n\tvar pin = $($(targetBtn).closest(\".pin\"));\n\tvar id = parseInt(pin.attr('id'));\n\tvar count = pin.attr('data-'+name);\n\tvar disp = pin.find('.display.'+name)\n\tvar dispText = pin.find('.display.text.'+name)\n\tsubmitProgress(button);\n\t\n\t//TODO: ether add progress or move contents out of onFollow to speed it up\n\tthis.onFollow = function( result ) {\n\t\tconsole.log('onFollow', result);\n\t\t// Update the number of followers displayed.\n\t\tconsole.log('count: '+count)\n\t\tconsole.log('state = '+state)\n\t\tif(state == \"True\") {\n\t\t\tbutton.attr('data-state', 'False');\n\t\t\tbutton.html('Follow')\n\t\t\tcount--;\n\t\t\tconsole.log('count: '+count)\n\t\t} else {\n\t\t\tbutton.attr('data-state', 'True');\n\t\t\tbutton.html('Un-Follow')\n\t\t\tcount++;\n\t\t\tconsole.log('count: '+count)\n\t\t\t//this.showLoader('Unliking');\n\t\t}\n\t\tpin.attr('data-'+name, count);\n\t\tdispText.html(count);\n\t};\n\t\n\tvar url = pinsPrefix+'/toggle/auth/User/'+id+'/';\n\tconsole.log('-ajax - 4 follow()');\n\t$.ajax({//4\n\t\turl: url,\n\t\ttype: 'POST',\n\t\tcontentType: 'application/json',\n\t\tsuccess: $.proxy(this.onFollow, this),//todo: need to detect if followed or not\n\t\terror: function(jqXHR, settings) {\n\t\t\tconsole.warn('follow - ajax error');\n\t\t},\n\t});\n}", "isFollowing(follower, followee) {\r\n const q = this.clone(UserProfileQuery, null);\r\n q.concat(`.isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)`);\r\n q.query.set(\"@v\", `'${encodeURIComponent(follower)}'`);\r\n q.query.set(\"@y\", `'${encodeURIComponent(followee)}'`);\r\n return q.get();\r\n }", "handleFollowingNav() {\n if (this.userData.following.edges === null\n || this.userData.following.edges === undefined\n || this.userData.following.edges.length === 0) {\n const emptyPrompt = `${this.userData.userLogin} is not following other GitHub users.`;\n const pushEmpty = StackActions.push('Empty', { emptyPrompt });\n this.navigation.dispatch(pushEmpty);\n } else {\n const pushFollowing = StackActions.push('Following',\n { following: this.userData.following.edges, user: this.userData.userLogin });\n this.navigation.dispatch(pushFollowing);\n }\n }", "async is_follow() {\n const {id} = this.state;\n const followings = await get_object('@storage_following');\n if (followings) {\n let follow = followings.find(item => item.id === id);\n this.setState({is_follow: follow ? true : false});\n }\n }", "function update(req, res, next) {\n /* jshint maxstatements: 21 */\n\n var id = req.params.id;\n var followers = req.user.followers;\n var approved = req.body.approved;\n var blocked = req.body.blocked;\n\n try {\n id = new ObjectId(id);\n } catch (err) {\n return res.status(httpStatus.BAD_REQUEST).json({\n status: 'failed',\n message: 'not a user id'\n });\n }\n\n if (typeof approved !== 'boolean' && typeof blocked !== 'boolean') {\n return res.status(httpStatus.BAD_REQUEST).json({\n status: 'failed',\n message: 'no data included'\n });\n }\n\n // find the relevent user\n var found;\n for (var index = 0, len = followers.length; index < len; index++) {\n var follower = followers[index];\n if (follower.id.equals(id)) {\n found = follower;\n break;\n }\n }\n\n if (!found) {\n return res.status(httpStatus.BAD_REQUEST).json({\n status: 'failed',\n message: 'not following user ' + id.toString()\n });\n }\n\n if (approved !== undefined) {\n found.status.approved = approved;\n }\n\n if (blocked !== undefined) {\n found.status.blocked = blocked;\n }\n\n req.user.save(function (err) {\n if (err) {\n return next(err);\n }\n\n return res.status(httpStatus.OK).json({\n status: 'success',\n message: 'follower status updated'\n });\n });\n\n}", "function processFollowButton(userObject,itemOwnerID){\n\t// follow and unfollow \n\t$(\"#toUnfollowButton\").hide()\n\t$(\"#toFollowButton\").hide()\n \tif(include(userObject.followingList, itemOwnerID)){\n \t\tconsole.log('Has followed owner')\n \t\t$(\"#toUnfollowButton\").show()\n \t\t$(\"#toUnfollowButton\").unbind()\n \t\t// ajax to unfollow \n \t\t$(\"#toUnfollowButton\").click(function(){\n \t\t\t$.ajax({\n\t\t\t\turl: \"/toUnFollowUser\",\n\t\t\t\tdata: {\"targetUserID\":itemOwnerID},\n\t\t\t\tsuccess: function(response) {\n\t\t\t\t //Do Something\n\t\t\t\t console.log('unFollow success!')\n\t\t\t\t processFollowButton(response.targetUser, itemOwnerID)\n\t\t\t\t},\n\t\t\t\terror: function(xhr) {\n\t\t\t\t //Do Something to handle error\n\n\t\t\t\t}\n\t\t\t});\n \t\t})\n\n \t}else{\n \t\tconsole.log('Not follow owner yet')\n \t\t$(\"#toFollowButton\").show()\n \t\t$(\"#toFollowButton\").unbind()\n \t\t// ajax to follow\n \t\t$(\"#toFollowButton\").click(function(){\n \t\t\t$.ajax({\n\t\t\t\turl: \"/toFollowUser\",\n\t\t\t\tdata: {\"targetUserID\":itemOwnerID},\n\t\t\t\tsuccess: function(response) {\n\t\t\t\t //Do Something\n\t\t\t\t console.log('Follow success!')\n\t\t\t\t processFollowButton(response.targetUser, itemOwnerID)\n\n\t\t\t\t},\n\t\t\t\terror: function(xhr) {\n\t\t\t\t //Do Something to handle error\n\t\t\t\t}\n\t\t\t});\n \t\t})\n \t\t\n \t}\n}", "function updateUserList(users) {\n users.forEach(function(user) {\n if (user.id == me.id) {return;}\n addUser(user);\n });\n}", "function streamUser() {\n var $body = $('.people-follow');\n for(var key in streams) {\n if(key === 'users') {\n for(var key in streams.users) {\n var user = key;\n var $user = $('<a id='+user+'></a><br>');\n $user.text('@' + user);\n $user.appendTo($body);\n }\n } \n }\n}", "function highlightFollowedUsers(doc) {\n try {\n doc = doc || document;\n var follow_re = new RegExp('^(' + config.nobles.join(\"|\") + ')$');\n if (isMainPage()) {\n // color people followed and make follow/unfollow links etc.\n $('.user_follow, .flair', doc).remove();\n\n try {\n $('.subtext a:nth-child(2)', doc).each(function() {\n makeFollowUserLink(follow_re, this);\n });\n } catch (it) {\n console.log(it);\n }\n } else if (isCommentsPage()) {\n $('.user_follow, .flair', doc).remove();\n\n makeFollowUserLink(follow_re, $('table .subtext a', doc)[0]);\n try {\n $('span.comhead > a.hnuser', doc).each(function() {\n makeFollowUserLink(follow_re, this);\n });\n } catch (a) {\n console.log(a);\n }\n } else if (isLeadersPage()) {\n $('.user_follow, .flair', doc).remove();\n doLeadersPage(doc);\n } else if (isProfilePage()) {\n var td = $('.user_follow', doc).closest('td')[0];\n td.innerHTML = td.firstChild.innerHTML;\n doProfilePage(doc);\n } else {\n console.log(\"Don't understand what kind of hn page this is\");\n }\n } catch (e) {\n console.log(e);\n }\n }", "async function unfollowUser(current_id, user_id){\r\n console.log(current_id + \" Will Now Unfollow: \" + user_id)\r\n\r\n // Call API to make change\r\n fetch('/unfollow/' + current_id + '/' + user_id)\r\n\t.then(res => res.json())\r\n\t.then(data => {\r\n\t\t// Print data\r\n\t\tconsole.log(data);\r\n \r\n // after following, clear the current follow button and add unfollow button\r\n document.getElementById('follow_option').innerHTML = \"\";\r\n\t\tloadFollowStatus(current_id, user_id, \"no\") // will now display follow button\r\n\t\tdecrementFollowerCount(current_id, user_id); // decrements the follower count\r\n });\r\n}", "getFollowings(userid,maxid = null, callback) {\n var endpoint = 'friendships/' + userid + '/following/?'\n Instaifunctions.sendRequest(endpoint, null,\n (data) =>\n callback(data)\n )\n }", "following () {\n return this.belongsToMany(\n 'App/Models/User',\n 'follower_id',\n 'user_id'\n ).pivotTable('followers')\n }", "async followers (req, res, next) {\n await User.getFollowers(req.params.username, (err, followers) => {\n if (err) return next(err)\n\n res.send({ followers })\n })\n }", "addFollowerSpecific() {\n this.definition.extendedType = NSmartContract.SmartContractType.FOLLOWER1;\n\n let ownerLink = new roles.RoleLink(\"owner_link\", \"owner\");\n this.registerRole(ownerLink);\n\n let fieldsMap = {};\n fieldsMap[\"action\"] = null;\n fieldsMap[\"/expires_at\"] = null;\n fieldsMap[FollowerContract.PAID_U_FIELD_NAME] = null;\n fieldsMap[FollowerContract.PREPAID_OD_FIELD_NAME] = null;\n fieldsMap[FollowerContract.PREPAID_FROM_TIME_FIELD_NAME] = null;\n fieldsMap[FollowerContract.FOLLOWED_ORIGINS_FIELD_NAME] = null;\n fieldsMap[FollowerContract.SPENT_OD_FIELD_NAME] = null;\n fieldsMap[FollowerContract.SPENT_OD_TIME_FIELD_NAME] = null;\n fieldsMap[FollowerContract.CALLBACK_RATE_FIELD_NAME] = null;\n fieldsMap[FollowerContract.TRACKING_ORIGINS_FIELD_NAME] = null;\n fieldsMap[FollowerContract.CALLBACK_KEYS_FIELD_NAME] = null;\n\n let modifyDataPermission = new permissions.ModifyDataPermission(ownerLink, {fields : fieldsMap});\n this.definition.addPermission(modifyDataPermission);\n }", "async function getOneUserPopulateFollowing() {\n try {\n const populatedUser = await UserModel.findById(\"5f5f85f887dcf2441f096960\")\n .populate(\"following\")\n .exec();\n\n console.log(populatedUser);\n } catch (error) {\n console.log(error);\n }\n }", "async function getFollowings() {\n console.log('Getting users which are followed by you')\n let hash = 'd04b0a864b4b54837c0d870b0e77e076'\n let body = await rp.get({\n url: 'https://www.instagram.com/graphql/query/',\n headers: {\n 'cookie': `sessionid=${sessionId};`\n },\n qs: {\n query_hash: hash,\n variables: variables\n },\n })\n body = JSON.parse(body)\n let data = body.data.user.edge_follow.edges\n data.forEach(item => $following.push(item.node.username))\n nextCursor = body.data.user.edge_follow.page_info.end_cursor\n nextPage = body.data.user.edge_follow.page_info.has_next_page\n await processData(nextCursor, nextPage, hash, false)\n}", "onSync(changes) {\n if (changes.id[0] !== this.id) {\n let obj = this.mergeSynced(changes, 'follows')\n this.sync(obj)\n }\n }", "_shiftNextUser() {\r\n this.getCurrentUser().isActive = false;\r\n this.users.push(this.users.shift());\r\n this.getCurrentUser().isActive = true;\r\n }", "handleFollowBtn(){\n let followState;\n let followerNumber = Number(this.state.followerNumber)\n if(this.state.following){\n //Unfollow\n this.setState({following:false,followerNumber:followerNumber-=1})\n followState=false;\n }else{\n //Follow\n this.setState({following:true,followerNumber:followerNumber+=1})\n followState=true;\n }\n\n //Push data\n fetch('https://ride-hub.herokuapp.com/api/subforum/follow', {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n is_follow:followState,\n forum_id:this.state.id,\n creation_date:this.getDateTime()\n })\n }).then(response=>{\n if(!response.ok){\n console.log('Error: '+response.status);\n followState=!followState;\n this.setState({following:followState,followerNumber:followerNumber-=1})\n if(response.status===403){\n alert('You must log in to use this function')\n }\n }\n }\n )\n \n }", "function stopFollowing() {\n return false;\n }", "async setUsersStatusToLoggedIn(user) {\n const hoursToStayLoggedIn = 24;\n const now = new Date();\n user.loggedInUntil = now.setHours(now.getHours() + hoursToStayLoggedIn);\n await this.chatDAO.updateUser(user);\n }", "function getFollowers() {\n\tT.get('users/show', { screen_name: 'TheGreatLeadr' }, function (err, data, response) {\n\tfollowerMod++;\n if(followerMod >= 6){\t\n \t\t//Logs the amount responses to the bot with the specific string to the console.\n \t\t//Dubbed here as \"active citizens\".\n console.log(\"There are currently \" + tagcounter + \" active citizens of \" + data.followers_count + \" total citizens in the great nation.\")\n followerMod = 0;\n }\n \n\t \t\t//Calculates the \"citizen\"/\"active citizen\" ratio and acts respectively.\n\t \t\tif (data.followers_count >= tagcounter * 2) {\n\t\t\n\t\t} else {\n\n\t\t\t//If the active amount of users (people who tweet the specific string to the bot)\n\t\t\t//is more than 50% of the followers, this log will show\n\t\t\tconsole.log('NATION REACHED ACTIVE LEVEL');\n\n\t\t\t//Makes the cooldown trick do wonders\n\t\t\tcooldown++;\n\n\t\t\t//Calls the \"Active\" level image function to be executed\n\t\t\ttweetImageActive();\n\t\t}\n\t})\n}", "function removeFollower(){\n\t\t//one follower name comes with an unfollow button\n\t\telement.all(by.id(\"folowerName\")).each(function(element, index){\n\t\t\telement.getText().then(function(text){\n\t\t\t\tif(text == \"Follower\"){\n\t\t\t\t\telement.all(by.id(\"unfollowBtn\")).get(index).click()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}", "function doesntFollowBack() {\r\n let output = [];\r\n for (user in pplUserFollows) {\r\n let check = false;\r\n for (i = 0; i < pplUserFollows[user].length; i++) {\r\n if (pplUserFollows[pplUserFollows[user][i]].includes(user)) {\r\n check = true;\r\n continue;\r\n }\r\n }\r\n if (!check) {\r\n output.push(user);\r\n }\r\n }\r\n let listOfUsers = output.join(\" \");\r\n output.length === 0 ? console.log(\"Everyone follows someone who follows them back\") :\r\n console.log(listOfUsers + \" follow someone who doesn't follow them back\");\r\n}", "function follow(username) {\n// Send the username to the server\n $.get(\"/users/follow/\" + username)\n .done(function () {\n\n // Change the id to unfollow\n $('#follow-btn').attr({\n id: \"unfollow-btn\"\n })\n // Change the text to unfollow\n .text(\"Unfollow\");\n\n\n showMessage(\"You just follwed \" + username + \" Congratulations !!\");\n\n }).fail(function () {\n showMessage(\"Error when trying to follow the user \" + username, ALERT_DANGER)\n })\n}", "function mergeArrays(){\n const arr=[userFollowing, id2]\n let jointArray=[]\n arr.forEach(array => {\n jointArray = [ ...jointArray, ...array]\n })\n const newSet= [...new Set([...jointArray])]\n\n //3. add API request to PUT the selected followee to the users API\n usersAPI.postFollowing(id, {following: newSet})\n setAddedResult(true)\n }", "function followage(user, channel, bot) { //Will go over user once reached\n request('https://api.rtainc.co/twitch/followers/length?channel=' + getUser(channel) + '&name=' + user, function(error, response, body) {\n if (!error && response.statusCode == 200) {\n bot.say(channel, user + ' has been following ' + getUser(channel) + ' for ' + body); //Respond how long user has been following based on API response\n }\n });\n }", "function followOpt(username){\n const follow = document.getElementById('follow_button_3');\n const unfollow = document.getElementById('follow_button_4');\n \n const headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization' : 'Token ' + checkStore('token'),\n };\n const method = 'PUT';\n\n follow.onclick = async function() {\n const path = 'user/follow?username='+ username;\n await api.makeAPIRequest(path, {\n method, headers\n }).then(function (res) {\n buttonInit();\n document.getElementById('follow_option').style.display = 'block';\n document.getElementById('follow_option').innerHTML = '';\n const info = createElement('b', res.message);\n document.getElementById('follow_option').appendChild(info);\n location.reload(); \n });\n }\n\n unfollow.onclick = async function() {\n const path = 'user/unfollow?username='+ username;\n await api.makeAPIRequest(path, {\n method, headers\n }).then(function (res) {\n buttonInit();\n document.getElementById('follow_option').style.display = 'block';\n document.getElementById('follow_option').innerHTML = '';\n const info = createElement('b', res.message);\n document.getElementById('follow_option').appendChild(info);\n location.reload(); \n });\n }\n}", "function ProfileCardFollow(){\n PeopleService.Follow($rootScope.UserCard.id)\n .then(\n resolve => {\n $rootScope.UserCard.fav = true ;\n $rootScope.User.favs = resolve.data ;\n }\n );\n }", "async function determine_follow(user_id_1, user_id_2){\r\n // console.log(\"User Visiting: \" + user_id_1 + \" User Being Visited: \" + user_id_2);\r\n\tconst follows = await fetch('/following/user/' + user_id_1 + '/' + user_id_2);\r\n const data = await follows.json();\r\n // console.log(data);\r\n return data.follows; // follows is the actual attribute name \r\n}", "function init() {\n if (vm.isAuthenticated()) {\n vm.isFollowed = vm.user.followers.find(x => x._id == vm.currentUser._id) !== undefined;\n }\n }", "function tofollow(){\n const follow_2 = document.getElementById('follow_button_2');\n follow_2.onclick = function() {\n const username = document.getElementById('funame').value;\n if (! username){\n window.alert(\"The username must not left empty!\");\n return false;\n }\n const path = 'user/?username='+ username;\n const headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization' : 'Token ' + checkStore('token'),\n };\n const method = 'GET';\n api.makeAPIRequest(path, {\n method, headers\n }).then(function (res) {\n buttonInit();\n document.getElementById('follow_option').style.display = 'block';\n document.getElementById('follow_option').innerHTML = '';\n\n if ('username' in res){\n const info = createElement('b', username + ' exists !\\xa0\\xa0\\xa0');\n const follow = createElement('li', 'Follow', { class:'nav-item', id: \"follow_button_3\", style: \"cursor:pointer\" });\n const unfollow = createElement('li', 'Unfollow', { class:'nav-item', id: \"follow_button_4\", style: \"cursor:pointer\" });\n document.getElementById('follow_option').appendChild(info); \n document.getElementById('follow_option').appendChild(follow);\n document.getElementById('follow_option').appendChild(unfollow);\n followOpt(username); \n }\n else{\n const info = createElement('b', username + ' does not exist !\\xa0\\xa0\\xa0');\n document.getElementById('follow_option').appendChild(info);\n }\n });\n }\n}", "function follow_user() {\n username = document.querySelector('#username').textContent;\n\n const request = new Request(\n `/follow/${username}/`,\n {headers: {'X-CSRFToken': csrftoken}}\n );\n\n fetch(request, {\n method: 'POST',\n mode: 'same-origin'\n })\n .then(response => response.json())\n .then(result => {\n // Print error message\n console.log(result);\n });\n\n // Change the button text\n buttonText = document.querySelector('#followButton');\n if (buttonText.innerHTML === 'Follow') buttonText.innerHTML = 'Unfollow';\n else buttonText.innerHTML = 'Follow';\n \n}", "async follow(options) {\n return await this.client.user.followPlaylist(this.id, options);\n }", "function followClicked(memberID, loginName) {\n // call the function to add json object that contains\n // the id of the member followed and the login name\n addFollow({\n id: memberID,\n login: loginName,\n }).then((newFollow) => {\n // 'update' the list of people followed\n setFollowed(followed.concat(newFollow));\n });\n }", "function Profile({profile, photosCollection}) {\n\n const user = userData();\n\n const[isFollowedPofile, setIsFollowedPofile] = useState(false) \n\n\n console.log(\"profile\", profile)\n console.log(\"authUser\", user)\n\n\n const handleFollow = async () => {\n\n await updateFollowingAuthenticatedUser(user.docId, profile.userId, isFollowedPofile )\n await updateFollowerSuggestedUser(profile.docId, user.userId, isFollowedPofile)\n\n setIsFollowedPofile(!isFollowedPofile)\n\n }\n\n useEffect( () => {\n\n async function checkIsUserFollowedProfile(){\n const isFollowed = await isLoggedUserFollowedProfile(user.username, profile.userId)\n setIsFollowedPofile(isFollowed)\n }\n\n\n if(user.userId != profile.userId){\n checkIsUserFollowedProfile()\n }\n \n\n }, [profile])\n\n return !profile?.docId && !user?.docId ? (\n <Skeleton height={500} width={900}/>\n ) : (\n <div className=\"sm: mx-1.5\">\n <div className=\"header flex w-full\">\n\n {/* PHOTO */}\n <section className=\"w-1/2 mr-2 flex justify-center object-contain\">\n <img src={`/images/avatars/${profile.username}.jpg`} \n className=\"rounded rounded-full sm:w-header-profile-photo sm-max:w-header-profile-photo-sm h-auto\"\n alt=\"\"/>\n </section>\n\n\n <section className=\"w-full max-w-header-profile\">\n {/* USERNAME + BUTTON FOLLOW */}\n <div className=\"flex mb-5 sm:items-center sm-max:flex-col\">\n <p className=\"text-2xl sm:mr-5 sm-max:bg-white\">{profile.username}</p> \n {\n profile?.userId != user?.userId ? (\n <button\n onClick={() => handleFollow()}\n className=\"bg-blue-post font-semibold text-white text-sm py-1 px-5 sm:w-auto sm-max: w-full\">\n {isFollowedPofile ? \"Followed\" : \"Follow\"}\n </button>\n ) : (\n <></>\n )\n }\n </div>\n\n {/* NUMBER POST, FOLLOWERS, AND FOLLOWING */}\n <ul className=\"flex w-full mb-5 sm-max:hidden\">\n <li className=\"mr-7\"><b className=\"font-semibold\"> {photosCollection?.length} </b> {photosCollection?.length <= 1 ? \"post\" : \"posts\"}</li>\n <li className=\"mr-7\"><b className=\"font-semibold\"> {profile.followers?.length} </b> {profile.followers?.length <= 1 ? \"follower\" : \"followers\"}</li>\n <li className=\"\">{profile.following?.length} following</li>\n </ul>\n <p className=\"break-words sm-max:hidden\">{profile?.fullName}</p>\n </section>\n\n </div>\n\n {/* RESPONSIVE If THE SIZE IS SMALL */}\n {/* NUMBER POST, FOLLOWERS, AND FOLLOWING */}\n <span>\n <p className=\"break-words mt-4 px-5 sm:hidden\">{profile?.fullName}</p>\n <ul className=\"flex w-full justify-around mt-5 sm:hidden\">\n <li><b className=\"font-semibold\"> {photosCollection?.length} </b> {photosCollection?.length <= 1 ? \"post\" : \"posts\"}</li>\n <li><b className=\"font-semibold\"> {profile.followers?.length} </b> {profile.followers?.length <= 1 ? \"follower\" : \"followers\"}</li>\n <li>{profile.following?.length} following</li>\n </ul>\n </span>\n \n\n\n </div>\n )\n}", "function FollowUnfollow(props) {\n\n\n\n const { userInfo, currentUsername, setFollowers } = props\n\n const [isFollowing, setIsFollowing] = useState(false)\n\n useEffect(() => {\n \n const followerList = userInfo.connections.followers.map(follower => follower.follower)\n if (followerList.includes(currentUsername)) {\n setIsFollowing(true)\n } else {\n setIsFollowing(false)\n }\n\n }, [currentUsername, userInfo.connections.followers])\n\n\n //hiddenText, buttonColor\n\n const [[, , isFollowError,], setFollowData]\n = useApi(operations.FOLLOW, {})\n const [[, , isUnfollowError,], setUnfollowData]\n = useApi(operations.UNFOLLOW, {})\n\n const handleOnClick = e => {\n e.preventDefault()\n if (isFollowing) {\n setUnfollowData({\n urlVariables: [userInfo.username]\n })\n setFollowers(prevFollowers => {\n const newFollowers = [...prevFollowers]\n return newFollowers.filter(follower => follower.follower !== currentUsername)\n })\n setIsFollowing(false)\n\n } else {\n setFollowData({\n payload: {\n followee: userInfo.username,\n }\n })\n setFollowers(prevFollowers => {\n const newFollowers = [{\n follower: currentUsername,\n since: new Date().getFullYear(),\n }]\n return newFollowers.concat(prevFollowers)\n })\n setIsFollowing(true)\n }\n }\n\n // useEffect(() => {\n\n // console.log(\"useEffect 2 executed\")\n\n // if (isFollowing) {\n\n // visibleText = \"Following\"\n // hiddenText = \"Unfollow\"\n // buttonColor = \"green\"\n // } else {\n\n // visibleText = \"Follow\"\n // hiddenText = \"Follow\"\n // buttonColor = \"blue\"\n // }\n // }, [isFollowing])\n\n // console.log(\"visibleText:\", visibleText, \"Hidden Text:\", hiddenText, \"buutoncolor:\", buttonColor)\n\n\n return (\n\n <Card.Content extra>\n\n {/* <Button disabled={isFollowLoading || isUnfollowLoading}\n //primary\n animated='fade'\n onClick={handleOnClick}\n color={isFollowLoading || isUnfollowLoading\n ? 'grey'\n : buttonColor}\n > */}\n {\n isFollowing ?\n <Button animated='fade' color=\"green\" onClick={handleOnClick}>\n <Button.Content visible>Following</Button.Content>\n <Button.Content hidden>Unfollow</Button.Content>\n </Button>\n :\n <Button animated='fade' color=\"blue\" onClick={handleOnClick}>\n <Button.Content visible>Follow</Button.Content>\n <Button.Content hidden>Follow</Button.Content>\n </Button>\n }\n\n\n {isFollowError || isUnfollowError ? <div>Operation Unsuccessfull. Try again</div> : null}\n </Card.Content>\n )\n}", "function get_following(time_itr) {\n document.getElementById('following_btn').removeEventListener('click', get_following)\n url = '../profile/api/get/data/following/users/'\n\n max_itr = 3\n\n if (max_itr == time_itr) {\n return //Actually Enable the load more followers button \n }\n\n fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-CSRFToken': csrftoken,\n },\n body: JSON.stringify({ 'deliverd': following_recived, 'user': user, 'per_call': 1 })\n })\n .then((resp) => {\n return resp.json()\n })\n .then((data) => {\n if (!data['is_following_anyone']) {} else {\n var following = data['following']\n following_recived += data['others']['deliverd']\n for (obj in following) {\n if (is_owner == 'True') {\n //Then Only Unfollow Buttons and if user presses a unfollow button, unfollow the user and remove the div \n var username__ = following[obj][2]\n var name__ = obj\n var profile_url__ = following[obj][1]\n var user_id__ = following[obj][0]\n\n item = ('<div id=\"user_following_div' + user_id__ + '\"style=\"display: block;margin:auto\" class=\"follower bg-light p-2\"><img src=\"' + profile_url__ + '\" class=\"img-follower\"><a class=\"follower-name\">' + name__ + '</a><br><button onclick=\"unfollow_user(' + \"'\" + username__ + \"'\" + ')\" data-id=\"' + username__ + '\"class=\"btn btn-info \">Unfollow</button><a href=\"#\" class=\"follower-link\" href=\"#\">' + username__ + '</a> </div>')\n\n document.getElementById('following').innerHTML += item\n\n } else {\n //We can have a ton different buttons -- Requested Follow Back Unfollow and Follow.\n var username__ = following[obj][2]\n var name__ = obj\n var profile_url__ = following[obj][1]\n var user_id__ = following[obj][0]\n var button_text = following[obj][3][0]\n var button_on_click = following[obj][3][1]\n var button_on_click_func_parameters = following[obj][3][2]\n item = ('<div id=\"user_following_div' + user_id__ + '\"style=\"display: block;margin:auto\" class=\"follower bg-light p-2\"><img src=\"' + profile_url__ + '\" class=\"img-follower\"><a class=\"follower-name\">' + name__ + '</a><br><button id=\"button_following_id' + username__ + '\" onclick=\"' + button_on_click + \"'\" + button_on_click_func_parameters + \"')\" + '\" data-id=\"' + username__ + '\"class=\"btn btn-info \">' + button_text + '</button><a href=\"#\" class=\"follower-link\" href=\"#\">' + username__ + '</a> </div>')\n\n document.getElementById('following').innerHTML += item\n\n }\n\n }\n\n if (data['others']['has_more']) {\n get_following(time_itr + 1)\n } else {\n\n return //No more Followers\n\n }\n }\n\n })\n}", "async setFlagForUser (userId) {\n\t\tlet op;\n\t\t// set or clear flag\n\t\tif (this.clear) {\n\t\t\top = { $unset: { [this.flag]: true } };\n\t\t}\n\t\telse {\n\t\t\top = { $set: { [this.flag]: true } };\n\t\t}\n\t\tawait this.data.users.updateDirect({ _id: this.data.users.objectIdSafe(userId) }, op);\n\n\t\t// send pubnub update on user's me-channel\n\t\tconst requestId = UUID();\n\t\tconst message = {\n\t\t\tuser: Object.assign(op, { id: userId }),\n\t\t\trequestId\n\t\t};\n\t\tconst channel = `user-${userId}`;\n\t\ttry {\n\t\t\tawait this.pubnubClient.publish(\n\t\t\t\tmessage,\n\t\t\t\tchannel\n\t\t\t);\n\t\t}\n\t\tcatch (error) {\n\t\t\t// this doesn't break the chain, but it is unfortunate\n\t\t\tthis.logger.warn(`Unable to publish user op to channel ${channel}: ${JSON.stringify(error)}`);\n\t\t}\n\t}", "function getFollowings(){\n apiService.getFollowings({user: vm.name}).$promise.then(function(result) {\n vm.followingUsers = result.following\n console.log('following are '+vm.followingUsers)\n vm.followingUsers.map(function (name){\n if (!vm.followmap[name]){\n vm.followmap[name] = {}\n }\n if (!vm.followmap[name]['pic']) {// store their profile pics\n apiService.getPicture({user: name}).$promise.then(function(result) {\n vm.followmap[name]['pic'] = result.pictures[0].picture\n }, function(error) {\n console.log('Error getting profile pic for user: '+name, error)\n })\n }\n if (!vm.followmap[name]['status']) {// store their status\n apiService.getStatuses({user: result.following.join()}).$promise.then(function(result) {\n result.statuses.map(function(object) {\n vm.followmap[object.username]['status'] = object.status\n })\n }, function(error) {\n console.log('Error getting statues for multiple users', error)\n })\n }\n })\n }, function(error) {\n console.log('Error in getting followers', error)\n\n })\n }", "function getFollowingUsers(req, res){\n\tvar user_id = req.user.sub;\n\tvar page = 1;\n\n\tif(req.params.id && req.params.page){\n\t\tuser_id = req.params.id;\n\t\tpage = req.params.page;\n\t}\n\tif(req.params.id){\n\t\tif(req.params.id.length>=4){ \n\t\t\tuser_id = req.params.id;\n\t\t}else{\n\t\t\tpage = req.params.id;\n\t\t}\n\t}\n\n\tvar items_per_page = 5;\n\n\t// Extract all user data with populate()\n\tFollow.find({user:user_id}).populate('followed', '_id name surname nick image status').paginate(page, items_per_page, (err, follows, total) => {\n\t\tif(err) return res.status(500).send({message: 'Server error'});\n\n\t\tUser.findById(user_id, '-password', (err, user) => {\n\t\t\tif(err) return res.status(500).send({message: 'Error in the request'});\n\t\t\tif(!user) return res.status(404).send({message: 'The user doesnt exist'});\n\t\t\tif(total == 0) return res.status(200).send({user : user});\n\n\t\t\tfollowUserIds(req.user.sub).then((value) => {\n\t\t\t\treturn res.status(200).send({\n\t\t\t\t\ttotal : total,\n\t\t\t\t\tuser: user,\n\t\t\t\t\tpages : Math.ceil(total/items_per_page),\n\t\t\t\t\tfollows : follows,\n\t\t\t\t\tusers_following : value.following,\n\t\t\t\t\tusers_follow_me : value.followed,\n\t\t\t\t\titems_per_page: items_per_page\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t});\n}", "function _followAll() {\n // Go to top\n window.scrollTo(0,0);\n\n for(var i = 0; i <= totalFollowers; i++) {\n // Get each button from the buttons array\n var btn = btnArray[i];\n /**\n * Iterate over each span tag inside the btn element.\n * If the btn has text \"Follow\" then only click the button\n */\n for(var j = 0; j < btn.children.length; j++) {\n /**\n * Check the display property of current span element.\n * If the display property of current span element is \"block\" and the\n * text is \"Following\", then don't click the button. We are already follwing\n * the person. (We would unfollow that person if we click the button)\n */\n var currentStyleOfSpan = _getStyle(btn.children[j], \"display\");\n if(currentStyleOfSpan == \"block\" && btn.children[j].innerHTML.trim() == \"Following\") {\n console.log(\"Time to break, move on to next btn\");\n break;\n } else if(currentStyleOfSpan == \"block\" && btn.children[0].childElementCount == 1){\n /** btn.children[0].childElementCount == 1, true when span element contains another\n * span tag \"<span class=\"Icon Icon--follow\"></span>\" (this is the follow icon)\n * and text \"Follow\". This is the Follow button.\n */\n btn.click()\n\n /**\n * TEST CASE: This is a test case. To be used while development. This test case\n * changes the background color of ONLY \"Follow\" buttons instead of clicking them.\n */\n // common.test(btn, \"yellow\");\n }\n }\n }\n // Success message\n alert(\"Successfully followed!\");\n }", "function removeFollowing(req, res) {\n var username = req.user;\n var toBeRemovedFollowing = req.params.user ? req.params.user.split(',')[0] : null;\n if (!toBeRemovedFollowing) {\n res.send(400)\n }\n Profile.find({username: username}, function (err, result) {\n if (err) return res.json({error: \"Error finding \" + username + Profile.toString()});\n var user = result[0];\n var index = user.following.findIndex(function (following) {\n return following === toBeRemovedFollowing\n });\n user.following.splice(index, 1);\n user.save(function (err, user) {\n if (err) return res.json({error: \"Error saving \" + user.username + Profile.toString()});\n res.send({\"username\": user.username, \"following\": user.following})\n })\n });\n}", "follow() {\n this.setState({\n isFollowingChecked: false\n });\n\n axios\n .get(\n `${DOMAIN_NAME}/api/follow/${this.state.email}`,\n this.configAxios\n )\n .then(res => {\n this.setState({\n isFollowing: res.data.isFollowing,\n isFollowingChecked: true\n });\n console.log(\"Is following \", res.data);\n })\n .catch(error => {\n if (axios.isCancel(error)) {\n console.log(\"View Profile Component Unmounted\");\n }\n\n console.log(\"Is following \", error);\n });\n }", "function makeFriends(userA, userB){\n //If one of the user IDs doesn't exist, stop\n let user, user2;\n users.forEach(value => {\n if(value.username == userA) {\n user = value;\n }\n if(value.username == userB) {\n user2 = value;\n }\n });\n if(!user || !user2) {\n return;\n }\n\n let indexUser1 = users.findIndex(i => i.username === user.username);\n let indexUser2 = users.findIndex(i => i.username === user2.username);\n\n //If the users are already friends, stop\n if(users[indexUser1].friends.includes(user2)){\n return;\n }\n\n //Update both so they are now friends\n users[indexUser1].friends.push(users[indexUser2]);\n users[indexUser2].friends.push(users[indexUser1]);\n\n if(users[indexUser1].FriendRequests.includes(user2)) {\n let indexFriend1 = users[indexUser1].FriendRequests.findIndex(i => i === user2);\n users[indexUser1].FriendRequests.splice(indexFriend1,1);\n }\n else if(users[indexUser2].FriendRequests.includes(user)) {\n let indexFriend2 = users[indexUser2].FriendRequests.findIndex(i => i === user);\n users[indexUser2].FriendRequests.splice(indexFriend2,1);\n }\n}", "function followUser(userId) {\n\tconsole.log(userId);\n\t$.ajax({\n\t\ttype: 'POST',\n\t\turl: '/user/follow',\n\t\tdata: {friendId:userId},\n\t\terror: function(){\n\t\t\t// Error function goes here\n\t\t\tconsole.log(\"Error, your request was not sent\");\n\t\t\t$('#'+userId).css({'font':'red'});\n\t\t},\n\t}).done(function(){\n\t\t// disalbe button\n\t\t$('#'+userId).css({'font':'green'});\n\t});\n}", "function is_following() {\n username = document.querySelector('#username').textContent;\n\n const request = new Request(\n `/follow/${username}`,\n {headers: {'X-CSRFToken': csrftoken}}\n );\n\n fetch(request, {\n method: 'GET',\n mode: 'same-origin'\n })\n .then(response => response.json())\n .then(result => {\n // Print error message\n console.log(result);\n if (result['is being followed']) {\n document.querySelector('#followButton').innerHTML = 'Unfollow'\n }\n else {\n document.querySelector('#followButton').innerHTML = 'Follow'\n }\n });\n}", "function set_multiple_users(enabled) {\n transition_was_enabled = current_transition >= 0;\n modify_transition(false);\n\n if (enabled) {\n var n_users = 2;\n user_positions = [];\n for (var i=0; i<n_users; ++i)\n user_positions.push([user_x, height+icon_size*(i-(n_users-1)/2)]);\n } else {\n user_positions = [[user_x,height]];\n }\n \n var u = users.selectAll(\"image\")\n .data(user_positions);\n u\t// Definition for the creation of new users\n .enter().append(\"image\")\n\t\t.attr({\n\t\t\t\"xlink:href\": function(d, i) { if (i==0) { return \"img/user-computer-yellow.png\"; } else { return \"img/user-computer-blue.png\"; } },\n\t\t\t\"x\": user_x-icon_size/2,\n\t\t\t\"y\": height-icon_size/2,\n\t\t\t\"height\": icon_size,\n\t\t\t\"width\": icon_size\n\t\t})\n u\t// Move the user to the right position\n .transition()\n\t\t.attr(\"opacity\", 1.0)\n .attr(\"x\", function(d, i) { return d[0]-icon_size/2; } )\n\t\t.attr(\"y\", function(d, i) { return d[1]-icon_size/2; } )\n .each(\"end\", function() {modify_transition(transition_was_enabled);} )\n u\t// What to do when a user is removed\n .exit()\n .remove();\n\n\n}", "async function followThisUser(identity_user_id, user_id) {\n try {\n var following = await Follow.findOne({ user: identity_user_id, followed: user_id }).exec()\n .then((following) => {\n return following;\n })\n .catch((err) => {\n return handleError(err);\n });\n var followed = await Follow.findOne({ user: user_id, followed: identity_user_id }).exec()\n .then((followed) => {\n return followed;\n })\n .catch((err) => {\n return handleError(err);\n });\n return {\n following: following,\n followed: followed\n }\n }\n catch (e) {\n console.log(e);\n }\n}", "async updateMentionedUsers () {\n\t\tawait Promise.all((this.mentionedUsers || []).map(async user => {\n\t\t\tawait this.updateMentionsForUser(user);\n\t\t}));\n\t}", "function UpdateUsers(userList) {\n users.empty();\n for (var i = 0; i < userList.length; i++) {\n if (userList[i].username != myName) {\n users.append('<li class=\"player\" id=\"' + userList[i].id + '\"><a href=\"#\">' + userList[i].username + '</a></li>')\n }\n }\n }", "function unfollowUser(req ,res) {\n var userId1 = req.params.userId1;\n var userId2 = req.params.userId2;\n userModel\n .unfollowUser(userId1 , userId2)\n .then(function (user) {\n userModel\n .unfollowingUser(userId2 , userId1)\n .then(function (fake) {\n res.send(user);\n },function (err) {\n response.status=\"KO\";\n response.description=\"Unable to un follow the given user\";\n res.json(response);\n });\n } , function (err) {\n response.status=\"KO\";\n response.description=\"Unable to unfollow the given user\";\n res.json(response);\n });\n }", "function UpdateFollowerPosition(followerID : int , player : NetworkPlayer, pos : Vector3, rot : Quaternion){\n\tif(followerHash.Contains(followerID)){\n\t\tvar follower : ViralFollowerNetwork;\n\t\tfollower = followerHash[followerID] as ViralFollowerNetwork;\n\t\tif(follower.currentNetworkPlayer == player){\n\t\t\tfollower.nextPosition = pos;\n\t\t\tfollower.nextRotation = rot;\n\t\t}\n\t}\n}", "updatePins() {\n\t var tem = this.props.screenProps.userData.follow.slice(0)\n\t tem.push(this.props.screenProps.user)\n db.collection('Pins')\n .find({'username': { $in:tem}})\n .then(pins => this.setState({ pins: pins.reverse() }));\n }", "function updateRelationships(){\n\t\tconsole.log('gonna updateRelationships')\n\t\t//post per aggiornare relazione tra past e current.\n\t\tdate = new Date(Date.now());\n\t\t$.post(\"/relation\",{\n\t\t\tprevious: pastPlayerVideoId,\n\t\t\tclicked: getCurrentPlayerId(),\n\t\t\trecommender: currentPlayerRecommender,\n\t\t\tlastSelected: date\n\t\t}).done((data)=>{\n\t\t\tconsole.log('Relations Updated');\n\t\t})\n\t}", "function followPlayer(follower, leader, offsetX, offsetY) {\n directionX = leader.body.velocity.x > 1 ? 1 : -1\n follower.x = leader.body.x + (offsetX * directionX);\n follower.y = leader.body.y + offsetY;\n return follower;\n}", "function onToggleFollowingInsightSuccess(data) {\n\tvar favicon = $(\".addfav\", \".insight_\" + data.uniqueId);\n\tif(data.follow) {\n\t\tfavicon.addClass(\"active\");\n\t} else {\n\t\tfavicon.removeClass(\"active\");\n\t}\n}", "function follow(id)\n{\n\t\t$.post(\"/follow/execute\", {\"follow\": \"yes\", \"id\": id},function(data)\n\t\t{\n\t\t\t\tif(data.state==\"success\")\n\t\t\t\t\t\tnotify(\"Vous suivez désormais \" + data.follow +\".\");\n\t\t\t\telse\n\t\t\t\t\t\tnotify(\"Une erreur est survenue.\");\n\t\t} );\n}" ]
[ "0.78267974", "0.6657105", "0.65614206", "0.6557745", "0.65547055", "0.64684045", "0.6447828", "0.6396043", "0.6362754", "0.6319824", "0.62682825", "0.6210443", "0.6200791", "0.6176093", "0.61171323", "0.61151266", "0.60980606", "0.6068679", "0.60037637", "0.59808797", "0.5957137", "0.5925945", "0.5914824", "0.5895823", "0.58919966", "0.58832705", "0.584438", "0.5840225", "0.58366877", "0.5808018", "0.58013004", "0.57597774", "0.5755164", "0.5734228", "0.5723252", "0.5719272", "0.5718532", "0.5708469", "0.570696", "0.56942624", "0.56891245", "0.56882536", "0.56856847", "0.56457645", "0.5608118", "0.5594463", "0.55860984", "0.55736136", "0.5572208", "0.55429757", "0.55390674", "0.55334705", "0.5519097", "0.5487564", "0.54767036", "0.54732025", "0.5441563", "0.5427314", "0.54228514", "0.5418199", "0.5396407", "0.5387861", "0.53650767", "0.53618747", "0.5343652", "0.53417104", "0.53404415", "0.53398585", "0.53313345", "0.533132", "0.53282005", "0.5325331", "0.5321615", "0.5319985", "0.53177446", "0.5317107", "0.5316442", "0.5294635", "0.52920437", "0.52802753", "0.5278668", "0.5276024", "0.5269289", "0.52639425", "0.5261537", "0.5253075", "0.5253034", "0.52469903", "0.5244053", "0.52409", "0.5239479", "0.52389437", "0.52312636", "0.5229418", "0.5228913", "0.52243835", "0.5221351", "0.52157736", "0.52093995", "0.5207859" ]
0.70508695
1
Add user to following List
followUser(state, userId) { state.loading.following = true; state.loading.follow = true; let user = state.userList.find((user) => user._idUser === userId); if (user) { state.followingUsers.push(user); state.nonFollowingUsers = state.nonFollowingUsers.filter( (user) => user._idUser !== userId ); } state.loading.following = false; state.loading.follow = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "followUser(name, followedName) {\n if (this.findUser(name)) {\n if (this.findUser(followedName)){\n this.findUser(name).addFollower(this.findUser(followedName));\n }\n }\n }", "function follow() {\n UserService.follow(vm.currentUser, vm.user)\n .then(res => {\n vm.user.followers.push(vm.currentUser._id);\n vm.isFollowed = true;\n\n // send notification to the server that user is followed\n socket.emit('notification', {'to': vm.user._id, 'from': vm.currentUser._id, 'author': vm.currentUser.username, 'type': 'follow'});\n });\n }", "setFollowUserList(state) {\n state.userList.forEach((user) => {\n let userF = state.currentUser.following.find(\n (following) => following._idUser === user._idUser\n );\n if (userF) {\n state.followingUsers.push(user);\n } else {\n state.nonFollowingUsers.push(user);\n }\n });\n state.loading.following = false;\n state.loading.follow = false;\n }", "function addToFollowPage(id) {\n const list = JSON.parse(localStorage.getItem('followPage')) || []\n const user = users.find((user) => user.id === id)\n \n if (list.some((user) => user.id === id)) {\n return alert(\"Already followed.\")\n }\n list.push(user)\n localStorage.setItem('followPage', JSON.stringify(list))\n }", "function follow(req, res) {\n Profile.findById(req.user.profile)\n .then(followerProfile => {\n followerProfile.following.push(req.params.id)\n followerProfile.save()\n .then(()=> {\n Profile.findById(req.params.id)\n .then(followingProfile=>{\n followingProfile.followers.push(req.user.profile)\n followingProfile.save()\n })\n res.redirect(`/profiles/${req.params.id}`)\n })\n })\n .catch((err) => {\n console.log(err)\n res.redirect('/')\n })\n}", "function setFollowedUsers() {\n vm.followedUsers.forEach((user) => {\n for(var i = 0; i < vm.users.length; i++){\n if(user.username === vm.users[i].username){\n vm.users[i].follows = true;\n break;\n }\n }\n });\n }", "function addFollower() {\n followers = followers + 1;\n}", "function addUserToGamePlayerList(username) {\n console.log(\"adding \" + username);\n var thisPlayer = document.createElement('li');\n thisPlayer.classList.add('list-group-item','justify-content-between');\n thisPlayer.appendChild(document.createTextNode(username));\n if(gamePlayerList.children().length === 0) {\n var leaderBadge = document.createElement('span');\n leaderBadge.classList.add('badge','badge-success','badge-pill');\n leaderBadge.appendChild(document.createTextNode('Leader'));\n thisPlayer.appendChild(leaderBadge);\n }\n\n gamePlayerList.append(thisPlayer);\n}", "function followUser() {\n if (LoginService.isLoggedIn()) {\n UserProfileService\n .followUser(vm.userInfo.id)\n .then(function () {\n vm.isFollowing = true;\n\n //reload details for the current user who has been followed/unfollowed\n getUserInfoForOtherUsers(vm.userInfo.userName);\n });\n }\n }", "function updateUserList(users) {\n users.forEach(function(user) {\n if (user.id == me.id) {return;}\n addUser(user);\n });\n}", "function addUser(userList, user) {\r\n let newList = Object.assign({}, userList)\r\n newList[user.name] = user\r\n return newList\r\n}", "function addUser(userList, user){\n let newList = Object.assign({}, userList);\n newList[user.name] = user;\n return newList;\n }", "function addToOnlineUsers(nickname) {\n var onlineList = $('#online_now');\n var onlineUsers = $('<li>', {\n html : nickname,\n id : nickname\n });\n onlineList.append(onlineUsers);\n }", "function addUserToElement(userID,itemNo) {\n\t\tvar idListLength, i;\n\t\tidListLength = gapi.hangout.data.getValue(\"listTxt\" + itemNo + \"listID\") || \"0\";\t\t\t// get length of current list ID list\n\t\tfor (i = 1; i <= idListLength; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ---\n\t\t\tif (userID == gapi.hangout.data.getValue(\"listTxt\" + itemNo + \"listID\" + i)){ return; };// ---Check for id exsisting already if so quit\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ---\n\t\tidListLength = (parseInt(idListLength, 10) + 1).toString();\t\t\t\t\t\t\t\t\t// increase target list length\n\t\taddNewItemToList (\"listTxt\" + itemNo + \"listID\",idListLength,userID);\t\t\t\t\t\t// add ID to list\n\t}", "function addUser(newUserList, requestUserId) {\n setUsers(newUserList)\n removeInviteUser(requestUserId)\n }", "function followClicked(memberID, loginName) {\n // call the function to add json object that contains\n // the id of the member followed and the login name\n addFollow({\n id: memberID,\n login: loginName,\n }).then((newFollow) => {\n // 'update' the list of people followed\n setFollowed(followed.concat(newFollow));\n });\n }", "function addFollow(req, res, next) { \n db\n .task(t => { \n return t.none(\"UPDATE users SET user_followers = array_append(user_followers, ${username}) WHERE id=${user_id}\", \n { username: req.body.username, user_id: req.body.user_id })\n .then(user => { \n return t.none(\"UPDATE users SET user_following = array_append(user_following, ${user_username}) WHERE username=${username}\", \n { user_username: req.body.user_username, username: req.body.username, user_id: req.body.user_id })\n })\n })\n .then(function(data) {\n res.status(200).json({\n status: \"success\",\n message: \"Added one follower\"\n });\n })\n .catch(function(err) {\n return next(err);\n });\n}", "function UpdateUsers(userList) {\n users.empty();\n for (var i = 0; i < userList.length; i++) {\n if (userList[i].username != myName) {\n users.append('<li class=\"player\" id=\"' + userList[i].id + '\"><a href=\"#\">' + userList[i].username + '</a></li>')\n }\n }\n }", "function addFollows(follows) {\n var logo = \"https://www.gravatar.com/avatar/a2b6df699ae0cd59f5077a5cae4cf994/?s=80&r=pg&d=mm\";\n var status = \"\";\n var online = false;\n // Add a Twitch account that was closed\n if (follows.indexOf(\"brunofin\") === -1) { follows.push([\"brunofin\",status,logo,online]); }\n // Add a Twitch account that never existed\n if (follows.indexOf(\"comster404\") === -1) { follows.push([\"comster404\",status,logo,online]); }\n // Add some Twitch accounts that are usually active\n if (follows.indexOf(\"OgamingSC2\") === -1) { follows.push([\"OgamingSC2\",status,logo,online]); }\n if (follows.indexOf(\"ESL_SC2\") === -1) { follows.push([\"ESL_SC2\",status,logo,online]); }\n if (follows.indexOf(\"cretetion\") === -1) { follows.push([\"cretetion\",status,logo,online]); }\n if (follows.indexOf(\"freecodecamp\") === -1) { follows.push([\"freecodecamp\",status,\"https://static-cdn.jtvnw.net/jtv_user_pictures/freecodecamp-profile_image-d9514f2df0962329-300x300.png\",online]); }\n if (follows.indexOf(\"storbeck\") === -1) { follows.push([\"storbeck\",status,logo,online]); }\n if (follows.indexOf(\"habathcx\") === -1) { follows.push([\"habathcx\",status,logo,online]); }\n if (follows.indexOf(\"RobotCaleb\") === -1) { follows.push([\"RobotCaleb\",status,logo,online]); }\n if (follows.indexOf(\"noobs2ninjas\") === -1) { follows.push([\"noobs2ninjas\",status,logo,online]); }\n }", "follow(entity) {\n this.following = entity;\n }", "updateTrackList(following) {\n // Add any new follows to the trackedUsers list\n for (let i = 0; i < following.length; i++) {\n let user = following[i];\n\n if (!(user in this.botStatus.trackedUsers)) {\n this.botStatus.trackedUsers[user] = 0;\n }\n }\n\n // Remove any trackedUsers that the bot is no longer following\n for (let userID in this.botStatus.trackedUsers) {\n if (!this.utils.isInArray(following, userID)) {\n delete this.botStatus.trackedUsers[userID];\n }\n }\n }", "function addUser(user) {\n users.push(user);\n }", "function addingListUsers(users){\n for(let i = 0; i < users.length; i++){\n const HTMLString = playListTemplate(users[i])\n const HTMLTemplate = playListHTMLTemplate(HTMLString);\n $playlist.append(HTMLTemplate);\n }\n }", "function appendUser(user) {\n let li = document.createElement(\"li\");\n li.innerHTML = user;\n document.querySelector(\"#users\").append(li);\n var chatWindow = document.getElementById(\"chatWindow\");\n chatWindow.scrollIntoView({ behavior: 'smooth', block: 'end' });\n chatWindow.scrollTop = chatWindow.scrollHeight;\n }", "function setFollowingButton () {\n\tvar uid = new User(document.cookie).id();\n\tif (uid) {\n\t\tmyFtButton.setAttribute('href', '/users/' + uid + '/following/new');\n\t\tmyFtButton.textContent = 'Following';\n\t\tmyFtButton.insertAdjacentHTML('beforeend', ' <span class=\"notify-badge\"></span>');\n\t}\n}", "function add(user, members) {\n\tvar list = document.createElement(\"li\");\n\tvar textnode = document.createTextNode(user);\n\tvar ul_len = document.getElementById(members).childNodes.length;\n\n\t// create input element\n\tvar input = document.createElement(\"input\");\n\tinput.setAttribute(\"type\", \"hidden\");\n\tinput.setAttribute(\"name\", members + ul_len);\n\tinput.setAttribute(\"id\", members + ul_len);\n\tinput.setAttribute(\"value\", user);\n\tlist.appendChild(input);\n\tlist.appendChild(textnode);\n\tlist.setAttribute('class', 'pr-5');\n\n\t// add remove button\n\tvar remove = removeBtn();\n\tlist.appendChild(remove);\n\tdocument.getElementById(members).appendChild(list);\n\tremove.onclick = function () {\n\t\tdocument.getElementById(members).removeChild(list);\n\t}\n}", "function followUser(username) {\n if (!isLoggedIn()) return;\n\n //reset paging so we make sure our results start at the beginning\n fullActivityFeed.resetPaging();\n userFeed.resetPaging();\n\n var options = {\n method:'POST',\n endpoint:'users/me/following/users/' + username\n };\n client.request(options, function (err, data) {\n if (err) {\n $('#now-following-text').html('Aw Shucks! There was a problem trying to follow <strong>' + username + '</strong>');\n } else {\n $('#now-following-text').html('Congratulations! You are now following <strong>' + username + '</strong>');\n showMyFeed();\n }\n });\n }", "async following (req, res, next) {\n await User.getFollowing(req.params.username, (err, following) => {\n if (err) return next(err)\n\n res.send({ following })\n })\n }", "addUser(user) {\n /* istanbul ignore else */\n if (!this.active_list) {\n this.active_list = [];\n }\n const index = this.active_list.findIndex((a_user) => a_user.email === user.email);\n /* istanbul ignore else */\n if (index < 0) {\n this.active_list = [...this.active_list, user];\n }\n this.setValue(this.active_list);\n this.search_str = '';\n }", "function addToPeersList() {\n if(peersArr.length < 1){\n role = 'hub';\n return peers.$set(myId, {username: username, role: role});\n } else {\n role = 'spoke';\n return peers.$set(myId, {username: username, role: role});\n }\n\n }", "function addUserToList(user_name, user_list) {\r\n if (!user_list) {\r\n user_list = document.getElementById('user_list');\r\n }\r\n\r\n var li = document.createElement(\"li\");\r\n var span_name = document.createElement(\"span\");\r\n\r\n li.id = user_name;\r\n span_name.className += \"chat_name\";\r\n span_name.onclick = function() {\r\n var text_box = document.getElementById('msg');\r\n text_box.value = text_box.value + user_name + \": \";\r\n document.getElementById('msg').focus();\r\n };\r\n span_name.appendChild(document.createTextNode(user_name));\r\n\r\n li.appendChild(span_name);\r\n user_list.appendChild(li);\r\n}", "function followUser(screenName) {\n bot.post('friendships/create', { screen_name: screenName }, (err, data, response) => {\n if (err) console.log(err)\n console.log(data)\n });\n}", "function addUser(newUser) {\n userDataArray.push(newUser);\n updateDOM();\n}", "function saveUsers(user){\n users.unshift(user)\n return users\n}", "function createNewUser(userObj) {\r\n var node = document.createElement(\"LI\");\r\n var innerElement = document.createTextNode(userObj.username + ' (' + userObj.email + ')');\r\n node.appendChild(innerElement);\r\n document.getElementById(\"users\").appendChild(node);\r\n }", "function removeFollower(e) {\n var followerInput = followInput.value;\n var req = new XMLHttpRequest();\n req.open('POST', '/users/' + currentUser.username + '/unfollow', true);\n req.addEventListener('load', function() {\n while (followingList.firstChild) {\n followingList.removeChild(followingList.firstChild);\n }\n\n for(var i = 0; i < currentUser.following.length; i++) {\n var following = createFollowingList(currentUser.following[i].username);\n followingList.appendChild(following);\n }\n followInput.value = null;\n });\n req.send(followerInput);\n}", "function addFriendEntry(el) {\n let template = document.querySelector(\"#friends-current\").content;\n let parent = document.querySelector(\".friends_current-parent\");\n let clone = template.cloneNode(true);\n clone.querySelector(\".paragraph\").textContent = el.username;\n // Add id to user\n clone.querySelector(\".button\").dataset.uuid = el._id;\n clone.querySelector(\"button\").addEventListener(\"click\", removeFriend);\n parent.appendChild(clone);\n // Create array for the friend for later use\n fluidFriendObject = {};\n}", "function insertNewUser(req, res, newuser) {\n newuser[\"following\"] = [];\n conn.collection('users').insert(newuser, function (err,docs) {\n if (err) {\n res.status(401).send('Error in registration');\n } else {\n passport.authenticate('local')(req, res, function () {\n res.send(req.user);\n })\n }\n });\n}", "function appendList(user) {\n \t$('#unordList').append('<li>' + user + '</li>');\n\n }", "function addUser(data) {\n var node = document.createElement('span');\n node.className = 'user';\n node.textContent = data[3];\n node.dataset.user = data[0];\n\n var deleteNode = document.createElement('span');\n deleteNode.className = 'delete';\n deleteNode.innerHTML = '&times;';\n node.appendChild(deleteNode);\n\n userList.insertBefore(node, input);\n\n input.placeholder = '';\n sendButton.disabled = false;\n\n sendView.resize();\n }", "function appendUser(user) {\n var username = user.username;\n /*\n * A new feature to Pepper, which is a permission value,\n * may be 1-5 afaik.\n *\n * 1: normal (or 0)\n * 2: bouncer\n * 3: manager\n * 4/5: (co-)host\n */\n var permission = user.permission;\n\n /*\n * If they're an admin, set them as a fake permission,\n * makes it easier.\n */\n if (user.admin) {\n permission = 99;\n }\n\n /*\n * For special users, we put a picture of their rank\n * (the star) before their name, and colour it based\n * on their vote.\n */\n var imagePrefix;\n switch (permission) {\n case 0:\n imagePrefix = 'normal';\n break;\n // Normal user\n case 1:\n // Featured DJ\n imagePrefix = 'featured';\n break;\n case 2:\n // Bouncer\n imagePrefix = 'bouncer';\n break;\n case 3:\n // Manager\n imagePrefix = 'manager';\n break;\n case 4:\n case 5:\n // Co-host\n imagePrefix = 'host';\n break;\n case 99:\n // Admin\n imagePrefix = 'admin';\n break;\n }\n\n /*\n * If they're the current DJ, override their rank\n * and show a different colour, a shade of blue,\n * to denote that they're playing right now (since\n * they can't vote their own song.)\n */\n if (API.getDJs()[0].username == username) {\n if (imagePrefix === 'normal') {\n drawUserlistItem('void', '#42A5DC', username);\n } else {\n drawUserlistItem(imagePrefix + '_current.png', '#42A5DC', username);\n }\n } else if (imagePrefix === 'normal') {\n /*\n * If they're a normal user, they have no special icon.\n */\n drawUserlistItem('void', colorByVote(user.vote), username);\n } else {\n /*\n * Otherwise, they're ranked and they aren't playing,\n * so draw the image next to them.\n */\n drawUserlistItem(imagePrefix + imagePrefixByVote(user.vote), colorByVote(user.vote), username);\n }\n}", "function streamUser() {\n var $body = $('.people-follow');\n for(var key in streams) {\n if(key === 'users') {\n for(var key in streams.users) {\n var user = key;\n var $user = $('<a id='+user+'></a><br>');\n $user.text('@' + user);\n $user.appendTo($body);\n }\n } \n }\n}", "function addUser(user) {\n\tdata.push(user);\n\tupdateDOM();\n}", "function addFriend(newFriend){\n\tthis.Friendlist = this.Friendlist + \", \" + newFriend;\n}", "_shiftNextUser() {\r\n this.getCurrentUser().isActive = false;\r\n this.users.push(this.users.shift());\r\n this.getCurrentUser().isActive = true;\r\n }", "addUserToFriendlist({ params }, res) {\n User.findOneAndUpdate(\n { _id: params.userId },\n { $push: { friends: params.friendId } },\n { new: true, runValidators: true }\n )\n .then(dbUserData => {\n if (!dbUserData) {\n res.status(404).json({ message: 'No user found with this id!' });\n return;\n }\n res.json(dbUserData);\n })\n .catch(err => res.status(400).json(err));\n }", "function addUserToList(panelName, userId) {\n // get role store\n var roleStore = window['roleStore_' + panelName];\n\n if(!isUserInStore(panelName, userId)) {\n\t// append user\n\t$('[data-panel-name=\"'+panelName+'\"] div.permission-panel-roles ul').append('<li><a data-panel-name=\"'+panelName+'\" data-panel-userid=\"'+userId+'\" href=\"javascript:;\">'+roleStore[userId]+'</a></li>');\n\n\t// run onclickuser to set onclick for roles\n\tonClickUser();\n\n\t// add user to storage\n\taddUserToStore(panelName, userId);\n }\n}", "function addToFavs()\n {\n favorites.push(users[0].userName);\n dismissResult();\n }", "function add_all_members(members, acc_owner) {\n\tvar users = g_members.split(\"&#39;\");\n\t// Removes the [] parantheses.\n\tusers.splice(0, 1);\n\tusers.pop();\n\n\t// Removes all comma values.\n\tfor (var i = users.length - 1; i--;) {\n\t\tif (users[i].match(\",\")) users.splice(i, 1);\n\t}\n\n\tfor (var i = 0; i < users.length; i++) {\n\t\tconsole.log(users[i]);\n\t\tconsole.log(acc_owner);\n\t\tif(users[i] == acc_owner) {\n\t\t\tvar list = document.createElement(\"li\");\n\t\t\tvar textnode = document.createTextNode(users[i]);\n\t\t\tvar ul_len = document.getElementById(members).childNodes.length;\n\t\t\n\t\t\t// create input element\n\t\t\tvar input = document.createElement(\"input\");\n\t\t\tinput.setAttribute(\"type\", \"hidden\");\n\t\t\tinput.setAttribute(\"name\", members + ul_len);\n\t\t\tinput.setAttribute(\"id\", members + ul_len);\n\t\t\tinput.setAttribute(\"value\", users[i]);\n\t\t\tlist.appendChild(input);\n\t\t\tlist.appendChild(textnode);\n\t\t\tlist.setAttribute('class', 'pr-5');\n\t\t\tdocument.getElementById(members).appendChild(list);\n\t\t} else {\n\t\t\tadd(users[i], members)\n\t\t}\t\n\t}\n\n}", "function loadFollowing() {\n UserService.getFollowing(vm.user.username, vm.loaded)\n .then(res => {\n vm.arr.push(...res);\n vm.loaded = vm.arr.length;\n });\n }", "async handleFollowers (thing, op, options = {}) {\n\t\t// if this is a legacy codemark, created before codemark following was introduced per the \"sharing\" model,\n\t\t// we need to fill its followerIds array with the appropriate users\n\t\tif (thing.get('followerIds') === undefined) {\n\t\t\top.$set.followerIds = await new CodemarkHelper({ request: this.request }).handleFollowers(\n\t\t\t\tthing.attributes,\n\t\t\t\t{\n\t\t\t\t\tmentionedUserIds: this.parentPost.get('mentionedUserIds'),\n\t\t\t\t\tteam: this.team,\n\t\t\t\t\tstream: this.stream,\n\t\t\t\t\tparentPost: this.parentPost\n\t\t\t\t}\n\t\t\t);\n\t\t}\n\n\t\t// also add this user as a follower if they have that preference, and are not a follower already\n\t\tconst userNotificationPreference = options.ignorePreferences ? 'involveMe' : \n\t\t\t((this.user.get('preferences') || {}).notifications || 'involveMe');\n\t\tconst followerIds = thing.get('followerIds') || [];\n\t\tif (userNotificationPreference === 'involveMe' && followerIds.indexOf(this.user.id) === -1) {\n\t\t\tif (op.$set.followerIds) {\n\t\t\t\t// here we're just adding the replying user to the followerIds array for the legacy codemark,\n\t\t\t\t// described above\n\t\t\t\tif (op.$set.followerIds.indexOf(this.user.id) === -1) {\n\t\t\t\t\top.$set.followerIds.push(this.user.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\top.$addToSet = { followerIds: [this.user.id] };\n\t\t\t}\n\t\t}\n\n\t\t// if a user is mentioned that is not following the thing, and they have the preference to\n\t\t// follow things they are mentioned in, or we're ignoring preferences,\n\t\t// then we'll presume to make them a follower\n\t\tconst mentionedUserIds = this.attributes.mentionedUserIds || [];\n\t\tlet newFollowerIds = ArrayUtilities.difference(mentionedUserIds, followerIds);\n\t\tif (newFollowerIds.length === 0) { return []; }\n\n\t\t// search for followers within the provided user array first\n\t\tlet newFollowers = [];\n\t\tif (this.users) {\n\t\t\tfor (let i = newFollowerIds.length-1; i >= 0; i--) {\n\t\t\t\tconst user = this.users.find(user => user.id === newFollowerIds[i]);\n\t\t\t\tif (user) {\n\t\t\t\t\tnewFollowers.push(user);\n\t\t\t\t\tnewFollowerIds.splice(i, 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// get any others from the database\n\t\tif (newFollowerIds.length > 0) {\n\t\t\tlet followersFromDb = await this.request.data.users.getByIds(\n\t\t\t\tnewFollowerIds,\n\t\t\t\t{\n\t\t\t\t\tfields: ['id', 'preferences'],\n\t\t\t\t\tnoCache: true,\n\t\t\t\t\tignoreCache: true\n\t\t\t\t}\n\t\t\t);\n\t\t\tnewFollowers = [...newFollowers, ...followersFromDb];\n\t\t}\n\n\t\tnewFollowers = newFollowers.filter(user => {\n\t\t\tconst preferences = user.get('preferences') || {};\n\t\t\tconst notificationPreference = preferences.notifications || 'involveMe';\n\t\t\treturn (\n\t\t\t\toptions.ignorePreferences || (\n\t\t\t\t\t!user.get('deactivated') && \n\t\t\t\t\t(\n\t\t\t\t\t\tnotificationPreference === 'all' ||\n\t\t\t\t\t\tnotificationPreference === 'involveMe'\n\t\t\t\t\t)\n\t\t\t\t)\n\t\t\t);\n\t\t});\n\t\tnewFollowerIds = newFollowers.map(follower => follower.id);\n\t\tif (newFollowerIds.length > 0) {\n\t\t\tif (op.$set.followerIds) {\n\t\t\t\top.$set.followerIds = ArrayUtilities.union(op.$set.followerIds, newFollowerIds);\n\t\t\t}\n\t\t\telse {\n\t\t\t\top.$addToSet = op.$addToSet || { followerIds: [] };\n\t\t\t\top.$addToSet.followerIds = ArrayUtilities.union(op.$addToSet.followerIds, newFollowerIds);\n\t\t\t}\n\t\t}\n\t}", "async function add(req, res, next) {\n try {\n req.body.user = req.currentUser\n req.body.users = req.currentUser\n const playlist = await Playlist.create(req.body)\n await playlist.save()\n const user = await User.findById(req.currentUser._id)\n user.playlists.push(playlist)\n const savedUser = await user.save()\n res.status(200).json(savedUser)\n } catch (e) {\n next(e)\n }\n}", "function appendUserToList(url, nickname) {\n\tvar $user = $('<li>').html('<a class= \"user_link\" href=\"'+url+'\">'+nickname+'</a>');\n\t//Add to the user list\n\t$(\"#user_list\").append($user);\n\treturn $user;\n}", "function addUser(u){\n users.push(new userModel.User(u.username, u.firstName, u.lastName, u.email, u.password));\n console.log('Added user ' + u.username);\n}", "function follow_user(id, follow) {\n fetch('/follow', {\n method: 'POST',\n body: JSON.stringify({\n \"id\": id,\n \"follow\": follow\n })\n })\n .then(response => response.json())\n .then(result => {\n load_profile(id);\n })\n}", "add(user) {\n return __awaiter(this, void 0, void 0, function* () {\n if (user == null) {\n throw new nullargumenterror_1.NullArgumentError('user');\n }\n this.users.push(user);\n });\n }", "function add_user_ui(u) {\n //a = `<div id=\"${name_to_id(u.first_name)}\" onClick=\"update_person(this)\" class=\"person\"><div class=\"person-name\">${u.first_name}</div><div class=\"person-date\">${u.last}</div></div>`\n a = `<div id=\"${name_to_id(u.first_name + u.last_name)}\" onClick=\"update_person(this)\" class=\"person\"><div class=\"person-name\">${u.first_name}</div><div class=person-lastname>${u.last_name}</div></div>`\n $(\"#contact_list\").append(a);\n}", "function postUser(e, book){ \n\n e.preventDefault()\n let show = document.getElementById('show-panel')\n let newObj = {id: 1, username: \"Peter\"}\n let ul = e.target.nextElementSibling\n let nuUl= document.createElement('ul')\n let new_id = parseInt(e.target.id) \n\n \n\nif (book.users.filter(users => users.id === newObj.id).length > 0){\n alert(\"You already liked this book!\"); \n \n }\n else{ \n let newUser = book.users.push(newObj)\n fetch(`http://localhost:3000/books/${new_id}`, {\n method: 'PATCH',\n headers:{\n 'Content-Type': \"application/json\",\n Accept: \"application/json\"\n },\n body: JSON.stringify({\n users: book.users\n })\n })\n \n .then(resp => resp.json())\n .then(data => { \n show.removeChild(ul)\n nuUl.id = data.id\n \n newUser = getUsers(data, data.users, nuUl)\n \n show.appendChild(newUser) \n })\n \n }\n }", "add(state, users) {\n users.forEach(user => {\n if (!user.id) return // should not happen\n state.users[user.id] = user\n })\n }", "addUser(user) {\r\n if (this.userUuids.indexOf(user.getUuid()) == -1) {\r\n this.userUuids.push(user.getUuid());\r\n this.update();\r\n }\r\n }", "function addToDatabase() {\n if (!hasError) {\n console.log(3, hasError);\n database = firebase.database();\n var setUserListRef = database.ref(`userList`);\n setUserListRef.push({\n \"userName\": userName,\n \"lastSpoken\": [\"null\"],\n \"favoritePlayer\": [\"null\"]\n })\n }\n }", "function _setUsers(pUser){\n var usersList = _getUsers();\n\n usersList.push(pUser);\n localStorage.setItem('lsUsersList', JSON.stringify(usersList));\n }", "function addToCollaboratorList (currentList, newUser) {\n if (currentList === '') {\n return newUser;\n } else {\n let tempList = [];\n\n tempList = currentList;\n tempList.push(newUser);\n return tempList;\n }\n}", "function pushToFriendsList(){\n if (i < dbRelationship.length) {\n // console.log(\"running length\");\n // we want to capture the user that isn't the one querying the list\n if (dbRelationship[i].userOneId._id == req.user._id) {\n // first we push the opposite id of the request user to friendsList\n // console.log(\"running push\");\n friendList.push(dbRelationship[i].userTwoId);\n // then increase i by one\n i++;\n // console.log(i);\n // then we call the function again\n pushToFriendsList();\n } else if (dbRelationship[i].userTwoId._id == req.user._id){\n // console.log(\"running else push\");\n // push opposite id of the request user to friendsList\n friendList.push(dbRelationship[i].userOneId);\n // increase i by one\n i++;\n // console.log(i);\n // call the function again\n pushToFriendsList();\n } else {\n return;\n }\n } else {\n return res.json(friendList);\n }\n }", "function addBlogList(object, user, picture, title, description, date, userId) {\n\tif (!object[user]) {\n\t\tobject[user] = [];\n\t}\n\tobject[user].unshift([picture, title, description, date, userId]);\n}", "addFriend(newFriend){\n var i;\n for (i = 0; i < this._friends.length; i++) {\n if (this._friends[i] === newFriend){\n console.log(newFriend + \" is already in list\");\n return;\n }\n }\n this._friends.push(newFriend);\n }", "function loadFollowers() {\n UserService.getFollowers(vm.user.username, vm.loaded)\n .then(res => {\n vm.arr.push(...res);\n vm.loaded = vm.arr.length;\n });\n }", "function addTodoListUser() {\n var listId = document.forms.todoForm.listId.value;\n var login = document.forms.shareListForm.login.value;\n dwr.engine.beginBatch();\n todo_lists.addTodoListUser(listId, login, replyAddTodoListUser);\n todo_lists.getTodoListUsers(listId, replyShareTodoListUsers);\n dwr.engine.endBatch();\n tracker('/ajax/addTodoListUser');\n}", "function follow(username, loggedInUsername, toFollow, usernameKey, toFollowKey){\n\t//make an ajax call to ChangeFollowServlet\n\tvar xhttp = new XMLHttpRequest();\n\tconsole.log(\"/\"+window.location.pathname.split(\"/\")[1]);\n\txhttp.open(\"GET\", \"/\"+window.location.pathname.split(\"/\")[1]+\"/ChangeFollowServlet?\"+usernameKey+\"=\"+\n\t\t\tusername+\"&\"+toFollowKey+\"=\"+toFollow, false);\n\txhttp.send();\n\t\n\t//if the loggedInUser added the username to their following list\n\tif (toFollow){\n\t\t//create a new h2 element\n\t var h2 = document.createElement('h2');\n\t //set the id to loggedin_follower (so we know the exact element that references the loggedin user's username)\n\t h2.id = \"loggedin_follower\";\n\t //create and a element, and set the href to navigate to the user_profile jsp\n\t var a = document.createElement('a');\n\t a.href = \"/\"+window.location.pathname.split(\"/\")[1]+\"/jsp/user_profile.jsp?\"+usernameKey+\"=\"+loggedInUsername;\n\t //create a text node with the loggedInUsername and append it as a child to the a element\n\t var text = document.createTextNode(loggedInUsername);\n\t a.appendChild(text);\n\t //append the a element as a child of the h2 element\n\t h2.appendChild(a);\n\t //append the h2 element as a child of the followers div\n\t document.getElementById('followers').appendChild(h2);\n\t //switch visiblity of unfollow and follow buttons\n\t document.getElementById(\"follow_button\").style.display = \"none\";\n\t document.getElementById(\"unfollow_button\").style.display = \"block\";\n\t\t \n\t}\n\t//if the loggedIsUser removed the username from their following list\n\telse{\n\t\t//remove the loggedin_follower element from the followers div\n\t document.getElementById('loggedin_follower').remove();\n\t //switch visibility of unfollow and follow buttons\n\t document.getElementById(\"unfollow_button\").style.display = \"none\";\n document.getElementById(\"follow_button\").style.display = \"block\";\t\t\n\t}\n\t\n\treturn false;\n}", "function createListFollowing(allDiv, content, responseAsJson, authToken, apiUrl){\n\tlet p = document.createElement(\"p\"); //name\n\tp.style.textAlign = \"center\";\n\tlet span = document.createElement(\"span\"); //username\n\tspan.style.color = \"var(--reddit-blue)\";\n\tspan.textContent = \" @\" + responseAsJson.username;\n\tspan.style.fontSize = \"small\";\n\tspan.className = \"listAll\"; //make each username linkable\n\tspan.onclick = function(){ let form = createUserPage(allDiv,\n responseAsJson.username, authToken, apiUrl);\n openEdit(allDiv, form)}; //when clicked opens their user page\n\tp.textContent = responseAsJson.name;\n\tp.appendChild(span);\n\tp.style.fontSize = \"small\";\n\tcontent.appendChild(p);\n\treturn content\n}", "function add_to_user_memes( meme_object )\n {\n // assign an id to the meme we add for the user\n var id = _this.meme_id;\n meme_object.id = id;\n\n // check if id already exists in the system\n for( var i = 0 , len = _this.user_memes.length ; i < len ; i++ )\n {\n var current = _this.user_memes[i];\n if( id == current.id ){\n // remove the item\n _this.user_memes.splice( i , 1 );\n break;\n }\n }\n\n // add the object to our array\n _this.user_memes.push( meme_object );\n\n // move the id by one\n _this.meme_id++;\n }", "function enhanceFollowersFunctionality() {\n var followerWrappers = document.querySelectorAll(\"#followers [data-userid]\");\n followerWrappers.forEach(function(followerEl) {\n var timestamp = followerEl.querySelector(\".timestamp\");\n timestamp.innerText = formatServerDateTime(timestamp.innerText);\n var followerName = followerEl.dataset.username;\n var blockButton = followerEl.querySelector(\".block-follower-button\");\n if(!blockButton) return; // Buttons are rendered on the backend only for the owner of the follower listing page.\n blockButton.addEventListener(\"click\", function() {\n toggleBlock(blockButton, followerName);\n });\n });\n}", "async addMembersToTalk(parent, args, ctx, info) {\n // check login\n if (!ctx.request.userId) {\n throw new Error('You must be logged in to do that!');\n }\n // check that the user is the member of the talk\n // TODO\n\n // add new members\n // transform array of members\n const members = args.members.map(member => ({ id: member }));\n return ctx.db.mutation.updateTalk(\n {\n data: {\n members: {\n connect: members,\n },\n },\n where: {\n id: args.id,\n },\n },\n info\n );\n }", "function addExistingMember(self) {\n show2ListsMembersContainer(self);\n if (!self.list1) {\n getAllTeamMembers(self);\n } \n }", "function onToggleFollowingUserSuccess(data) {\n\tvar favicon = $(\".addfav\", \".user_\" + data.id);\n\tif(data.follow) {\n\t\tfavicon.addClass(\"active\");\n\t} else {\n\t\tfavicon.removeClass(\"active\");\n\t}\n}", "async function getOneUserPopulateFollowing() {\n try {\n const populatedUser = await UserModel.findById(\"5f5f85f887dcf2441f096960\")\n .populate(\"following\")\n .exec();\n\n console.log(populatedUser);\n } catch (error) {\n console.log(error);\n }\n }", "function addNewUser(user){\n fetch(\"https://students-3d096.firebaseio.com/.json\", {\n method:\"POST\",\n headers: {\n \"Content-type\": \"application/json\"\n }, \n body: JSON.stringify(user)\n })\n .then(res => res.json())\n .then(data => { \n users.push({...user, id: data.name});\n showUsersInfo(users);\n })\n}", "function updateUserList(nicknames) {\n var $userListDiv = $('.user-list');\n var $userList;\n $userListDiv.empty();\n $userListDiv.append('<span class=\"user-count\">' + nicknames.length + ' users currently connected</span>');\n $userList = $('<ul></ul>').appendTo($userListDiv);\n for (var i = 0; i < nicknames.length; i++) {\n $userList.append('<li>' + nicknames[i] + '</li>');\n }\n}", "function addUser () {\r\n document.querySelector(\".add-user form\").addEventListener(\"submit\", (e) => {\r\n e.preventDefault();\r\n\r\n var value = e.target.querySelector(\"#user-name\").value;\r\n value = value.trim();\r\n value = value.length == 0 ? null : value;\r\n\r\n if(value === null) return;\r\n\r\n var newElem = document.createElement(\"li\");\r\n newElem.setAttribute(\"draggable\", true);\r\n newElem.innerHTML = value;\r\n\r\n e.target.querySelector(\"#user-name\").value = \"\";\r\n document.querySelector(\".user-list ul\").appendChild(newElem);\r\n\r\n // update events for new elements\r\n sortableList1.update(newElem);\r\n });\r\n}", "updateUserList(newUser) {\n if(newUser.name === undefined || newUser.name.trim().length == 0) {\n this.toggleErrorMessage('Please enter a valid user name');\n } else {\n this.toggleErrorMessage();\n UserDataService.addUser(newUser).then((users)=> {\n // Pass users and last user\n this.props.updateUsers(users, users[users.length -1]);\n }, this.handleServiceError);\n }\n }", "constructor(userData) {\n this.id = userData.id;\n this.name = name;\n this.address = address;\n this.email = email;\n this.strideLength = strideLength;\n this.dailyStepGoal = dailyStepGoal;\n this.friends = []\n // will connect to other users\n }", "function createUserInformation(){\n\tconsole.log(\"function: createUserInformation\");\n\t$().SPServices({\n\t\toperation: \"UpdateListItems\",\n\t\twebURL: siteUrl,\n\t\tasync: false,\n\t\tbatchCmd: \"New\",\n\t\tlistName:\"ccUsers\",\n\t\tvaluepairs:[\n\t\t\t\t\t\t[\"Title\", personInformation().pseudoName], \n\t\t\t\t\t\t[\"PERSON_EMAIL\", personInformation().personEmail], \n\t\t\t\t\t\t[\"P_LAST_NAME\", personInformation().personLastName],\t\n\t\t\t\t\t\t[\"P_FIRST_NAME\", personInformation().personFirstName], \n\t\t\t\t\t\t[\"PERSON_ROLE\", personInformation().personRole], \n\t\t\t\t\t\t[\"PERSON_RANK\", personInformation().personRank], \n\t\t\t\t\t\t[\"PERSON_DIRECTORATE\", personInformation().personDirectorate], \n\t\t\t\t\t\t[\"PERSON_ACTIVE\", personInformation().personActive],\n\t\t\t\t\t\t[\"PERSON_ATTRIBUTES\", personAttributes()],\n\t\t\t\t\t\t[\"PERSON_TRAINING\", personTraining()]\n\t\t\t\t\t],\n\t\tcompletefunc: function (xData, Status) {\n\t\t\t$(xData.responseXML).SPFilterNode(\"z:row\").each(function(){\n\t\t\t\tuserId = $(this).attr(\"ows_ID\");\n\t\t\t})\n\t\t}\n\t});\n\t// Redirect\n\tsetTimeout(function(){\n\t\tsetUserInformationRedirect(userId);\n\t}, 2000);\t\n}", "function addUserInContactList( data ){\n\n\n var _div_date = ( data.date === null || data.date === undefined ) ? '' :\n '<div class=\"col-12 col-sm-auto d-flex flex-column align-items-end\"> \\\n <div class=\"last-message-time\">'+data.date+'</div> \\\n </div>';\n\n var _last_message = ( data.lastMessage === null || data.lastMessage === undefined ) ? '' : '<p class=\"last-message text-truncate text-muted\">'+ data.lastMessage +'</p>';\n\n var _contact =\n '<div class=\"contact ripple flex-wrap flex-sm-nowrap row p-4 no-gutters align-items-center\" id=\"'+data.user.id+'\" > \\\n \\\n <div class=\"col-auto avatar-wrapper\"> \\\n <img src=\"../assets/images/avatars/'+data.user.profilePicture+'\" class=\"avatar\" alt=\"'+data.user.firstName+'\" /> \\\n <i class=\"status '+ switchActive( data.user.action ) +' s-4\" name=\"status-contact\" ></i> \\\n </div> \\\n \\\n <div class=\"col px-4\"> \\\n <span class=\"name h6\">'+data.user.firstName+'</span> \\\n '+_last_message+' \\\n </div> \\\n \\\n '+_div_date+' \\\n \\\n </div> \\\n <div class=\"divider\"></div>';\n\n $('.chat-list').append( _contact ); // user - add in contact\n\n }", "async function loadUsersFollowers() {\n const currentUsers = await getUsers(user);\n const currentFollows = await getFollows(user);\n\n // Sets users and follows states\n setUsers(currentUsers);\n setFollows(currentFollows);\n setIsLoading(false);\n }", "createFollowersList(data) {\n let followerListHTML = data.data.map((user) => {\n const {\n html_url: htmlUrl,\n avatar_url: imageUrl,\n login: username\n } = user;\n\n // Render HTML for list of followers\n return `\n <li>\n <div class=\"avatar-image\">\n <a href=\"${htmlUrl}\" target=\"_blank\">\n <img src=\"${imageUrl}\">\n </a>\n </div>\n <span>\n <a href=\"${htmlUrl}\" target=\"_blank\">${username}</a>\n </span>\n <button id=\"${username}\" class=\"search-btn\">Search user</button>\n </li>\n `\n }).join('');\n\n // Append the list of followers into the followers container\n this.$followersList.append(followerListHTML);\n\n // Register 'search-btn' element\n this.$userSearchButton = $('.search-btn');\n\n // Activate User Card Search Function\n this.activateSearchUserButton();\n }", "function refreshListOfUsersWhoHaveAddedYou(l) { User.downloadListOfUsersWhoHaveAddedYou(l); }", "function removeFollowing(req, res) {\n var username = req.user;\n var toBeRemovedFollowing = req.params.user ? req.params.user.split(',')[0] : null;\n if (!toBeRemovedFollowing) {\n res.send(400)\n }\n Profile.find({username: username}, function (err, result) {\n if (err) return res.json({error: \"Error finding \" + username + Profile.toString()});\n var user = result[0];\n var index = user.following.findIndex(function (following) {\n return following === toBeRemovedFollowing\n });\n user.following.splice(index, 1);\n user.save(function (err, user) {\n if (err) return res.json({error: \"Error saving \" + user.username + Profile.toString()});\n res.send({\"username\": user.username, \"following\": user.following})\n })\n });\n}", "function tofollow(){\n const follow_2 = document.getElementById('follow_button_2');\n follow_2.onclick = function() {\n const username = document.getElementById('funame').value;\n if (! username){\n window.alert(\"The username must not left empty!\");\n return false;\n }\n const path = 'user/?username='+ username;\n const headers = {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'Authorization' : 'Token ' + checkStore('token'),\n };\n const method = 'GET';\n api.makeAPIRequest(path, {\n method, headers\n }).then(function (res) {\n buttonInit();\n document.getElementById('follow_option').style.display = 'block';\n document.getElementById('follow_option').innerHTML = '';\n\n if ('username' in res){\n const info = createElement('b', username + ' exists !\\xa0\\xa0\\xa0');\n const follow = createElement('li', 'Follow', { class:'nav-item', id: \"follow_button_3\", style: \"cursor:pointer\" });\n const unfollow = createElement('li', 'Unfollow', { class:'nav-item', id: \"follow_button_4\", style: \"cursor:pointer\" });\n document.getElementById('follow_option').appendChild(info); \n document.getElementById('follow_option').appendChild(follow);\n document.getElementById('follow_option').appendChild(unfollow);\n followOpt(username); \n }\n else{\n const info = createElement('b', username + ' does not exist !\\xa0\\xa0\\xa0');\n document.getElementById('follow_option').appendChild(info);\n }\n });\n }\n}", "function appendUserListElement(firstname, lastname) {\n searchResultsList.append('<li><p>'+firstname+\" \"+lastname+'</p></li>');\n }", "function setUserList(id, list) {\n \n userList.userId = getCurrentUser().userId;\n userList.listId = list[0];\n userList.listName = list[1];\n userList.items = list[2];\n }", "function refreshListOfAddedUsers(l) { User.downloadListOfAddedUsers(l); }", "addUsers(state, users) {\n for (let u of users) {\n Vue.set(state.allUsers, u.id,\n new User(u.id, u.first_name, u.last_name, u.picture_url));\n }\n }", "function addToSubscribed(username) {\n var subscribed = getSubscribedList();\n subscribed[username] = true;\n setSubscribedList(subscribed);\n }", "function addData(newUser) {\n data.push(newUser);\n updateDOM();\n}", "function addToRegisteredUsers( obj ) {\n\t// alter this function if mongoDB is used later\n\tconsole.log(\"pushing the new user to the storage\");\n\tregisteredUsers.push(obj);\n\t//obj = {};\n}", "function drawUserlistItem(imagePath, color, username) {\n /*\n * If they aren't a normal user, draw their rank icon.\n */\n if (imagePath !== 'void') {\n var realPath = 'http://www.theedmbasement.com/basebot/userlist/' + imagePath;\n $('#plugbot-userlist').append('<img src=\"' + realPath + '\" align=\"left\" style=\"margin-left:6px;margin-top:2px\" />');\n }\n\n /*\n * Write the HTML code to the userlist.\n */\n $('#plugbot-userlist').append(\n '<p style=\"cursor:pointer;' + (imagePath === 'void' ? '' : 'text-indent:6px !important;') + 'color:' + color + ';' + ((API.getDJs()[0].username == username) ? 'font-size:15px;font-weight:bold;' : '') + '\" onclick=\"$(\\'#chat-input-field\\').val($(\\'#chat-input-field\\').val() + \\'@' + username + ' \\').focus();\">' + username + '</p>');\n}", "function show_list(user){\n let usrList = document.getElementsByClassName(\"user-list\")[0];\n let usrUl = document.createElement(\"ul\");\n for(let i = 0;i < user.items.length ; i++){\n let usrLi = document.createElement(\"li\");\n let usrRepo = document.createTextNode(user.items[i].name+\" _\");\n usrLi.appendChild(usrRepo);\n usrUl.appendChild(usrLi);\n }\n usrList.appendChild(usrUl);\n}", "function addUser(user){\n signUpContainer.push(user);\n localStorage.setItem(\"users\" , JSON.stringify(signUpContainer)) ;\n messageSuccess();\n clearInputs();\n}", "function addUserToTask(input, li) {\n jQuery(input).val(\"\");\n\n var userId = jQuery(li).find(\".complete_value\").text();\n var taskId = jQuery(\"#task_id\").val();\n\n var url = \"/tasks/add_notification\";\n var params = { user_id : userId, id : taskId }\n jQuery.get(url, params, function(data) {\n\tjQuery(\"#task_notify\").append(data);\n\thighlightActiveNotifications();\n });\n}", "function addOrRemoveEndUser(endUser){\n\t\t\tif(isEndUserAdded(endUser)){\n\t\t\t\tvar index = $scope.addedEndUsers.map(function(e){return e.PartnerId;}).indexOf(endUser.PartnerId);\n\t\t\t\t$scope.addedEndUsers.splice(index,1);\n\t\t\t}else{\n\t\t\t\t$scope.addedEndUsers.pop();\n\t\t\t\t$scope.addedEndUsers.push(endUser);\n\t\t\t}\n\t\t}" ]
[ "0.71166307", "0.70443064", "0.694382", "0.6905326", "0.6781021", "0.6712102", "0.6682262", "0.6583409", "0.65381575", "0.647421", "0.64643097", "0.64557135", "0.64342296", "0.6434143", "0.6429521", "0.640087", "0.6375317", "0.6360598", "0.6350468", "0.63387096", "0.63372934", "0.63285553", "0.629413", "0.6292799", "0.6220234", "0.62045634", "0.61973834", "0.61553645", "0.6145522", "0.6139214", "0.6119093", "0.6094544", "0.60867566", "0.6080102", "0.60789263", "0.606841", "0.6065712", "0.6057631", "0.6051308", "0.60488105", "0.60435855", "0.6039696", "0.6028718", "0.6027668", "0.6026733", "0.6019482", "0.60152334", "0.60122365", "0.60084105", "0.59989274", "0.59960514", "0.5961465", "0.5958767", "0.5958544", "0.5945726", "0.59404254", "0.59399027", "0.5931736", "0.59219164", "0.5913999", "0.59027934", "0.5890546", "0.58889616", "0.58841026", "0.5881639", "0.5871032", "0.5870754", "0.58676803", "0.58627176", "0.5861823", "0.585765", "0.58522236", "0.5842452", "0.5842214", "0.58394957", "0.5826682", "0.58244634", "0.5815674", "0.58019316", "0.5801168", "0.57984215", "0.5797329", "0.5797213", "0.57966", "0.5791028", "0.57858825", "0.5771674", "0.5771645", "0.5769916", "0.5743756", "0.5737242", "0.57369995", "0.5728411", "0.5720907", "0.57207584", "0.5720133", "0.5718728", "0.57174635", "0.5712079", "0.571043" ]
0.6969874
2
Remove user to following List
unfollowUser(state, userId) { state.loading.following = true; state.loading.follow = true; let user = state.userList.find((user) => user._idUser === userId); if (user) { state.nonFollowingUsers.push(user); state.followingUsers = state.followingUsers.filter( (user) => user._idUser !== userId ); } state.loading.following = false; state.loading.follow = false; }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "function removeFollowing(req, res) {\n var username = req.user;\n var toBeRemovedFollowing = req.params.user ? req.params.user.split(',')[0] : null;\n if (!toBeRemovedFollowing) {\n res.send(400)\n }\n Profile.find({username: username}, function (err, result) {\n if (err) return res.json({error: \"Error finding \" + username + Profile.toString()});\n var user = result[0];\n var index = user.following.findIndex(function (following) {\n return following === toBeRemovedFollowing\n });\n user.following.splice(index, 1);\n user.save(function (err, user) {\n if (err) return res.json({error: \"Error saving \" + user.username + Profile.toString()});\n res.send({\"username\": user.username, \"following\": user.following})\n })\n });\n}", "function removeFollower(e) {\n var followerInput = followInput.value;\n var req = new XMLHttpRequest();\n req.open('POST', '/users/' + currentUser.username + '/unfollow', true);\n req.addEventListener('load', function() {\n while (followingList.firstChild) {\n followingList.removeChild(followingList.firstChild);\n }\n\n for(var i = 0; i < currentUser.following.length; i++) {\n var following = createFollowingList(currentUser.following[i].username);\n followingList.appendChild(following);\n }\n followInput.value = null;\n });\n req.send(followerInput);\n}", "function unfollow() {\n UserService.unfollow(vm.currentUser, vm.user)\n .then(res => {\n vm.user.followers.splice(vm.user.followers.findIndex(x => x._id == vm.currentUser._id), 1);\n vm.isFollowed = false;\n });\n }", "function removeFollower(){\n\t\t//one follower name comes with an unfollow button\n\t\telement.all(by.id(\"folowerName\")).each(function(element, index){\n\t\t\telement.getText().then(function(text){\n\t\t\t\tif(text == \"Follower\"){\n\t\t\t\t\telement.all(by.id(\"unfollowBtn\")).get(index).click()\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}", "function removeFromTheirFollowers(index, pID , pName){\r\n\t\tvar params = {\r\n\t\t\t\t TableName : 'user',\r\n\t\t\t\t Key: {\r\n\t\t\t\t\t \"userId\" : pID,\r\n\t\t\t\t\t \"userName\" : pName\r\n\t\t\t\t\t},\r\n\t\t\t\t\tUpdateExpression: \"remove followers[\" + index + \"]\"\r\n\t\t\t };\r\n\t\t\t\tconsole.log(\"Attempting a conditional delete...\");\r\n\t\t\t\tdocClient.update(params, function(err, data) {\r\n\t\t\t\t if (err) {\r\n\t\t\t\t console.error(\"Their Followers : Unable to delete item. Error JSON:\", JSON.stringify(err, null, 2));\r\n\t\t\t\t } else {\r\n\t\t\t\t console.log(\"DeleteItem succeeded from their Followers:\", JSON.stringify(data, null, 2));\r\n\t\t\t\t }\r\n\t\t\t\t});\r\n\t\r\n}", "function unfollow(){\n let users = document.querySelectorAll('div.r-1awozwy.r-18u37iz.r-1wtj0ep');\n for (let i = 0; i < users.length; i++){\n\t\tlet user = users[i]\n \tif( !user.children[0].children[0].children[0].children[1].children[1]) {\n\t\t\tif(user.children[1].children[0].children[0].children[0].children[0].innerHTML == 'Following'){\n\t\t\t\tuser.children[1].children[0].click();\n\t\t\t\tdocument.querySelectorAll('[data-testid=confirmationSheetConfirm]')[0].click();\n\t\t\t\tconsole.log('You just unfollow this user')\n }\n }\n }\n}", "function removeFromFollowing(index,userId,userName){\r\n//\t//DBIndex = getIndex(email,\"following\",googleUserId,googleUserName);\r\n//\t//pass email to check/Remove , Followers / Following , Account NAme & Email ID\r\n\t\t\tvar params = {\r\n\t\t\t TableName : 'user',\r\n\t\t\t Key: {\r\n\t\t\t\t //TODO : To be profile.getuserid...\r\n\t\t\t\t \"userId\" : googleUserId,\r\n\t\t\t\t \"userName\" : googleUserName\r\n\t\t\t\t},\r\n\t\t\t\tUpdateExpression: \"remove following[\" + index + \"]\"\r\n\t\t };\r\n\t\t\tconsole.log(\"Attempting a conditional delete...\");\r\n\t\t\tdocClient.update(params, function(err, data) {\r\n\t\t\t if (err) {\r\n\t\t\t console.error(\"Following : Unable to delete item. Error JSON:\", JSON.stringify(err, null, 2));\r\n\t\t\t } else {\r\n\t\t\t console.log(\" Following : DeleteItem succeeded:\", JSON.stringify(data, null, 2));\r\n\t\t\t getIndex(googleUserId,\"followers\",userId,userName,googleUserName);\r\n\t\t\t }\r\n\t\t\t});\r\n}", "function unFollowUser() {\n if (LoginService.isLoggedIn()) {\n UserProfileService\n .unFollowUser(vm.userInfo.id)\n .then(function () {\n vm.isFollowing = false;\n\n //reload details for the current user who has been followed/unfollowed\n getUserInfoForOtherUsers(vm.userInfo.userName);\n });\n }\n }", "function unfollow(req, res) {\n Profile.findById(req.user.profile)\n .then(followerProfile => {\n followerProfile.following.remove({_id:req.params.id})\n followerProfile.save()\n .then(()=> {\n Profile.findById(req.params.id)\n .then(followingProfile=>{\n followingProfile.followers.remove({_id: req.user.profile._id})\n followingProfile.save()\n })\n res.redirect(`/profiles/${req.params.id}`)\n })\n })\n .catch((err) => {\n console.log(err)\n res.redirect('/')\n })\n}", "function action_removeSelectedUserFromCollaboratorList() {\n var parentUl = $('#panel-collaborators').children('ul');\n var users = parentUl.children('li');\n var user = users.get(0);\n\n // Remove selected user from list..\n var collaborator = collaboratorList.find(function(oneInfo) {\n return oneInfo.email === selectedCollaboratorEmail;\n });\n collaboratorList.splice(collaboratorList.indexOf(collaborator), 1);\n\n users.splice(selectedCollaboratorIndex, 1);\n parentUl.html('');\n parentUl.append(users);\n}", "removeUser(user) {\n this.active_list = this.active_list.filter((a_user) => a_user.email !== user.email);\n this.setValue(this.active_list);\n }", "function RemoveMe (id : int ){ // This function is the \"MASTER BREAKER\" breaking begins here\n\tif(!followersCanBreak){ return;} // Only Run if followers can Break Off\n\t\n\tif(editingList){return;} // We are already removing something\n\t//we use a for loop to remove every follower starting from the follower that called this\n\teditingList = true; // Set this to return true so we cant add while editingList\n\t\n\tif(followersBreakWithParent){\n\t\tfor(var i : int = followers.Count -1; i > 0; i--){\n\t\t\tvar follower : ViralFollower = followers[i].GetComponent(ViralFollower);\n\t\t\tfollower.RemoveMe();\n\t\t\tfollowers.RemoveAt(i);\n\t\t\tif(follower.bondId == id){\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}else{\n\t\tfor(var j : int = followers.Count -1; j > 0; j--){\n\t\t\tfollower = followers[j].GetComponent(ViralFollower);\n\t\t\tif(follower.bondId == id){\n\t\t\t\tfollower.RemoveMe();\n\t\t\t\tfollowers.RemoveAt(j);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\t\n\t}\n\teditingList = false;\n}", "function removeUserFromElement(userID,itemNo) {\n\t\tvar idListLength, i;\n\t\tidListLength = gapi.hangout.data.getValue(\"listTxt\" + itemNo + \"listID\") || \"0\";\t\t\t// get length of current list ID list\n\t\tfor (i = 1; i <= idListLength; i++){\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ---\n\t\t\tif (userID == gapi.hangout.data.getValue(\"listTxt\" + itemNo + \"listID\" + i)){\n\t\t\t\tremoveItemFromList(\"listTxt\" + itemNo + \"listID\",i);\n\t\t\t};\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ---Check for id exsisting already if so quit\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// ---\n\n\t}", "function removeUser(user_name) {\r\n var user_list = document.getElementById('user_list');\r\n var el_name = document.getElementById(user_name);\r\n\r\n user_list.removeChild(el_name);\r\n}", "function remove (u) {\n return users.remove(u)\n}", "function unfollowClicked(memberID) {\n // call the deleteFollow function to delete the json object from my api\n // whose id matches the memberID parameter\n deleteFollow(memberID).then(() => {\n // use the filter function to return an array whose id does not\n // match the id of the member that was unfollowed\n const filteredFollowed = followed.filter((follow) => {\n return follow.id !== memberID;\n });\n // update the list of people followed\n setFollowed(filteredFollowed);\n });\n }", "function removeUserFromList(panelName, userId) {\n //\n $('[data-panel-name=\"'+panelName+'\"] [data-panel-userid=\"'+userId+'\"]').parent().remove();\n\n //\n removeUserFromStore(panelName, userId);\n}", "updateTrackList(following) {\n // Add any new follows to the trackedUsers list\n for (let i = 0; i < following.length; i++) {\n let user = following[i];\n\n if (!(user in this.botStatus.trackedUsers)) {\n this.botStatus.trackedUsers[user] = 0;\n }\n }\n\n // Remove any trackedUsers that the bot is no longer following\n for (let userID in this.botStatus.trackedUsers) {\n if (!this.utils.isInArray(following, userID)) {\n delete this.botStatus.trackedUsers[userID];\n }\n }\n }", "function removeUser(userList, username) {\r\n let newList = Object.assign({}, userList)\r\n delete newList[username]\r\n return newList\r\n}", "function removeFollow(req, res, next) { \n db\n .task(t => { \n return t.none(\"UPDATE users SET user_followers = array_remove(user_followers, ${username}) WHERE id=${user_id}\", \n { username: req.body.username, user_id: req.body.user_id })\n .then(user => { \n return t.none(\"UPDATE users SET user_following = array_remove(user_following, ${user_username}) WHERE username=${username}\", \n { user_username: req.body.user_username, username: req.body.username, user_id: req.body.user_id })\n })\n })\n .then(function(data) {\n res.status(200).json({\n status: \"success\",\n message: \"Removed one follower\"\n });\n })\n .catch(function(err) {\n return next(err);\n });\n}", "removeUser(user) {\r\n\t\tvar toRemove = -1;\r\n\t\tfor (let i = 0; i < this.players.length; i++) {\r\n\t\t\tif (this.players[i].username == user.username) {\r\n\t\t\t\ttoRemove = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (toRemove >= 0) {\r\n\t\t\tthis.players.splice(toRemove, 1);\r\n\t\t}\r\n\t\tvar removeElements = -1;\r\n\t\tfor (let j = 0; j < this.userPoints.length; j++) {\r\n\t\t\tif (user.username === this.userPoints[j].user) {\r\n\t\t\t\tremoveElements = j;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (removeElements > -1) {\r\n\t\t\tthis.userPoints.splice(removeElements, 1);\r\n\t\t}\r\n\t}", "function unfollowUser() {\n if($rootScope.currentUser == null){\n vm.returnData = \"Log in to continue\";\n }else{\n NoteService\n .unfollowUser(vm.note.user.uid, $rootScope.currentUser._id)\n .then(function (response) {\n vm.userFollowed = 0;\n console.log(response);\n });}\n }", "function removeUser(e) {\n if(e.target.classList.contains('tab_span')) {\n\n let response = confirm(\"Mean to delete member from list?\");\n\n if(response) {\n let data = JSON.parse(localStorage.getItem(\"users\"));\n\n let tr = e.target.parentNode.parentNode.id;\n\n data.forEach((obj, index) => {\n if(obj.userID === (+tr)) {\n data.splice(index, 1);\n }\n })\n\n if(data.length === 0) {\n localStorage.removeItem(\"users\");\n \n form_block.style.display = \"none\";\n\n return ( userID = 1, usersArr = [] );\n } else {\n usersArr = [...data];\n\n localStorage.setItem(\"users\", JSON.stringify(data));\n\n return updateTable();\n }\n } \n }\n}", "removeUser(user) {\n // User in Array suchen und \"rausschneiden\"\n for (var i=this.users.length; i >= 0; i--) {\n if (this.users[i] === user) {\n this.users.splice(i, 1);\n }\n }\n // geänderte Raumdetails wieder an alle senden\n var room = this;\n room.sendDetails();\n}", "function removeUserSite() {\n\t$(this).parent().remove();\n}", "function removeFriend() {\n let friendName = getFriendNameFromButton(this);\n console.log(`Removing friend: ${friendName}`);\n this.parentElement.removeChild(this);\n\n browser.storage.local.get(\n [\n \"friends\"\n ],\n function(response) {\n let friendsArray = response.friends;\n let newFriendsArray = [];\n\n for(let i = 0; i < friendsArray.length; i++) {\n if (friendsArray[i] !== friendName) {\n newFriendsArray.push(friendsArray[i])\n }\n }\n\n browser.storage.local.set(\n {\n \"friends\": newFriendsArray\n }\n )\n }\n );\n }", "function deleteFollow(req, res) {\n const userId = req.user.sub;\n const followId = req.params.id;\n Follow.findOneAndRemove({\n 'user': userId,\n 'followed': followId\n }, (err, followBD) => {\n\n if (err) {\n return res.status(500).json({\n message: 'hubo un error al guardar el usuario'\n });\n }\n if (!followBD) {\n return res.status(404).json({\n message: 'el usuario no fue encontrado'\n });\n }\n return res.status(200).json({\n message: 'el follow fue eliminado',\n followBD\n });\n\n });\n}", "function deleteInactiveUsers (users) {\n if (users.length > 0) {\n const user = users.pop()\n\n // This should trigger the userStatusLink removal sequence\n firebase.ref('/status/' + user).remove()\n }\n\n return null\n}", "deletUser(user){\n users=users.filter(u=>{\n return u.name !=user.name\n })\n }", "function unfollow(){\n\tif(!confirm(\"Are you sure you want to unfollow all selected athletes?\"))\n\t\treturn;\n\n\t// create an array of keys\n\tkeys = [];\n\t//loop through each line\n\t$(\".lineItem\").each(function(){\n\n\t\t// if it is checked, remove it from the list and the storage\n\t\tif($(this).find(\"input\").prop(\"checked\")){\n\t\t\tvar id = $(this).attr(\"value\");\n\t\t\t$(this).remove();\n\t\t\tkeys.push(id);\n\t\t\t//update the count\n\t\t\tfollowCount--;\n\t\t}\n\t});\n\n\t//remove from storage\n\tchrome.storage.sync.remove(keys);\n\t//update the page\n\t$(\"#follow-count\").text(\"(\"+followCount+\")\");\n\tchrome.tabs.reload();\n}", "function removeUser(req, res,list) {\n \n let lista=list\n let userId=req.user.sub // cogo el id del usuario a añadir \n // let list=req.body.list // cogo la lista donde voy a añadirlo\n console.log(list)\n /* console.log(userId)\n \n console.log(list)\n console.log(list[0].name)\n console.log(product)\n console.log(product[0]._id)\n console.log(req.user.sub)\n */\n\n // compruebo que existe el id de usuario y que se ha encontrado la lista\n if (req.user.sub && lista) { \n // si encuentro la lista cogo el nombre de la lista\n let listId=lista._id\n\n // console.log(nombrelista)\n // console.log(req.user.sub)\n\n // busco la lista y actualizo añadiendo un producto funciona pero debe buscarlo con el $in\n List.findOneAndUpdate({ _id:listId}, \n {$pull: \n {associatedUsers:\n { $in: [ userId ] }}},\n \n // propiedades \n \n {new:true},\n \n \n ).exec( function(error) {\n if (error) {\n return res.json({\n success: false,\n message: 'No se pudo eliminar',\n err: {error}\n \n });\n } else {\n return res.json({\n success: true,\n message: 'Se elimino el usuario'\n });\n }\n })\n } else {\n return res.json({\n success: false,\n message: 'No se pudo agregar el usuario, por favor verifique que el _id sea correcto'\n });\n }\n}", "function removeFollowUp()\n{\n\tvar context = this;\n\tvar preferencesAux = eval('('+ preferences.get() + ')');\n\tvar list = preferencesAux.followUp;\n\tvar listAux = []\n\t\n\tfor(var i=0; i < list.length; i++)\n\t{\n\t\tif(list[i] != context.symbol)\n\t\t\tlistAux[listAux.length] = list[i];\t\t\n\t}\n\t\n\tvar img = context.image;\n\timg.src = urlimage + \"add.png\";\n\timg.removeEventListener(\"click\", EzWebExt.bind(removeFollowUp, context), false);\n\timg.addEventListener(\"click\", EzWebExt.bind(addFollowUp, context), false);\n\timg.setAttribute(\"title\", BolsaGadget.getTranslatedLabel(\"addToFollowUp\"));\n\t\t\n\tpreferencesAux.followUp = listAux;\n\tpreferences.set(to_json(preferencesAux));\n\tpanelSettings = new StyledElements.StyledNotebook({\n 'id': 'panelSettings'\n });\n \n\tif(preferencesAux.followUp.length > 0){\n\t\tvar currentTab = panelMain.getTabByIndex(0);\n\t\tcurrentTab[\"__context\"] = {};\n\t\tcurrentTab.__context[\"type\"] = 1;\n\t\tcurrentTab.__context[\"symbols\"] = preferencesAux.followUp;\n\t\tcurrentTab.__context[\"tags\"] = preferencesAux.list;\n\t\trefresh(currentTab.__context.type, currentTab.__context.symbols, currentTab.__context.tags, 0);\n\t}\t\n\t// OCULTAMOS LA PESTAÑA DE SEGUIMIENTO\n\t//displayAlternativeInfo();\n}", "function removeFromSubscribed(username) {\n var subscribed = getSubscribedList();\n delete subscribed[username];\n setSubscribedList(subscribed);\n }", "function removeUser(id) {\n const newUserList = users.filter((user) => user._id !== id)\n setUsers(newUserList)\n }", "removeUser(username) {\n for (let i = this.chatUsersDB.length - 1; i >= 0; --i) {\n if (chatUsersDB[i].username === username) {\n chatUsersDB.splice(i, 1);\n }\n }\n }", "function removeFromSubscribed(username) {\n\tvar subscribed = getSubscribedList();\n\tdelete subscribed[username];\n\tsetSubscribedList(subscribed);\n}", "function removeUser (existingData, user ) {\n let tempList = existingData[0].active\n let position = tempList.indexOf(user)\n if (position !== -1) {\n tempList.splice(position,1)\n return tempList\n }\n}", "function elimina_account(){\r\n var users = JSON.parse(localStorage.getItem(\"users\") || \"[]\");\r\n var user=JSON.parse(sessionStorage.user);\r\n\r\n for(var i=0;i<users.length;i++){\r\n if(users[i].username == user.username){\r\n users.splice(i, 1);\r\n localStorage.setItem(\"users\", JSON.stringify(users));\r\n elimina_all_prenotazioni();\r\n }\r\n }\r\n}", "function removeFromLocalList(remoteList) {\n if ( isArrayEmpty(localList) ) {\n // the local list is empty. Do nothing\n return;\n }\n for (var nickname in localList) {\n if ( remoteList[nickname] == null ) {\n // an user in local list doesn't exist in remote list\n // get the node with this nick name\n var nodes = $(\"userList\").childNodes;\n for (var i = 0; i < nodes.length; i++) {\n var node = nodes[i].lastChild; // should be the text node\n if (node.nodeValue == nickname) {\n // remove this node\n nodes[i].shrink({\n afterFinish: removeDt\n });\n delete localList[nickname];\n break;\n }\n }\n }\n }\n}", "prune (callback) {\n var self = this;\n\n /*\n * Get a list of all my followers\n */\n \n this.twit.get('followers/ids', function (err, reply) {\n if(err) return callback(err);\n \n var followers = reply.ids;\n \n /*\n * Get a list of all the people I follow.\n */\n\n self.twit.get('friends/ids', function(err, reply) {\n if(err) return callback(err);\n \n var friends = reply.ids\n , pruned = false;\n \n\n /*\n * Find one person who doesn't follow me back and unfollow them.\n */\n\n while(!pruned) {\n var target = randIndex(friends);\n \n if(!~followers.indexOf(target)) {\n pruned = true;\n self.twit.post('friendships/destroy', { id: target }, callback); \n }\n }\n });\n });\n }", "deleteUser(username){\n console.log(\"deleteUser called\");\n \n for (var i = 0; i < this.users.length; i++){\n if (this.users[1] === username){\n let tmp = this.users[i];\n this.users[i] = this.users[0];\n this.users[0] = tmp;\n this.users.shift();\n return;\n }\n }\n }", "function removeOnlineUsers(nickname) {\n $('#' + nickname + '').remove();\n }", "removeUser(id){\n var user = this.getUser(id);\n if(user){\n this.users = this.users.filter((user)=> user.id!==id); /* USER LIST WILL BE UPDATED */\n }\n\n return user;\n }", "async function unfollowUser(current_id, user_id){\r\n console.log(current_id + \" Will Now Unfollow: \" + user_id)\r\n\r\n // Call API to make change\r\n fetch('/unfollow/' + current_id + '/' + user_id)\r\n\t.then(res => res.json())\r\n\t.then(data => {\r\n\t\t// Print data\r\n\t\tconsole.log(data);\r\n \r\n // after following, clear the current follow button and add unfollow button\r\n document.getElementById('follow_option').innerHTML = \"\";\r\n\t\tloadFollowStatus(current_id, user_id, \"no\") // will now display follow button\r\n\t\tdecrementFollowerCount(current_id, user_id); // decrements the follower count\r\n });\r\n}", "function removeTrailFromUser(trail){\n\n // Find the trail to remove.\n var uniqueId = trail.unique_id;\n var currentUser = vm.currentUser;\n for(i = 0; i < currentUser.trails.length; i++){\n if(currentUser.trails[i].unique_id == uniqueId){\n var removeIndex = i;\n }\n }\n\n // Splice out the trail that needs to be removed from the user.\n var removedTrail = currentUser.trails.splice(removeIndex, 1)[0];\n\n // Update the user in our database.\n ProjectUserClient\n .updateUser(currentUser)\n .then(function(err, retVal){\n });\n\n // Find the user that needs to be removed from the trail.\n var userId = currentUser._id;\n for(i = 0; i < removedTrail.users.length; i++){\n if(removedTrail.users[i] == userId){\n var removeIndex = i;\n }\n }\n removedTrail.users.splice(removeIndex, 1);\n\n // If our updated trail has no more users, delete it from our Mongo database.\n if(removedTrail.users.length == 0){\n TrailClient\n .deleteTrail(removedTrail)\n .then(function(err, retVal){\n viewInfo(removedTrail);\n })\n }\n // Simply update the trail if it still has users in it.\n else{\n TrailClient\n .updateTrail(removedTrail)\n .then(function (err, retVal) {\n viewInfo(removedTrail);\n })\n }\n\n }", "function removeUser(){\n\tfor(i in currentProject.members){\n\t\tif(currentProject.members[i].name == savedMem){\n\t\t\tfor (j in currentProject.members[i].role) {\n\t\t\t\tdelete currentProject.members[i].name;\n\t\t\t\tdelete currentProject.members[i].role[j];\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t}\n\tdocument.getElementById(\"EditUser\").style.display = \"none\";\n\tpopTable();\n}", "deleteUserFromFriendlist({ params }, res) {\n User.findOneAndUpdate(\n { _id: params.userId },\n { $pull: { friends: params.friendId } },\n { new: true, runValidators: true }\n )\n .then(dbUserData => {\n if (!dbUserData) {\n res.status(404).json({ message: 'No user found with this id!' });\n return;\n }\n res.json(dbUserData);\n })\n .catch(err => res.status(400).json(err));\n }", "function unfollowUser(req ,res) {\n var userId1 = req.params.userId1;\n var userId2 = req.params.userId2;\n userModel\n .unfollowUser(userId1 , userId2)\n .then(function (user) {\n userModel\n .unfollowingUser(userId2 , userId1)\n .then(function (fake) {\n res.send(user);\n },function (err) {\n response.status=\"KO\";\n response.description=\"Unable to un follow the given user\";\n res.json(response);\n });\n } , function (err) {\n response.status=\"KO\";\n response.description=\"Unable to unfollow the given user\";\n res.json(response);\n });\n }", "function removeUserFromTable(userId){\n let userListRows = $userListTable.childNodes\n let userListLength = userListRows.length\n for(let i = 1; i < userListLength; i++){\n let row = userListRows[i]\n if(row.getAttribute('user-id') == userId){\n $userListTable.removeChild(row)\n break\n }\n }\n}", "deleteFriendRequest(thisUserId,fromUserId,callback){\n\n this.Model.User.findOne({'_id' : thisUserId} , function(err,user){\n /*If there is any error throw it*/\n if (err){\n throw err;\n }\n\n /*Remove that particular friend request*/\n for (var i=0; i < user.friendRequests.length; i++){\n if (user.friendRequests[i].fromId == fromUserId){\n user.friendRequests.splice(i,1);\n break;\n }\n }\n\n /*Store user back to database*/\n user.save(function(err){\n /*If there is any error throw it*/\n if (err){\n throw err;\n }\n callback();\n });\n\n });\n\n }", "function goout_users(out_users) {\n for (var j = users.length - 1; j > 0; j--) {\n for (var i = 0; i < out_users.length; i++) {\n if (users[j].id == out_users[i].id) {\n //$(otherVideoBoxs[users[j].boxIndex]).attr('easyrtc-id', '').css('display', 'none');\n users[j].element.remove();\n users.splice(j, 1);\n break;\n }\n }\n }\n}", "removeUser (user) {\n if (this.state.filteredUsers.length !== 0) {\n const users = this.state.filteredUsers.filter((oneuser) => oneuser._id !== user)\n this.setState({ filteredUsers: users })\n }\n }", "function removeUser(id)\n\t{\n\t\tvar tempArray = [];\n\n\t\tfor (var i = 0, l = userAuthors.length; i < l; i++)\n\t\t{\n\t\t\tif ( userAuthors[i] !== id)\n\t\t\t{\n\t\t\t\ttempArray.push(userAuthors[i]);\n\t\t\t}\n\t\t}\n\n\t\t//reset array with new array, missing removed id\n\t\tuserAuthors = tempArray;\n\n\t\t//change primaryAuthor\n\t\tprimaryAuthor = ( primaryAuthor !== id ) ? primaryAuthor : 0;\n\n\t\t//send\n\t\tparseFieldData('out');\n\t}", "function removeUserFromDom( userId ) {\n $(`.user-name-object[data-id=\"${userId}\"]`).remove();\n }", "function ProfileCardUnFollow(){\n PeopleService.UnFollow($rootScope.UserCard.id)\n .then(\n resolve => {\n $rootScope.UserCard.fav = false ;\n $rootScope.User.favs = resolve.data ;\n }\n );\n }", "removeUsers() {\n // Remove the admin from the list\n const membersToRemove = _.without(this.state.selectedEmployees, this.props.session.email);\n removeMembers(membersToRemove, this.props.route.params.policyID);\n this.setState({\n selectedEmployees: [],\n isRemoveMembersConfirmModalVisible: false,\n });\n }", "function handleOwnerRemove() {\n // Reload the grouping if you are not removing yourself, or if deleting anyone from the admins page\n if ($scope.currentUser !== $scope.userToRemove.username || !_.isUndefined($scope.adminsList)) {\n $scope.getGroupingInformation();\n $scope.syncDestArray = [];\n } else if ($scope.currentUser === $scope.userToRemove.username) {\n // Removing self from last grouping owned -> redirect to home page\n if ($scope.groupingsList.length === 1) {\n $window.location.href = \"home\";\n } else {\n $window.location.href = \"groupings\";\n }\n }\n }", "function _unFollow(){\n var btn;\n\n // Go to top\n window.scrollTo(0,0);\n // Get only those span's containing \"FOLLOWS YOU\"\n var spanArray = document.getElementsByClassName(\"FollowStatus\");\n for(var i = 0; i < spanArray.length; i++) {\n // Now navigate to the conatiner containing span \"FOLLOWS YOU\" and the Following Button\n var container = document.getElementsByClassName(\"FollowStatus\")[i].parentNode.parentNode.parentNode;\n // Get the following button, and click it to unfollow\n btn = container.getElementsByClassName(\"user-actions-follow-button js-follow-btn\")[0];\n btn.click();\n\n /*\n * TEST CASE: This is a test case. To be used while development. This test case\n * changes the background color of the \"Following\" buttons.\n */\n // common.test(btn, \"red\");\n }\n // Success message\n alert(\"Unfollowed only those who follow you!\");\n }", "function onUserOut(id) {\n\n for(var i=0; i<users.length; i++) {\n\n if (users[i].bodyId == id) {\n users[i].line.remove();\n users.splice(i, 1);\n break;\n }\n }\n}", "\"groceryLists.removeItem\"(_id, item) {\n if (!this.userId) {\n throw new Meteor.Error(\"Not authorized\");\n }\n \n GroceryLists.update(\n {\n $or: [ \n { _id: _id, userId: this.userId }, \n { _id: _id, collaborator: { $in: [this.userId] } } ]\n },\n {\n $pull: {\n items: {\n _id: item\n }\n },\n $set: {\n lastUpdated: new Date().getTime()\n }\n }\n );\n }", "function remove() {\n // REMOVE FROM DB\n let uid = $rootScope.account.authData.uid;\n $rootScope.db.users.child(uid).remove();\n }", "async removeFavourite (req, res) {\n try {\n if (req.body.user === req.session.user.user) {\n const newUser = await User.findOne({\n email: req.body.user\n })\n\n // Check if favourite exists then add\n for (let i = 0; i < newUser.favourites.length; i++) {\n if (req.body.url === newUser.favourites[i].url) {\n newUser.favourites.splice(i, 1)\n await newUser.save()\n res.send(['Add successfully removed from favourites.'])\n }\n }\n } else {\n res.send(['You are not logged in'])\n }\n } catch (err) {\n res.send(['error'])\n }\n }", "function deleteUser(event) {\n var removeBtn = $(event.target);\n var removeIndex = removeBtn.attr(\"id\").split('-')[1];\n var removeUserId = users[removeIndex]._id;\n try {\n userService\n .deleteUser(removeUserId)\n .then(function () {\n users.splice(removeIndex, 1);\n renderUsers(users);\n });\n }\n catch (err) {\n console.log(err.name + \": \" + err.message);\n }\n }", "function removeUserArticle(user) {\n document.querySelector(`[data-id=\"${user.id}\"]`).remove();\n}", "function removeUser(socketid){\n for(let i = 0; i < users.length; i++){\n if(users[i].id === socketid ) {\n let uname = users[i].user_name;\n users.splice(i,1);\n io.emit(\"chat message\", socketid, createFullMessage(socketid,\"Server\",`${uname} has disconnected`),userColor);\n io.emit(\"updateUserList\", users);\n }\n }\n}", "function deleteFollower( openId, pubAccoutId ){\n\n\tvar query= new AV.Query(Follower);\n\tquery.equalTo(\"openId\", openId );\n\n\tquery.find({\n \t\tsuccess: function(results) {\n \t\t\tconsole.log(\"Successfully retrieved \" + results.length + \" Follower.\");\n \t\t\t\t // process the result\n \t\t\t\tfor (var i = 0; i < results.length; i++) {\n \t\t\t\t\tvar object = results[i];\n\t\t\t\t\t//first delete related user\n\t\t\t\t\tvar queryUser =new AV.Query(AV.User);\n\t\t\t\t\tqueryUser.equalTo(\"followerId\", object.id);\n\t\t\t\t\tqueryUser.find({\n\t\t\t\t\t\tsuccess: function(results){\n\t\t\t\t\t\t for(var j=0; j< results.length; j++){\n\t\t\t\t\t\t\t var object=results[j];\n\t\t\t\t\t\t\t\t console.log(\"user found \"+object);\n\t\t\t\t\t\t\t object.destroy({\n\n\t\t\t\t\t\t\t\tsuccess: function(myObject) {\n \t\t\t\t\t\t\t\t\tconsole.log(\"user destroy success\");\n \t\t\t\t\t\t\t\t\t},\n \t\t\t\t\t\t\t\terror: function(myObject, error) {\n \t\t\t\t\t\t\t\t\tconsole.log(\"destory user failed.\"+ error.message);\n \t\t\t\t\t\t\t\t\t} \t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t } \n\n\t\t\t\t\t\t},\n\t\t\t\t\t\terror: function(error){\n\t\t\t\t\t\t\tconsole.log(\"find user failed\");\n\t\t\t\t\t\t},\n\t\t\t\t\t})\n\n \t\t\t\t\tobject.destroy({\n \t\t\t\t\t\tsuccess: function(myObject) {\n \t\t\t\t\t\tconsole.log(\"destroy success\");// 对象的实例已经被删除了.\n \t\t\t\t\t\t},\n \t\t\t\t\t\terror: function(myObject, error) {\n \t\t\t\t\t\tconsole.log(\"destory failed.\");\n \t\t\t\t\t\t}\n\t\t\t\t\t\t});\n \t\t\t\t}\n \t\t\t},\n \t\terror: function(error) {\n \t\t\tconsole.log(\"Error: \" + error.code + \" \" + error.message);\n \t\t\t}\n\n\n\t\t})\n}", "function deletFriend(e, index) {\n const FriendList = friendsList;\n FriendList.splice(index, 1);\n setFriendsList([...FriendList]);\n const deletedFriendIndex = duplicate2.indexOf(e);\n const deleteFromUser = e.friends.indexOf(activeaResponse.id);\n duplicate2[deletedFriendIndex].friends.splice(deleteFromUser, 1);\n duplicate2[loginUserIndex].friends.splice(index, 1);\n activeaResponse.friends.splice(index, 1);\n localStorage.setItem(\"Users\", JSON.stringify(duplicate2));\n localStorage.setItem(\"Active_User\", JSON.stringify(activeaResponse));\n }", "function removeRecipient(user, recipients) {\n var index = recipients.indexOf(user.email);\n if (index >= 0) {\n recipients.splice(index, 1);\n }\n }", "async removeList(req,res){\n const {id} = req.params;\n const response = await user.findById(req.userId);\n if(response.userType === 'comum'){ \n await GitUserList.findByIdAndRemove(id);\n res.sendStatus(200);\n }\n else{\n res.status(400).json({error: 'User does not have permission'});\n }\n }", "function Display_removeChatUser(_id) {\n\tvar chatUser = document.getElementById(_id);\n\tvar chatUserList = document.getElementById(\"chatUserList\");\n\tchatUserList.removeChild(chatUser);\n}", "function removeUser(user) {\n $(\"#usersList option\").each(\n function () {\n if ($(this).val() === user) $(this).remove();\n });\n}", "static async remove (trackIdsToRemove = [], userIdsToRemove = []) {\n // Get tracks from param and by parsing through user tracks\n const tracks = await this.getTracksFromUsers(userIdsToRemove)\n trackIdsToRemove = [...tracks.map(track => track.blockchainId), ...trackIdsToRemove]\n\n // Dedupe trackIds\n const trackIds = new Set(trackIdsToRemove)\n\n // Retrieves CIDs from deduped trackIds\n const segmentCIDsToRemove = await this.getCIDsFromTrackIds([...trackIds])\n\n try {\n await this.removeFromRedis(REDIS_SET_BLACKLIST_TRACKID_KEY, trackIdsToRemove)\n await this.removeFromRedis(REDIS_SET_BLACKLIST_USERID_KEY, userIdsToRemove)\n await this.removeFromRedis(REDIS_SET_BLACKLIST_SEGMENTCID_KEY, segmentCIDsToRemove)\n } catch (e) {\n throw new Error(`Failed to remove from blacklist: ${e}`)\n }\n }", "function removeUser(id){\r\n\tvar i;\r\n\tfor (i = 0; i < users.length; i++) { \r\n \tif(users[i].userID===id){\r\n \t\tusers.splice(i,1);\r\n \t\tconsole.log(\"index: \" + i);\r\n \t}\r\n\t}\r\n}", "async function unfollowRequestCall() {\n try {\n const response = await Axios.post(`/removeFollow/${state.profileData.profileUsername}`, { token: appState.user.token }, { cancelToken: unfollowRequest.token })\n setState(draft => {\n draft.profileData.isFollowing = false\n draft.profileData.counts.followerCount--\n draft.followActionRunning = false\n })\n } catch (error) {\n console.log(\"There was a problem unfollowing user or user cancelled\")\n }\n }", "function removeFromMylist() { return changeMylistState('remove',this); }", "remove() {\n let prev = this.prev;\n let next = this.next;\n if (prev) {\n this.prev.next = next;\n }\n if (next) {\n this.next.prev = prev;\n }\n }", "remove (user, callback) {\n\t\tthrow new Error ('Not yet implemented');\n\t}", "onDeleteUser(userid, cb) {\n\t\tlogger.debug(`delete user ${userid} for social`);\n\t\t// remove references to user ALL DOMAINS affected !\n\t\treturn this.colldomains.updateMany({ \"relations.friends\": userid }, { $pull: { \"relations.friends\": userid } })\n\t\t\t.then(() => this.colldomains.updateMany({ \"relations.blacklist\": userid }, { $pull: { \"relations.blacklist\": userid } }))\n\t\t\t.then(() => this.colldomains.updateMany({ \"relations.godchildren\": userid }, { $pull: { \"relations.godchildren\": userid } }))\n\t\t\t.then(() => this.colldomains.updateMany({ \"relations.godfather\": userid }, { $unset: { \"relations.godfather\": null } }))\n\t\t\t.then(() => cb(null))\n\t\t\t.catch(err => cb(err));\n\t}", "function removeUser (id){\n\n \n const removableIndex= users.findIndex((u)=>{\n return u.id === id\n })\n\n if(removableIndex!=-1){\n const removedUser = users.splice(removableIndex,1)[0];\n console.group(removedUser);\n return removedUser;\n\n }\n \n return null;\n\n \n}", "function userGone(details) {\n log_d(\"Got user left for user with details: \" + JSON.stringify(details));\n $('#userFeed' + details.userId).html('').remove();\n}", "function removeUser(res) {\n var name = res.match[2]\n , user = {name: name}\n , isCurrent = queue.isCurrent(user)\n , notifyNextUser = isCurrent && queue.length() > 1;\n\n if (name === 'me') {\n removeMe(res);\n return;\n }\n\n if (!queue.contains(user)) {\n res.send(name + ' isn\\'t in the queue :)');\n return;\n }\n\n queue.remove(user);\n res.send(name + ' has been removed from the queue. I hope that\\'s what you meant to do...');\n\n if (notifyNextUser) {\n notifyUser(queue.current());\n }\n }", "setFollowUserList(state) {\n state.userList.forEach((user) => {\n let userF = state.currentUser.following.find(\n (following) => following._idUser === user._idUser\n );\n if (userF) {\n state.followingUsers.push(user);\n } else {\n state.nonFollowingUsers.push(user);\n }\n });\n state.loading.following = false;\n state.loading.follow = false;\n }", "function deleteUser() {\n playersRef.child(thisIsPlayerNumberX).remove();\n // disableGamePlay();\n}", "function toClearUser() {\r\n $('.people-slider-message').remove(); \r\n $('.user-name').remove(); \r\n $('.user-position').remove(); \r\n $('.user-photo').remove(); \r\n}", "function removeUser(id) {\n\n var usersSpace = document.getElementById('space_for_users');\n var userToRemove = document.getElementById(id);\n\n usersSpace.removeChild(userToRemove);\n\n var count = getUsersCount();\n\n // Show message if no users\n if (count == 0) {\n document.getElementById('no-added-users').style.display = 'block';\n }\n\n return false;\n}", "async function deleteUser () {\n // delete user if exists in the saved list. input will be sent to the request\n await handleSaveList(\"/githubSearch/delete\", \"delete\",\n document.getElementById(\"inputBox\").value.trim());\n }", "function removeUser(name) {\n users = _.filter(users, function (u) {\n return u.name !== name;\n });\n }", "function removeUser(user) {\n\n // Get the user's ID.\n var id = user.id || user;\n\n var userName = $('#user-'+id).text();\n\n // Remove the corresponding element from the users list\n var userEl = $('#user-'+id).remove();\n\n // Re-append it to the body as a hidden element, so we can still\n // get the user's name if we need it for other messages.\n // A silly hack for a silly app.\n userEl.css('display', 'none');\n $('body').append(userEl);\n\n // Post a user status message if we're in a private convo\n if ($('#private-room-'+id).length) {\n postStatusMessage('private-messages-'+id, userName + ' has disconnected.');\n $('#private-message-'+id).remove();\n $('#private-button-'+id).remove();\n }\n\n}", "function removeUser (userId) {\n console.log('Removing user ', userId);\n const scene = document.getElementById('scene');\n const headToBeRemoved = document.getElementById(userId);\n console.log(`Attempting to remove ${userId}-body`);\n const bodyToBeRemoved = document.getElementById(`${userId}-body`);\n if (headToBeRemoved) {\n scene.remove(headToBeRemoved);\n headToBeRemoved.parentNode.removeChild(headToBeRemoved);\n }\n if (bodyToBeRemoved) {\n scene.remove(bodyToBeRemoved);\n bodyToBeRemoved.parentNode.removeChild(bodyToBeRemoved);\n }\n}", "remove({ getState, setState }, { payload }) {\n const state = getState();\n if (state && state.users) {\n setState({\n users: state.users.filter((u) => !(u.email === payload.email && u.name === payload.name)),\n });\n }\n }", "removeUser (id) {\n var user = this.getUser(id);\n\n if(user) {\n this.users = this.users.filter((user) => user.id !== id);\n }\n\n return user;\n }", "function UpdateUsers(userList) {\n users.empty();\n for (var i = 0; i < userList.length; i++) {\n if (userList[i].username != myName) {\n users.append('<li class=\"player\" id=\"' + userList[i].id + '\"><a href=\"#\">' + userList[i].username + '</a></li>')\n }\n }\n }", "del_friend(friend){\n if( this.friends.indexOf(friend) === -1)\n return 'friend doesnt exist';\n else {\n this.friends.splice( this.friends.indexOf(friend), 1);\n save_users(DEFAULT_USERS_FILE);\n return true;\n }\n }", "function sfjremovepmUser()\n{\n\tvar targetnames = document.getElementById('pmtonamelist');\n\tvar targetids = document.getElementById('pmtoidlist');\n\tvar i;\n\n\ttargetnames.remove(targetnames.selectedIndex);\n\t\n\ttargetids.value = '';\n\tfor(i=targetnames.options.length-1;i>=0;i--)\n\t{\n\t\ttargetnames.options[i].selected = true;\n\t\tif (targetids.value.length > 0)\n\t\t{\n\t\t\ttargetids.value += \", \";\n\t\t}\n\t\ttargetids.value += targetnames.options[i].value;\n\t}\n}", "function delete_user_if_exist_in_leaderboard(user) {\n for (let i = 0, len = leaderboard.length; i < len; i++) {\n // First step is check if the user is already on the leaderboard\n if (user.userID === leaderboard[i].userID) {\n leaderboard.splice(i, 1); // Delete the user\n // Once the user is deleted, we can now return a true and exit the function\n return true;\n }\n }\n }", "function removeLikes(book) {\n if (userLikes.includes(book.id)) {\n let index = userLikes.indexOf(book.id)\n userLikes.splice(index, 1)} \n }", "function removeFollowedCoachForAthlete(athleteId, coachId) {\n return UserModel.findById(athleteId)\n .then(function (athlete) {\n athlete.followedBy.pull(coachId);\n athlete.save();\n return athlete;\n })\n }", "function removeUserFromBar(req, res) {\n const query = { barId: req.params.id, userId: req.user.id };\n \n Going.findOneAndRemove(query, (err) => {\n if (err) {\n console.log('Error on removing user from bar');\n return res.status(500).send('We failed to remove the user for the bar');\n }\n\n return res.status(200).send('removed');\n });\n}", "function unFollow(id)\n{\n\t\t$.post(\"/follow/execute\", {\"unfollow\": \"yes\", \"id\": id},function(data)\n\t\t{\n\t\t\t\tif(data.state==\"success\")\n\t\t\t\t\t\tnotify(\"Vous ne suivez plus \" + data.unfollow +\".\");\n\t\t\t\telse\n\t\t\t\t\t\tnotify(\"Une erreur est survenue.\");\n\t\t} );\n}", "function removeFriendByID(req, res){\n var sessionID = userID;\n var currentID = parseInt(req.params.id);\n MongoClient.connect(\"mongodb://ezplan:12ezplan34@ds013916.mlab.com:13916/ezplan\", function(err, db){\n if(err){ res.send(err);}\n db.collection(\"friends\").update(\n {\n userid: sessionID\n },\n {\n $pull: {\n \"friends\": {\n userid: currentID\n }\n }\n }, function(err, doc){\n if(err){ res.send(err)}\n res.redirect('/friends');\n db.close();\n });\n });\n}" ]
[ "0.7917349", "0.78689265", "0.7410137", "0.7110647", "0.7074305", "0.6958612", "0.6936722", "0.68304014", "0.6809938", "0.68065923", "0.67217165", "0.66077363", "0.659144", "0.6582106", "0.6544967", "0.6510679", "0.6507983", "0.649706", "0.64764196", "0.64548826", "0.64028174", "0.64011514", "0.63808215", "0.6353591", "0.6338687", "0.6309474", "0.6286282", "0.6278281", "0.6267115", "0.6227236", "0.621923", "0.62168646", "0.62136805", "0.6209396", "0.6200906", "0.6199137", "0.619732", "0.61846197", "0.6183319", "0.6176725", "0.61675745", "0.6164994", "0.61639595", "0.6153298", "0.61390156", "0.6138053", "0.6126336", "0.6109945", "0.61067295", "0.6103102", "0.6101745", "0.6091305", "0.60870624", "0.60781693", "0.60697746", "0.60661775", "0.60545194", "0.6046337", "0.60454434", "0.6036468", "0.6014003", "0.60115325", "0.60042727", "0.60033715", "0.60007155", "0.59976375", "0.5978443", "0.59779656", "0.59652555", "0.5958584", "0.5953664", "0.59527695", "0.5950155", "0.59479886", "0.594603", "0.5935202", "0.5933352", "0.5932945", "0.591818", "0.5894855", "0.5890509", "0.5890479", "0.58882695", "0.58798444", "0.58741724", "0.5869199", "0.5867875", "0.5850852", "0.58421916", "0.5832447", "0.58296204", "0.5825797", "0.581435", "0.5805702", "0.58055973", "0.5802802", "0.5802259", "0.5760921", "0.5756623", "0.5745281" ]
0.68422747
7
SECURITY HELPERS, VALIDATION HELPERS
function isset(obj, val) { return !(obj === null || typeof obj === 'undefined' || typeof obj[val] === 'undefined'); }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "validate() {}", "function valida_user( ) /* OK */\r\n\t{\r\n \r\n\t}", "static validate(user) {\n return true\n }", "function valida_user2() /* OK */\r\n\t{\r\n \r\n\t}", "validate() {\n\t\t// Validate blog url\n\t\tconst parts = url.parse(this.url);\n\t\tif (!(parts.protocol && parts.host)) {\n\t\t\treturn new Error('INVALID_URL');\n\t\t}\n\n\t\t// Validate email (super basic, dependency free)\n\t\tif (this.user === undefined ||\n\t\t\tthis.user === '' ||\n\t\t\tthis.user.indexOf('@') <= 0 ||\n\t\t\tthis.user.indexOf('.') <= 0) {\n\t\t\treturn new Error('INVALID_USER');\n\t\t}\n\n\t\t// Validate data that should exist\n\t\tconst tests = ['pass', 'client', 'secret'];\n\t\tlet err = false\n\n\t\ttests.forEach((test) => {\n\t\t\tif (this[test] === undefined || this[test] === '') {\n\t\t\t\terr = err || new Error(`INVALID_${test.toUpperCase()}`);\n\t\t\t}\n\t\t});\n\n\t\t// Validate token. Handled by class\n\t\treturn err || this.token.validate();\n\t}", "validate() { }", "validate() {\n // Check required top level fields\n for (const requiredField of [\n 'description',\n 'organizationName',\n 'passTypeIdentifier',\n 'serialNumber',\n 'teamIdentifier',\n ])\n if (!(requiredField in this.fields))\n throw new ReferenceError(`${requiredField} is required in a Pass`);\n // authenticationToken && webServiceURL must be either both or none\n if ('webServiceURL' in this.fields) {\n if (typeof this.fields.authenticationToken !== 'string')\n throw new Error('While webServiceURL is present, authenticationToken also required!');\n if (this.fields.authenticationToken.length < 16)\n throw new ReferenceError('authenticationToken must be at least 16 characters long!');\n }\n else if ('authenticationToken' in this.fields)\n throw new TypeError('authenticationToken is presented in Pass data while webServiceURL is missing!');\n this.images.validate();\n }", "static checkSecurity (req, res) {\n res.status(200).send()\n }", "function validate() {\n return okusername && checkPass();\n}", "validate({ getState, action }, allow, reject) {\r\n let state = getState();\r\n if (!state.session.authenticated) {\r\n toastr.error('Unauthorized request');\r\n }\r\n if (state.session.user.userType != \"seeker\") {\r\n toastr.error(\"You don't have permission to edit listing, please register or login as a Seeker to submit or edit your listings\");\r\n } else {\r\n allow(action);\r\n }\r\n }", "isUserCredentialValid(name,password){\n\t\treturn true\n\t}", "function ValidateUserBySecurityInfo() {\n\n if (previousPage == 'DontRememberMyPassword') {\n return ValidateUserBySecurityInfoAndSendResetCode();\n } else if (previousPage == 'ForgotBothUsernameandPassword') {\n return ValidateUserBySecurityInfoAndSendUserName();\n } else if (previousPage == 'UnabletoAccessEmailAddress') {\n return UnabletoAccessEmailAddress();\n }\n return false;\n}", "async checkAttributes () {\n\t\t// must provide a password for confirmation if we don't already have one\n\t\tif (!this.user.get('passwordHash') && !this.request.body.password) {\n\t\t\tthrow this.errorHandler.error('parameterRequired', { info: 'password' });\n\t\t}\n\t\t// must provide a username for confirmation if we don't already have one\n\t\tif (!this.user.get('username') && !this.request.body.username) {\n\t\t\tthrow this.errorHandler.error('parameterRequired', { info: 'username' });\n\t\t}\n\t}", "checkAuth() { }", "_validate() {\n\t}", "function validate(){\n\n\t\t//TODO: make this work\n\n\n\t}", "isFieldLevelSecurity() {}", "function valid(){return validated}", "function validate(inst, validation) {}", "isValidate() { return !((!this.checkEmail()) || (!this.checkPassword())) }", "function _validateData() {\n const { identifier, password, ip } = user;\n var success = false;\n var error_name, error_code;\n\n if (\n identifier.length < 6 ||\n identifier.length > 254 ||\n identifier === \"undefined\"\n ) {\n error_name = \"username or email\";\n error_code = \"0003\";\n } else if (\n password.length < 8 ||\n password.length > 254 ||\n password === \"undefined\"\n ) {\n error_name = \"password\";\n error_code = \"0004\";\n } else if (!ipValidator(ip) || ip === \"undefined\") {\n error_name = \"ip\";\n error_code = \"0004\";\n } else {\n success = true;\n }\n //respuesta 409 - error del cliente\n switch (success) {\n case false:\n res.cookie(\"refreshToken\", null, {\n maxAge: 0,\n });\n res.status(400).send({\n error_code: `ERROR_SIGN_IN_${error_code}`,\n message: `Invalid ${error_name}.`,\n success: false,\n });\n return false;\n default:\n return true;\n }\n }", "validate(value) {\r\n if (value.toLowerCase().includes('password'))\r\n throw new Error('Password cannot contain password, come on');\r\n }", "selfValidate(){\n\n }", "async validateAttributes () {\n\t\tthis.userValidator = new UserValidator();\n\t\treturn this.validateEmail() ||\n\t\t\tthis.validatePassword() ||\n\t\t\tthis.validateUsername();\n\t}", "function Validate() {}", "function AuthorizationRequiredException() {}", "validate(value) {\n if (value.toLowerCase().includes(\"password\")) {\n // biar gak asal input password jadi password\n throw Error(\"Your password is invalid!\");\n }\n }", "function validation() {\r\n\t\t\r\n\t}", "function guard(){}", "claim(req, res, next) {\n req.checkBody('first_name', 'First name can\\'t be empty.').notEmpty();\n req.checkBody('last_name', 'Last name can\\'t be empty.').notEmpty();\n\n req.checkBody('password', 'Password must be at least 6 characters.').isLength({ min: 6 });\n req.checkBody('role', 'Must register with a role as an initiate or a member.').isSafeRole();\n\n req.checkBody('house', 'House must be red, green, or blue.')\n .isIn([Houses.RED, Houses.GREEN, Houses.BLUE]);\n\n req.checkBody('role', 'Role must be initiate or member.')\n .isIn([Roles.INITIATE, Roles.PENDING_MEMBER]);\n\n req.getValidationResult().then((result) => {\n if (!result.isEmpty()) {\n return res.status(400).json({ errors: result.array() });\n }\n\n next();\n });\n }", "auth(ctx, doc) {\n winston.warn(\n `${this.constructor.name} does not implement auth, disallowing.`\n );\n throw new Resource.ForbiddenError();\n }", "function validateAuthentication(req, res, next) {\n\tnext(); //continue processing the request\n}", "function Authentication() {\n//common functionality\n}", "function ensureUserValid(user) {\n function checkFields() {\n const keys = Object.keys(user);\n const validKeys = [\n 'title',\n 'description',\n 'preview',\n 'website',\n 'source',\n 'tags',\n ];\n const unknownKeys = difference(keys, validKeys);\n if (unknownKeys.length > 0) {\n throw new Error(\n `Site contains unknown attribute names=[${unknownKeys.join(',')}]`,\n );\n }\n }\n \n function checkTitle() {\n if (!user.title) {\n throw new Error('Site title is missing');\n }\n }\n \n function checkDescription() {\n if (!user.description) {\n throw new Error('Site description is missing');\n }\n }\n \n function checkWebsite() {\n if (!user.website) {\n throw new Error('Site website is missing');\n }\n const isHttpUrl =\n user.website.startsWith('http://') || user.website.startsWith('https://');\n if (!isHttpUrl) {\n throw new Error(\n `Site website does not look like a valid url: ${user.website}`,\n );\n }\n }\n \n function checkPreview() {\n if (\n !user.preview ||\n (user.preview instanceof String &&\n (user.preview.startsWith('http') || user.preview.startsWith('//')))\n ) {\n throw new Error(\n `Site has bad image preview=[${user.preview}].\\nThe image should be hosted on site, and not use remote HTTP or HTTPS URLs`,\n );\n }\n }\n \n function checkTags() {\n if (!user.tags || !(user.tags instanceof Array) || user.tags.includes('')) {\n throw new Error(`Bad showcase tags=[${JSON.stringify(user.tags)}]`);\n }\n const unknownTags = difference(user.tags, TagList);\n if (unknownTags.length > 0) {\n throw new Error(\n `Unknown tags=[${unknownTags.join(\n ',',\n )}\\nThe available tags are ${TagList.join(',')}`,\n );\n }\n }\n \n function checkOpenSource() {\n if (typeof user.source === 'undefined') {\n throw new Error(\n \"The source attribute is required.\\nIf your site is not open-source, please make it explicit with 'source: null'\",\n );\n } else {\n const hasOpenSourceTag = user.tags.includes('opensource');\n if (user.source === null && hasOpenSourceTag) {\n throw new Error(\n \"You can't add the opensource tag to a site that does not have a link to source code.\",\n );\n } else if (user.source && !hasOpenSourceTag) {\n throw new Error(\n \"For open-source sites, please add the 'opensource' tag\",\n );\n }\n }\n }\n \n try {\n checkFields();\n checkTitle();\n checkDescription();\n checkWebsite();\n checkPreview();\n checkTags();\n checkOpenSource();\n } catch (e) {\n throw new Error(\n `Showcase site with title=${user.title} contains errors:\\n${e.message}`,\n );\n }\n }", "function validateLogin(e, f, names){\r\n\t//implementation of login validation goes in here should the need arise\r\n\treturn true;\r\n}", "function checkParam() {\n // if course being accessed -> compare user to course\n if (req.params.id) {\n if (user.id === course.userId) {\n return true\n // if there's no match send 403(Forbidden) status code\n } else {\n res.status(403).send(`User: ${credentials.name} not authorized`)\n return false\n }\n // if user being accessed check if user exists\n } else if (user) {\n return true\n } else {\n return false\n }\n }", "async testOperationSecurity(req) {\n\t\treturn {\n\t\t\tresponse: req.scope || \"authentication succeeded!\",\n\t\t};\n\t}", "whenValid() {\n\n }", "function validateUser(req, res, next)\n{\n getUserFromTokenOrError(req, res, next)\n next()\n}", "function data_valid() {\n\tif (passName === true && passPrivilege === true) {\n\t\tsubmit.disabled = false;\n\t} else {\n\t\tsubmit.disabled = true;\n\t}\n}", "function validate_user_data(data){\n\t\n\tconst user = {\n\t\tvalid:true,\n\t\tusername:\"\",\n\t\tpassword:\"12345678\", //disabled for testing\n\t\temail:\"\",\n\t\tadmin:false,\n\t\terror:[]\n\t};\n\t\n\t//username\n\tif(data.username && validator.isLength(data.username, {min:2, max:255})){\n\t\tuser.username = validator.stripLow(data.username);\n\t\tuser.username = validator.escape(user.username);\n\t\tuser.username = validator.trim(user.username);\n\t}else{\n\t\tuser.valid = false;\n\t\tuser.error.push({username:\"Unsername length is not within allowed range (2-255)\"});\n\t}\n\t\n\t//email\n\tif(data.email && validator.isLength(data.email, {min:6, max:100}) && validator.isEmail(data.email)){\n\t\tuser.email = validator.stripLow(data.email);\n\t\tuser.email = validator.escape(user.email);\n\t\tuser.email = validator.trim(user.email);\n\t}else{\n\t\tuser.valid = false;\n\t\tuser.error.push({email:\"Email is not valid / not withing allowed range (6-100)\"});\n\t}\n\t\n\t//password\n\t/*if(data.password && validator.isLength(data.password,{min:8,max:255})){\n\t user.password = data.password;\n\t }else{\n\t user.valid = false;\n\t user.error.push({password:\"Password length is not within allowed range (8-255)\"});\n\t }*/\n\t\n\tif(validator.isBoolean(data.admin)){\n\t\tuser.admin = validator.toBoolean(data.admin);\n\t}else{\n\t\tuser.valid = false;\n\t\tuser.error.push({admin:\"Admin value is an invalid boolean\"});\n\t}\n\t\n\treturn user;\n}", "function validate() {\n\n\tvar reqBody = locals.body;\n\n\tif (!reqBody.email)\n\t\tthrow new Error('Email is required!');\n\n\tif(!GenHelper.isvalidEmail(reqBody.email))\n\t\tthrow new Error('Email required a valid format!');\n\n\tif (!reqBody.password)\n\t\tthrow new Error('Password is required!');\n}", "validate({url}, second) {\n\t\tlet errors = {}\n const user = store.getState().user.get('id')\n\t\tif (!user) errors.url = translate('please_login')\n if (!url) errors.url = translate('url_cant_be_empty')\n else if (url && !isUrl(url)) errors.url = translate('something_wrong_with_this_url')\n\t\treturn errors\n\t}", "function Validate(){}", "function Validate(){}", "function validateCLP(perms: ClassLevelPermissions, fields: SchemaFields, userIdRegExp: RegExp) {\n if (!perms) {\n return;\n }\n for (const operationKey in perms) {\n if (CLPValidKeys.indexOf(operationKey) == -1) {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `${operationKey} is not a valid operation for class level permissions`\n );\n }\n\n const operation = perms[operationKey];\n // proceed with next operationKey\n\n // throws when root fields are of wrong type\n validateCLPjson(operation, operationKey);\n\n if (operationKey === 'readUserFields' || operationKey === 'writeUserFields') {\n // validate grouped pointer permissions\n // must be an array with field names\n for (const fieldName of operation) {\n validatePointerPermission(fieldName, fields, operationKey);\n }\n // readUserFields and writerUserFields do not have nesdted fields\n // proceed with next operationKey\n continue;\n }\n\n // validate protected fields\n if (operationKey === 'protectedFields') {\n for (const entity in operation) {\n // throws on unexpected key\n validateProtectedFieldsKey(entity, userIdRegExp);\n\n const protectedFields = operation[entity];\n\n if (!Array.isArray(protectedFields)) {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `'${protectedFields}' is not a valid value for protectedFields[${entity}] - expected an array.`\n );\n }\n\n // if the field is in form of array\n for (const field of protectedFields) {\n // do not alloow to protect default fields\n if (defaultColumns._Default[field]) {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `Default field '${field}' can not be protected`\n );\n }\n // field should exist on collection\n if (!Object.prototype.hasOwnProperty.call(fields, field)) {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `Field '${field}' in protectedFields:${entity} does not exist`\n );\n }\n }\n }\n // proceed with next operationKey\n continue;\n }\n\n // validate other fields\n // Entity can be:\n // \"*\" - Public,\n // \"requiresAuthentication\" - authenticated users,\n // \"objectId\" - _User id,\n // \"role:rolename\",\n // \"pointerFields\" - array of field names containing pointers to users\n for (const entity in operation) {\n // throws on unexpected key\n validatePermissionKey(entity, userIdRegExp);\n\n // entity can be either:\n // \"pointerFields\": string[]\n if (entity === 'pointerFields') {\n const pointerFields = operation[entity];\n\n if (Array.isArray(pointerFields)) {\n for (const pointerField of pointerFields) {\n validatePointerPermission(pointerField, fields, operation);\n }\n } else {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `'${pointerFields}' is not a valid value for ${operationKey}[${entity}] - expected an array.`\n );\n }\n // proceed with next entity key\n continue;\n }\n\n // or [entity]: boolean\n const permit = operation[entity];\n\n if (permit !== true) {\n throw new Parse.Error(\n Parse.Error.INVALID_JSON,\n `'${permit}' is not a valid value for class level permissions ${operationKey}:${entity}:${permit}`\n );\n }\n }\n }\n}", "static validate({settings, user: {email, username, password}}) {\n\n // Verify the email address of the user.\n if (!email) {\n return Promise.reject(errors.ErrMissingEmail);\n }\n\n // Create a settings model to use for validation.\n let settingsModel = new SettingsModel(settings);\n\n // Verify other properties of the user.\n return Promise.all([\n UsersService.isValidUsername(username, false),\n UsersService.isValidPassword(password),\n settingsModel.validate()\n ]);\n }", "function validate() {\n // Define the data object and include the needed parameters.\n let data = { Token: token };\n // Make the validate API call and assign a callback function.\n authService.Validate(data).then(validateCallback);\n}", "async validateVoter(voterId) {\n //VoterId error checking here, i.e. check if valid drivers License, or state ID\n if (voterId) {\n return true;\n } else {\n return false;\n }\n }", "function Security() {\n events.EventEmitter.call(this);\n}", "detailsValid() {\n const { username, password } = this.state\n return (\n username && !username.match(/\\W/) && password\n && password.indexOf(' ') === -1\n )\n }", "async _validateAndSanitize() {\n const oThis = this;\n\n if (oThis.currentUserId !== oThis.userId) {\n return Promise.reject(\n responseHelper.paramValidationError({\n internal_error_identifier: 'a_s_u_rb_1',\n api_error_identifier: 'invalid_params',\n params_error_identifiers: ['invalid_user_id'],\n debug_options: { currentUserId: oThis.currentUserId }\n })\n );\n }\n }", "function is_token_valid(access_token_str, user_email_str, disable_str)\n {\n // IF THE SECURITY FIX HAS NOT BEEN DISABLED\n if(disable_str !== \"d\" && disable_str !== \"D\")\n {\n let jwt = require(\"jsonwebtoken\");\n let user_data = jwt.decode(access_token_str, {complete:true});\n\n // IF TOKEN HAS BEEN TAMPERED WITH\n if(user_data === null)\n {\n return false;\n }\n \n let email_str_from_token = user_data.payload.email_str;\n\n if(email_str_from_token !== user_email_str)\n return false;\n }\n\n /*****************************************************************/\n // AT THIS POINT, EVERYTHING IS THE SAME PRE SECURITY FIX\n\n let my_token_functions = require(\"./createJWT.js\");\n\n try\n {\n if(my_token_functions.isExpired(access_token_str))\n {\n return false;\n }\n \n else\n {\n return true;\n }\n }\n \n catch(error)\n {\n console.log(error.message);\n return false;\n }\n }", "function is_token_valid(access_token_str, user_email_str, disable_str)\n {\n // IF THE SECURITY FIX HAS NOT BEEN DISABLED\n if(disable_str !== \"d\" && disable_str !== \"D\")\n {\n let jwt = require(\"jsonwebtoken\");\n let user_data = jwt.decode(access_token_str, {complete:true});\n\n // IF TOKEN HAS BEEN TAMPERED WITH\n if(user_data === null)\n {\n return false;\n }\n \n let email_str_from_token = user_data.payload.email_str;\n\n if(email_str_from_token !== user_email_str)\n return false;\n }\n\n /*****************************************************************/\n // AT THIS POINT, EVERYTHING IS THE SAME PRE SECURITY FIX\n\n let my_token_functions = require(\"./createJWT.js\");\n\n try\n {\n if(my_token_functions.isExpired(access_token_str))\n {\n return false;\n }\n \n else\n {\n return true;\n }\n }\n \n catch(error)\n {\n console.log(error.message);\n return false;\n }\n }", "validate(args) {\n if (!Roles.userIsInRole(Meteor.user(), [ 'admin' ])) {\n throw new Meteor.Error(\"that's not allowed\");\n }\n }", "__validateRegisterParams(username, password) {\n let errorMsg = null;\n if(username == null || password == null) {\n errorMsg = \"missing parameters (username/password)\";\n } else if(typeof(username) != typeof(password) || typeof(username) != 'string') {\n errorMsg = \"parameters (username/password) must be strings.\"\n }\n\n if(errorMsg) return errorMsg;\n\n username = username.trim();\n password = password.trim();\n\n if(username.length < 4 || username.length > 16) errorMsg = \"Error: username longer than 16 or shorter than 4 characters\";\n if(password.length < 8 || password.length > 36) errorMsg = \"Error: password longer than 36 or shorter than 8 characters\";\n\n return errorMsg;\n }", "async validUser() {\n const grantAcess = await this.verify();\n return grantAcess;\n }", "function validateAccountInfo() {\n if (!volunteerRegObject.emailAddress) {\n return false;\n }\n if (!volunteerRegObject.password) {\n return false;\n }\n if (!volunteerRegObject.reenteredPassword) {\n return false;\n }\n return true;\n}", "validateResponse (data) {\n\t\t// validate that we got back \"ourselves\", and that there are no attributes a client shouldn't see\n\t\tthis.validateMatchingObject(this.currentUser.user.id, data.user, 'user');\n\t\tthis.validateSanitized(data.user, UserTestConstants.UNSANITIZED_ATTRIBUTES_FOR_ME);\n\t}", "function ValidationService() {\n\t}", "function validation(){\n\tvar password= document.getElementById(\"password\").value\n\tvar username = document.getElementById(\"username\").value\n\n\tif (username == null || username == \"\") {\n\t\talert(\"Name must be filled out\")\n\t} else if(password == null || password == \"\") {\n\t\talert(\"The password must be filled\")\n\t} else if (password !== \"12345\") {\n\t\talert(\"INCORRECT password\")\n\t} else if(password == \"12345\" || username ==\"imelda\") {\n\t\talert(\"PREMIUM ACCESS\")\n\t}\n}", "async testOperationSecurityWithParameter(req) {\n\t\treturn {\n\t\t\tresponse: req.scope || \"authentication succeeded!\",\n\t\t};\n\t}", "function validateData(){\r\n\t var nmflag=validatename();\r\n\t var passflag=validatepassword();\r\n\t var hbflag=validatehobbies();\r\n\t if(nmflag && passflag && hbflag){\r\n\t\t displayData();\r\n\t }\r\n\t return false;\r\n }", "function studentValidator(req, res, next) {\n\tcheck(''+req.body.yearOfpassingClass12th).isInt;\n\tcheck(''+req.body.rollno).isInt;\n\tcheck(''+req.body.cgpa).isDecimal;\n\tnext();\n}", "function validate(req, res) {\n var token = req.headers.authorization;\n try {\n var decoded = jwt.verify(token, secret);\n } catch (e) {\n return authFail(res);\n }\n if(!decoded || decoded.auth !== 'magic') {\n return authFail(res);\n } else {\n return privado(res, token);\n }\n }", "function securityValidation(){\n\t\n\tvar security = document.getElementById(\"security\");\n\tif(security.value ===\"\")\n\t{\n\t\tdocument.getElementById(\"security_error\").innerHTML=\"**Please select a security question.\";\n\t\treturn false;\n\t\t\n\t}\n\telse{\n\t\t\n\t\tdocument.getElementById(\"security_error\").innerHTML=\"\";\n\treturn true;\n\t\t\n\t}\n\t\n\t\n}", "loginFormRules() {\n\n const usernameInput = document.getElementById(\"login-username\");\n const passwordInput = document.getElementById(\"login-password\");\n\n return [\n {\n inputEl: usernameInput,\n rules: [\n {\n isValid: !stringIsBlank(usernameInput.value),\n msg: \"Brukernavn er obligatorisk\"\n }\n ]\n }, {\n inputEl: passwordInput,\n rules: [\n {\n isValid: !stringIsBlank(passwordInput.value),\n msg: \"Passord er obligatorisk\"\n }\n ]\n }\n ]\n\n }", "function employeeValidation(textFirstName, textLastName, textUserName, textEmail, textPassword, role_id) {\n\tlet messages = [];\n\tlet isValid = true;\n\tlet feedback = \"\";\n\t\n\t// validate the firstname\n\tfeedback = validateFirstName(textFirstName);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\n\t// validate the lastname\n\tfeedback = validateLastName(textLastName);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\n\t// validate the username\n\tfeedback = validateUserName(textUserName);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\t\n\t// validate the email\n\tfeedback = validateEmail(textEmail);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\n\t// validate the password\n\tfeedback = validatePassword(textPassword);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\n\t// validate the Role\n\tfeedback = validateRole(role_id);\n\tif (feedback.trim().length > 0) {\n\t\tmessages.push(feedback);\n\t\tfeedback = \"\";\n\t}\n\t\n\tif(messages.length > 0) {\n\t\tisValid = false;\n\t\traiseAlert(403,messages);\n\t}\n\n\treturn isValid;\n}", "function security (req, res, next)\n{\n\tif (! has_started_serving_apis)\n\t{\n\t\tif (is_openbsd) // drop \"rpath\"\n\t\t\tpledge.init(\"error stdio tty prot_exec inet dns recvfd\");\n\n\t\thas_started_serving_apis = true;\n\t}\n\n\tconst api = url.parse(req.url).pathname;\n\n\t// Not an API !\n\tif ((! api.startsWith(\"/auth/v1/\")))\n\t\treturn next();\n\n\tconst cert\t\t\t= req.socket.getPeerCertificate(true);\n\tconst min_class_required\t= MIN_CERTIFICATE_CLASS_REQUIRED.get(api);\n\n\tif (! min_class_required)\n\t{\n\t\treturn END_ERROR (\n\t\t\tres, 404,\n\t\t\t\t\"No such API. Please visit: \"\t+\n\t\t\t\t\"<http://auth.iudx.org.in> for documentation.\"\n\t\t);\n\t}\n\n\tcert.serialNumber\t= cert.serialNumber.toLowerCase();\n\tcert.fingerprint\t= cert.fingerprint.toLowerCase();\n\n\tif (is_iudx_certificate(cert))\n\t{\n\t\tlet\tinteger_cert_class\t= 0;\n\t\tconst\tcert_class\t\t= cert.subject[\"id-qt-unotice\"];\n\n\t\tif (cert_class)\n\t\t{\n\t\t\tinteger_cert_class = parseInt(\n\t\t\t\tcert_class.split(\":\")[1],10\n\t\t\t) || 0;\n\t\t}\n\n\t\tif (integer_cert_class < 1)\n\t\t\treturn END_ERROR(res, 403, \"Invalid certificate class\");\n\n\t\tif (integer_cert_class < min_class_required)\n\t\t{\n\t\t\treturn END_ERROR (\n\t\t\t\tres, 403,\n\t\t\t\t\t\"A class-\" + min_class_required\t+\n\t\t\t\t\t\" or above certificate \"\t+\n\t\t\t\t\t\"is required to call this API\"\n\t\t\t);\n\t\t}\n\n\t\tif (api.endsWith(\"/introspect\") && integer_cert_class !== 1)\n\t\t{\n\t\t\treturn END_ERROR (\n\t\t\t\tres, 403,\n\t\t\t\t\t\"A class-1 certificate is required \" +\n\t\t\t\t\t\"to call this API\"\n\t\t\t);\n\t\t}\n\n\t\tconst error = is_secure(req,res,cert,true); // validate emails\n\n\t\tif (error !== \"OK\")\n\t\t\treturn END_ERROR (res, 403, error);\n\n\t\tpool.query(\"SELECT crl FROM crl LIMIT 1\", [], (error,results) =>\n\t\t{\n\t\t\tif (error || results.rows.length === 0)\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 500,\n\t\t\t\t\t\"Internal error!\", error\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst CRL = results.rows[0].crl;\n\n\t\t\tif (has_certificate_been_revoked(req.socket,cert,CRL))\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 403,\n\t\t\t\t\t\"Certificate has been revoked\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (! (res.locals.body = body_to_json(req.body)))\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 400,\n\t\t\t\t\t\"Body is not a valid JSON\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tres.locals.cert\t\t= cert;\n\t\t\tres.locals.cert_class\t= integer_cert_class;\n\t\t\tres.locals.email\t= cert\n\t\t\t\t\t\t\t.subject\n\t\t\t\t\t\t\t.emailAddress\n\t\t\t\t\t\t\t.toLowerCase();\n\n\t\t\treturn next();\n\t\t});\n\t}\n\telse\n\t{\n\t\tocsp.check({cert:cert.raw, issuer:cert.issuerCertificate.raw},\n\t\tfunction (err, ocsp_response)\n\t\t{\n\t\t\tif (err)\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 403,\n\t\t\t\t\t\"Your certificate issuer did \"\t+\n\t\t\t\t\t\"NOT respond to an OCSP request\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (ocsp_response.type !== \"good\")\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 403,\n\t\t\t\t\t\"Your certificate has been \"\t+\n\t\t\t\t\t\"revoked by your certificate issuer\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Certificates issued by other CAs\n\t\t\t// may not have an \"emailAddress\" field.\n\t\t\t// By default consider them as a class-1 certificate\n\n\t\t\tconst error = is_secure(req,res,cert,false);\n\n\t\t\tif (error !== \"OK\")\n\t\t\t\treturn END_ERROR (res, 403, error);\n\n\t\t\tres.locals.cert_class\t= 1;\n\t\t\tres.locals.email\t= \"\";\n\n\t\t\t// but if the certificate has a valid \"emailAddress\"\n\t\t\t// field then we consider it as a class-2 certificate\n\n\t\t\tif (is_valid_email(cert.subject.emailAddress))\n\t\t\t{\n\t\t\t\tres.locals.cert_class\t= 2;\n\t\t\t\tres.locals.email\t= cert\n\t\t\t\t\t\t\t\t.subject\n\t\t\t\t\t\t\t\t.emailAddress\n\t\t\t\t\t\t\t\t.toLowerCase();\n\t\t\t}\n\n\t\t\tif (res.locals.cert_class < min_class_required)\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 403,\n\t\t\t\t\t\"A class-\" + min_class_required\t+\n\t\t\t\t\t\" or above certificate is\"\t+\n\t\t\t\t\t\" required to call this API\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tif (! (res.locals.body = body_to_json(req.body)))\n\t\t\t{\n\t\t\t\treturn END_ERROR (\n\t\t\t\t\tres, 400,\n\t\t\t\t\t\"Body is not a valid JSON\"\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tres.locals.cert\t= cert;\n\n\t\t\treturn next();\n\t\t});\n\t}\n}", "validate(value) {\n if (value.length < 6) {\n // if password too short or equals password, throw error\n throw new Error('password too short');\n // can use value.includes() can pass in multiple invalid passwords\n } else if (value === 'password') {\n throw new Error('pick a better password');\n }\n }", "async checkAuthentication(){\n let validity = await this.validateUserAgainstEmailAndToken(this.email, this.token, this.userCode, this.client, this.pm)\n return validity\n }", "async validate () {\n\t\tif (this.stream.get('teamId') !== this.teamId) {\n\t\t\tthrow this.errorHandler.error('streamNoMatchTeam', { info: this.streamId });\n\t\t}\n\t\tif (!this.fromUser.hasTeam(this.teamId)) {\n\t\t\tthis.log(`User ${this.fromUser.id} is not on team ${this.teamId}`);\n\t\t\tthrow this.errorHandler.error('unauthorized');\n\t\t}\n\t\tif (this.parentPost && this.parentPost.get('teamId') !== this.teamId) {\n\t\t\tthrow this.errorHandler.error('parentPostNoMatchTeam', { info: this.parentPostId });\n\t\t}\n\t\tif (this.parentPost && this.parentPost.get('streamId') !== this.streamId) {\n\t\t\tthrow this.errorHandler.error('parentPostNoMatchStream', { info: this.parentPostId });\n\t\t}\n\t}", "function handle_para(req,res) {\n username = req.body['username'];\n username = check_param(username);\n\n password = req.body['password'];\n password = check_param(password);\n \n action = req.body['action'];\n action = check_param(action);\n\n if (username == '' || password == '') { \n res.send(FAILED);\n return false;\n }\n return true; \n \n}", "function LoginController() {\n function isValidUserId(userList, user) {\n return userList.indexOf(user) >= 0;\n }\n\n return {\n isValidUserId\n }\n}", "function validateCredentials() {\n if(usernameInput.value.toLowerCase() === username) {\n if(passwordInput.value === password) {\n return true;\n } \n } \n return false;\n}", "validateForm() {\n\t\treturn this.props.user.username.length > 0\n\t\t\t&& this.props.user.password.length > 0;\n\t}", "function checkCreds() {\n checkEmail();\n return false;\n }", "checkLoginInfo(loginInfo){\n //check use name is empty\n if(typeof loginInfo.username !== 'string' || loginInfo.username.length === 0){\n return {\n status : false,\n msg: 'username can not be empty'\n }\n }\n //check password name is empty\n \n if(typeof loginInfo.password !== 'string' || loginInfo.password.length === 0){\n return {\n status : false,\n msg: 'password can not be empty'\n }\n }\n return {\n status : true,\n msg: 'login success'\n }\n }", "async function ensureValidReviewUser(req, res, next) {\n\ttry {\n\t\tlet userProjects;\n\t\t// check is user_type if \"user\" or \"tradesman\" - used to determine which model to call\n\t\tif (req.user.user_type === \"user\") {\n\t\t\tuserProjects = await Projects.allUser(req.user.id);\n\t\t} else {\n\t\t\tconst err = new ExpressError(`Unauthorized`, 401);\n\t\t\treturn next(err);\n\t\t}\n\n\t\t// checks if the project id is included in the userProjects list.\n\t\t// only allow user to proceed if a valid id is found\n\t\tfor (let project of userProjects) {\n\t\t\tif (project.id === +req.params.projectId) {\n\t\t\t\treturn next();\n\t\t\t}\n\t\t}\n\t\tconst err = new ExpressError(`Unauthorized`, 401);\n\t\treturn next(err);\n\t} catch (e) {\n\t\t// errors would happen here if we made a request and req.user is undefined or if user has not chat associated with them\n\t\tconst err = new ExpressError(`Unauthorized`, 401);\n\t\treturn next(err);\n\t}\n}", "securityContext(tagName, propName, isAttribute) {\n if (isAttribute) {\n // NB: For security purposes, use the mapped property name, not the attribute name.\n propName = this.getMappedPropName(propName);\n }\n // Make sure comparisons are case insensitive, so that case differences between attribute and\n // property names do not have a security impact.\n tagName = tagName.toLowerCase();\n propName = propName.toLowerCase();\n let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];\n if (ctx) {\n return ctx;\n }\n ctx = SECURITY_SCHEMA()['*|' + propName];\n return ctx ? ctx : SecurityContext.NONE;\n }", "securityContext(tagName, propName, isAttribute) {\n if (isAttribute) {\n // NB: For security purposes, use the mapped property name, not the attribute name.\n propName = this.getMappedPropName(propName);\n }\n // Make sure comparisons are case insensitive, so that case differences between attribute and\n // property names do not have a security impact.\n tagName = tagName.toLowerCase();\n propName = propName.toLowerCase();\n let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];\n if (ctx) {\n return ctx;\n }\n ctx = SECURITY_SCHEMA()['*|' + propName];\n return ctx ? ctx : SecurityContext.NONE;\n }", "securityContext(tagName, propName, isAttribute) {\n if (isAttribute) {\n // NB: For security purposes, use the mapped property name, not the attribute name.\n propName = this.getMappedPropName(propName);\n }\n // Make sure comparisons are case insensitive, so that case differences between attribute and\n // property names do not have a security impact.\n tagName = tagName.toLowerCase();\n propName = propName.toLowerCase();\n let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];\n if (ctx) {\n return ctx;\n }\n ctx = SECURITY_SCHEMA()['*|' + propName];\n return ctx ? ctx : SecurityContext.NONE;\n }", "securityContext(tagName, propName, isAttribute) {\n if (isAttribute) {\n // NB: For security purposes, use the mapped property name, not the attribute name.\n propName = this.getMappedPropName(propName);\n }\n // Make sure comparisons are case insensitive, so that case differences between attribute and\n // property names do not have a security impact.\n tagName = tagName.toLowerCase();\n propName = propName.toLowerCase();\n let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];\n if (ctx) {\n return ctx;\n }\n ctx = SECURITY_SCHEMA()['*|' + propName];\n return ctx ? ctx : SecurityContext.NONE;\n }", "checkInputs() {\n\t\treturn this.state.username && this.state.pass;\n\t}", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }", "canHandleAuthentication() {\n return false;\n }" ]
[ "0.63785255", "0.6327356", "0.6284442", "0.62311065", "0.62109786", "0.62055683", "0.6107432", "0.6044219", "0.5995475", "0.5985471", "0.59804684", "0.5972507", "0.59089386", "0.5908345", "0.58853257", "0.5846593", "0.58446574", "0.5832925", "0.5783657", "0.577195", "0.57547045", "0.57508105", "0.5743072", "0.5723777", "0.5683608", "0.5679908", "0.5678124", "0.56754446", "0.5672246", "0.5667746", "0.5659895", "0.5631461", "0.5626198", "0.56198645", "0.56191796", "0.56032294", "0.5602662", "0.5590655", "0.5574872", "0.55679905", "0.5565511", "0.5564468", "0.55591416", "0.5547406", "0.5547406", "0.5524201", "0.55239016", "0.552316", "0.5521345", "0.55158806", "0.55134207", "0.5511326", "0.5508745", "0.5508745", "0.5504294", "0.5497201", "0.54948467", "0.54945827", "0.54534554", "0.5451661", "0.54370975", "0.5437074", "0.5421418", "0.54206", "0.5398023", "0.5395711", "0.5395678", "0.5390244", "0.5386142", "0.5379196", "0.53596413", "0.5354464", "0.5347145", "0.53467315", "0.53461444", "0.53431314", "0.53420705", "0.5341954", "0.5341585", "0.533804", "0.533804", "0.533804", "0.533804", "0.53317285", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143", "0.5329143" ]
0.0
-1